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-62871
https://emacs.stackexchange.com/questions/62871
How to do local keymap with use-package
2021-01-19T02:51:29.213
# Question Title: How to do local keymap with use-package I want to bind the `verb` package's keymap within `org-mode`. Currently, I am using the `with-eval-after-load` function in the `:init` option. ``` (use-package org-plus-contrib :ensure t :init (require 'org-tempo) (with-eval-after-load 'org (define-key org-mode-map (kbd "C-c C-r") verb-command-map)) ) ``` It seems there's a `:bind-keymap` option for this. But I just cannot get it to work. After I defined the `:bind-keymap` option, it does not seem to have any effect. # Answer > 0 votes You can use the `:map` keyword within the `:bind` section. like this: ``` (use-package org-plus-contrib :ensure t :init (require 'org-tempo) :bind (:map org-mode-map ("C-c C-r" . verb-command-map)) ) ``` --- Tags: use-package ---
thread-62923
https://emacs.stackexchange.com/questions/62923
How can I bind a command to the F1 key?
2021-01-21T16:15:31.813
# Question Title: How can I bind a command to the F1 key? If I change: ``` (define-key org-mode-map (kbd "C-c d") 'org-toggle-todo-and-fold) ``` to eg: ``` (define-key org-mode-map (kbd "F1") 'org-toggle-todo-and-fold) ``` This doesn't work. Is there a way to map to F keys such as the F1 key? # Answer I think any key name that's more than one character needs to be be inside `<>`, so try ``` (define-key org-mode-map (kbd "<f1>") 'org-toggle-todo-and-fold) ``` > 5 votes # Answer Thank you for taking the time to help. Your answer is correct in that F keys need to be enclosed in \<\> brackets. This is very helpful. I had assumed though that F1 was available in emacs but it is already bound. I then found that F5 to F9 are available to the user. This is outlined at https://www.gnu.org/software/emacs/manual/html\_node/elisp/Key-Binding-Conventions.html I also found that a lower case f must be used eg `"<f5>"` Since `kbd "<F1>"` would not fully work because: 1. F1 is bound 2. It needs to be lower case I thought I would add an answer that is more complete because if I left a comment to your answer, it may not be obvious to people to see. So: ``` (define-key org-mode-map (kbd "<f5>") 'org-toggle-todo-and-fold) ``` does work fully. I don't mean to "steal" someone's answer though :) > 1 votes --- Tags: key-bindings ---
thread-62933
https://emacs.stackexchange.com/questions/62933
Search for text, print a message about it, and then return cursor to original position
2021-01-22T00:33:38.103
# Question Title: Search for text, print a message about it, and then return cursor to original position I want to write an Elisp command that searches for a specific string in the backward direction, pauses the cursor there for a second, echoes a message about that occurrence, and then returns the cursor back to its original position. The purpose of the command is to *examine the contents surrounding* the search string. My text is structured like below: ``` \begin{myverse} line one of verse line two of verse ॥ 3.2 ॥ \\ \end{myverse} \vspace{2mm} Lots of text below over multiple lines cursor here ``` If my cursor is at the last line (`cursor here`), I would like the Elisp function to search backwards for the first occurrence of the text , pause for a bit so that I can read the number (**3.2**), and then return the cursor back to its previous position. I have the following command: ``` (defun fn () "Retrieve verse number" (interactive) (setq test-str "॥") (save-excursion (search-backward test-str) (sit-for 1))) ``` How can this command be enhanced so that it that prints the verse number in the echo area (i.e. where I type `M-x fn`)? # Answer > 2 votes I guess you want this. This matches the text between the markers and makes it a message in the minibuffer when it is found. ``` (defun fn () (interactive) (save-excursion (when (re-search-backward "॥\\(.*\\)॥" nil t) (message (match-string 1)) (sit-for 1)))) ``` # Answer > 1 votes You can get behavior similar to what you want by just using backward *incremental* search (`C-r`, or `C-M-r` for regexp-searching). That takes you to the first search hit (and you can repeat the key to move to subsequent hits). This lets you see the search hit in context, which I guess is what your aim is. You can then just use `C-g` to cancel searching -- that returns the cursor to the starting point. (If you instead want to leave the cursor at a search hit, just use `RET` when you get to that hit.) # Answer > 0 votes Your Q is a bit mixed up as at the end of it you've asked for something not related to the title, but all good. Looking at your text structure wouldn't it not be a better idea to search backwards for text enclosed by your special format char? eg ॥ FINDME ॥ And this is where you can have some fun reading the man page for re-search-backward Of course, there are edge cases to sort out at a later date eg starting the search while inside your special grouping. But that's a separate issue for now. --- Tags: search, motion ---
thread-62948
https://emacs.stackexchange.com/questions/62948
How do I change the default indentation of 'if' for Common Lisp and Scheme?
2021-01-23T02:04:35.720
# Question Title: How do I change the default indentation of 'if' for Common Lisp and Scheme? When I am using `(setq lisp-indent-function 'common-lisp-indent-function)`, the `if`s are indented like this: ``` (if x y z) ``` For Scheme, `(setq lisp-indent-function 'scheme-indent-function)` also produces the same indentation as above. I would prefer `if`s to be indented like this instead: ``` (if x y z) ``` Is there a way to customize `common-lisp-indent-function` and `scheme-indent-function` such that `if`s will be indented by two spaces instead of being aligned with the predicate? # Answer > 1 votes Yes, there is. There are a few customization suggestions for `common-lisp-indent-function` inside cl-indent.el. The same mechanism is used for `scheme-indent-function`. Place the following in your init file: ``` (put 'if 'scheme-indent-function 1) ``` To achieve the following indentation in a Scheme buffer: ``` (if foo bar baz) ``` --- Tags: indentation, common-lisp, scheme ---
thread-62951
https://emacs.stackexchange.com/questions/62951
GNUS says sending email failed, but mail was sent [Unable to open server nnimap]
2021-01-23T05:18:21.260
# Question Title: GNUS says sending email failed, but mail was sent [Unable to open server nnimap] I have tried solve this for many many hours ;( macOS 11.1, Emacs 27.1 (brew), Gnus 5.13, msmtp 1.8.14 (brew) I use GNUS to read maildir that is synced using mbsync. I can read mail using GNUS but sending gives me ``` Warning: Opening nnimap server on office365...failed: ; Unable to open server nnimap+office365 due to: office365/imaps nodename nor servname provided, or not known Sending... Sending via mail... Opening nnimap server on office365... Server nnimap+office365 previously determined to be down; not retrying Opening nnimap server on office365...failed: gnus-inews-do-gcc: Can\u2019t open server archive ``` The mail **is** sent but GNUS think it is not. I can send email from the command line without any error or warning, so this should not be a msmtp configuration problem ``` cat msmtp-test.txt | msmtp -a default my.mail@gmail.com ``` The msmtp exe pointed out by the sendmail-program is verified to be used. I tried just about everything, the simple ``` (setq sendmail-program "/usr/local/bin/msmtp") (setq send-mail-function 'message-send-mail-with-sendmail) (setq smtpmail-debug-info t smtpmail-debug-verb t) ``` and many other settings I found on various pages. Any hints what is going on or how to debug this is appreciated, kent # Answer It looks like 1. successful email sending itself 2. failed saving of sent message copy in IMAP Sent folder \[`nnimap server on office365`\] > 1 votes --- Tags: gnus, email, imap ---
thread-3911
https://emacs.stackexchange.com/questions/3911
Access menu-bar using keyboard on Mac OS X
2014-11-26T19:06:08.907
# Question Title: Access menu-bar using keyboard on Mac OS X When I hit `C-f2` in any Mac OS X app (e.g., terminal, firefox), I get keyboard access to the menu bar (file/edit/options &c) In emacs I get a message `<C-f2> is undefined` in the Echo Area. When I hit `f10` (`menu-bar-open`) in Emacs, get the 2 item menu `search with google` and `add to itunes as a spoken track` or sometimes the single grayed-out item menu `select`. * How do i get Emacs to pass `C-f2` to the OS? * How do I get `f10` to invoke the real menu in Emacs? # Answer Here is the solution: ``` (define-key global-map (kbd "C-<f2>") (lambda () (interactive) (x-popup-menu (list '(0 0) (selected-frame)) (mouse-menu-bar-map)))) ``` Also fixed in the source tree so that now `f10` does the right thing. This gives mouse-less access to the menu-bar *functionality*, not the OS menu *interface*, so the question of how to tell Emacs to pass certain keys to the OS remains open. > 3 votes # Answer This does work for me with `Fn ^F2` (control function F2) using YAMAMOTO Mitsuharu's "Emacs Mac Port", installed via Homebrew. More precisely, my current OS and emacs versions are ``` OS X 10.10.1 (14B25) GNU Emacs 24.4.1 (x86_64-apple-darwin14.0.0, Carbon Version 157 AppKit 1343.14) of 2014-10-21 on iris-mac.crya.privado ``` The `Fn ^F2` shortcut is intercepted by the OS and never gets to Emacs. It gives keyboard access to the menubar just as in other apps. You have presumably turned on the option "Use all F1, F2, etc keys as standard function keys" in the Keyboard sheet of System Preferences, so you can just type `^F2` without using the `Fn` key. > 0 votes # Answer Without any configuration: * **Ctrl-Alt-DownArrow** this selects the apple icon in the menu-bar. From them, move left or right using the right/left keys. This is for OSX 10.11.3 but maybe previous versions too? Please confirm! * **Cmd-?**: Out of the box, OS X 10.10 has the shortcut 'Cmd-?' (That is, 'Cmd-Shift-/') to access the Help menu of the menu bar. This opens the menu Help and put the cursor in the text box in the 'Search Help' menu item. From there, use the arrow keys to access other menus/menu items. > 0 votes # Answer To use the menu bar on a Mac you use F10. This can be accomplished by pressing the Fn button on a MacBook Pro and then pressing F10. > 0 votes --- Tags: key-bindings, osx, menu-bar ---
thread-62919
https://emacs.stackexchange.com/questions/62919
How to disable magit on remote files with tramp?
2021-01-21T12:40:55.193
# Question Title: How to disable magit on remote files with tramp? I'm working with Emacs on windows, I usually work locally, but I want to disable magit when I'm working on a remote file. I'm trying to add a hook that disables magit when it detects that the file is on a remote server. I tried this snippet but it freezes tramp everytime I try to open a remote file: ``` (use-package magit :ensure t :init (add-hook 'magit-mode-hook (lambda () (when (file-remote-p default-directory) (magit-mode -1))))) ``` # Answer I don't think Magit will be responsible for that; but `vc` might? See whether `vc-ignore-dir-regexp` helps. That has a default value of: ``` "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'" ``` For ease of editing and reading, let's use `rx` syntax. The excellent `xr` package on GNU ELPA gives me the following `rx` syntax for the default `vc-ignore-dir-regexp` value: ``` (seq bos (or (seq (any "/\\") (any "/\\") (one-or-more (not (any "/\\"))) (any "/\\")) (seq "/" (or "net" "afs" "...") "/")) eos))) ``` So let's try the following. I'm using `tramp-methods` to establish the remote path syntax possibilities. n.b. The position of the `(eval-when-compile (require 'tramp))` looks very odd, but our usage of the `rx` macro needs `tramp-methods` to be defined at byte-compile time, and this achieves that without unnecessarily loading tramp in other circumstances. We could alternatively use the `rx-to-string` function instead of the `rx` macro, but this way we retain the slight compile-time performance benefit. ``` (with-eval-after-load "tramp" (eval-when-compile (require 'tramp)) (setq vc-ignore-dir-regexp (rx (seq bos (or (seq (any "/\\") (any "/\\") (one-or-more (not (any "/\\"))) (any "/\\")) (seq "/" (or "net" "afs" "...") "/") ;; Ignore all tramp paths. (seq "/" (eval (cons 'or (mapcar #'car tramp-methods))) ":" (zero-or-more anything))) eos)))) ``` > 2 votes --- Tags: magit, tramp ---
thread-62963
https://emacs.stackexchange.com/questions/62963
Since update to org-mode 9.4 misaligned column view headers
2021-01-23T16:53:54.353
# Question Title: Since update to org-mode 9.4 misaligned column view headers I updated org-mode to 9.4. When I enter column view, the header is not in the correct size, so table columns are not below the respective header field. I use different font sizes for different org-heading levels. But untill now in column-view everything was just the same font. Now it seems as if the lines inherit their respective org-level font size. What does cause this and how can I make it return to normal proportions? # Answer > 2 votes Got it: the faces `org-column` and `org-column-title` had no font and size set. After setting it to a Monospace font, the columns align. But I'm sure, it worked before without specifying. Don't know what changed. --- Tags: org-mode, formatting, column ---
thread-62952
https://emacs.stackexchange.com/questions/62952
Creating a Bookmark Handler for eww
2021-01-23T09:07:13.270
# Question Title: Creating a Bookmark Handler for eww I'm attempting to create a bookmark handler for eww so I can use Emacs's built-in bookmarks to save and visit urls with eww. There's an equivenant setup for w3m here: https://github.com/TotalView/dotemacs/blob/master/.emacs.d/elpa/w3m-20140330.1933/bookmark-w3m.el From what I can gather I need to: * Create a function to actually make a properly formatted bookmark entry. * Find a way to grab all the data you need to create the bookmark from eww. * Set bookmark-make-record-function to that function. * Make a bookmark 'handler' which launches eww with the bookmark's url. So far I've got the following setup. However, I'm getting the error `oht-eww-bookmark-make-record: Symbol’s value as variable is void: oht-eww-current-title` ``` (defun oht-eww-current-title () "Returns the title of the current eww buffer" (plist-get eww-data :title)) (defun oht-eww-bookmark-make-record () "Return a bookmark record for the current eww buffer." (interactive) `(,oht-eww-current-title (location . ,eww-current-url) (handler . ,oht-eww-bookmark-handler))) (defun oht-eww-set-bookmark-handler () "Set local variable to call function to save eww bookmark" (interactive) (set (make-local-variable 'bookmark-make-record-function) #'oht-eww-bookmark-make-record)) (defun oht-eww-bookmark-handler (record) "Jump to an eww bookmarked location." (eww (bookmark-prop-get record 'location))) ``` # Answer > 0 votes Seems like I just got the syntax wrong for the `oht-eww-bookmark-make-record` function. The below is a complete working solution. ``` (defun oht-eww-current-title () "Returns the title of the current eww buffer" (plist-get eww-data :title)) (defun oht-eww-bookmark-make-record () "Return a bookmark record for the current eww buffer." (interactive) `(,(oht-eww-current-title) (location . ,(eww-current-url)) (handler . oht-eww-bookmark-handler))) (defun oht-eww-set-bookmark-handler () "This tells Emacs which function to use to create bookmarks." (interactive) (set (make-local-variable 'bookmark-make-record-function) #'oht-eww-bookmark-make-record)) (defun oht-eww-bookmark-handler (record) "Jump to an eww bookmarked location." (eww (bookmark-prop-get record 'location))) (add-hook 'eww-mode-hook 'oht-eww-set-bookmark-handler) ``` --- Tags: eww ---
thread-62740
https://emacs.stackexchange.com/questions/62740
How to insert and right-align text that is not of the default font size?
2021-01-12T20:53:18.543
# Question Title: How to insert and right-align text that is not of the default font size? How to insert and right-align text that is not of the default font size? This doesn't work: ``` (let* ((text "abcd") (len (length text))) (insert "\n" (propertize " " 'display `((height 0.5) (space :align-to (- right (,len . width))))) (propertize "12345" 'font-lock-face 'error 'display '(height 0.5)) "\n")) ``` # Answer The example in the question works fine. There's a bug in Emacs 27.1 that makes it fail. See the discussion on the mailing list: Why is `(1 . width)` zero?. > 1 votes --- Tags: text-properties ---
thread-62716
https://emacs.stackexchange.com/questions/62716
Magit connecting to github with alternate ssh key
2021-01-11T20:55:23.617
# Question Title: Magit connecting to github with alternate ssh key I have two github accounts – one personal and one for my job. In most of my repos, I use my work account and magit works fine. In a couple personal repos, I have this in `.git/config`: ``` sshCommand = ssh -i /my/home/directory/.ssh/personal/id_rsa -F /dev/null ``` This works well from the command line for things like `git push`, but when I try to push from magit, I get this error: ``` ERROR: Permission to <personalaccount>/unified_docs_switcher.git denied to <workaccount>. ``` Since my work account is mentioned in the error message, it seems like magit's connection to git is ignoring the line in `.git/config`. Is there some other config I can add to magit to recognize this? Is there a different/better solution in magit to using different github accounts? (Edit: emacs 27.1 on MacOS from here, tested on magit 2.90.1 from melpa-stable and then 20210105.1030 from melpa) # Answer There's a pure Git solution you can use in your global `.gitconfig` \- I use an `include.path` config for personal stuff by default: ``` # .gitconfig # default user email and key [include] path = .gitconfig-personal ``` and that file contains name, personal email (which is used for SSH and identifying my GitHub account), and GPG key ID: ``` # .gitconfig-personal [user] name = jidicula email = "johanan@forcepush.tech" signingkey = "<personalKeyID>" ``` Then, below that first `[include]` in my global `.gitconfig`, I have an `includeIf.path` work config to use if the repo matches a pattern provided as an argument to `includeIf`: ``` # .gitconfig # When working with Work [includeIf "gitdir:**/work/**/.git"] path = .gitconfig-work ``` and that file contains name, work email, and work email GPG key ID: ``` # .gitconfig-work [user] name = jidicula email = "johanan@work.email" signingkey = "<workKeyID>" ``` Anything in this second config will overwrite whatever was defined by default - paired with the conditional `includeIf`, we get path-dependent Git config. Putting the global `.gitconfig` all together, we get: ``` # .gitconfig # default user email and key [include] path = .gitconfig-personal # When working with Work [includeIf "gitdir:**/work/**/.git"] path = .gitconfig-work ``` Then you'd fill `.gitconfig-personal` and `gitconfig-work` with your context-specific configs like emails, keys, usernames, pull behaviour, commit message templates, etc. You can read more about conditional includes here. > 4 votes --- Tags: magit, ssh ---
thread-62971
https://emacs.stackexchange.com/questions/62971
How to modify interactive function `occur` to a non-interactive function
2021-01-24T04:32:50.097
# Question Title: How to modify interactive function `occur` to a non-interactive function `occur` is an interactive compiled Lisp function in ‘replace.el’. The definition is as follows: ``` (defun occur (regexp &optional nlines region) (interactive (nconc (occur-read-primary-args) (and (use-region-p) (list (region-bounds))))) (let* ((start (and (caar region) (max (caar region) (point-min)))) (end (and (cdar region) (min (cdar region) (point-max)))) (in-region-p (or start end))) (when in-region-p (or start (setq start (point-min))) (or end (setq end (point-max)))) (let ((occur--region-start start) (occur--region-end end) (occur--matches-threshold (and in-region-p (line-number-at-pos (min start end)))) (occur--orig-line (line-number-at-pos (point))) (occur--orig-line-str (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (save-excursion ; If no matches `occur-1' doesn't restore the point. (and in-region-p (narrow-to-region start end)) (occur-1 regexp nlines (list (current-buffer))) (and in-region-p (widen)))))) ``` When the above function is invoked, the user is prompted to input a regexp for searching. What I want is to make a new function `myoccur` by hard-coding a regexp in the above function and make it non-interactive, so that I can conveniently invoke it. If a wrapper over the original `occur` can make it non-interactive, that would also be great. How should I do? # Answer > 2 votes I finally found a solution: ``` (global-set-key (kbd "C-x j") (lambda () (interactive) (occur "regexp" nil))) ``` I also found that `\` needs to be escaped by another `\` in the regexp, which is different from the regexp inputted in interactive mode. For example, to match all functions and subroutines defined in a Fortran code, the regexp should be: ``` ^ *\\(\\(subroutine\\)\\|\\(function\\)\\) ``` while in the interactive mode, the regexp is: ``` ^ *\(\(subroutine\)\|\(function\)\) ``` Update: The reason is that, which I found at emacs website, the string syntax for a backslash is `\\` --- Tags: commands, interactive, occur ---
thread-21664
https://emacs.stackexchange.com/questions/21664
How to prevent flycheck from treating my init.el as a package file?
2016-04-17T10:40:00.690
# Question Title: How to prevent flycheck from treating my init.el as a package file? If flycheck-mode is enabled for my init.el, I got the following kinds of errors: ``` The first line should be of the form: ";;; package --- Summary" (emacs-lisp-checkdoc) ... The footer should be: (provide 'init)\n;;; init.el ends here (emacs-lisp-checkdoc) ``` How can I stop flycheck from treating my init.el as a package? **EDIT** I tried to following minimal start up file: ``` ;; flycheck-mode (require 'flycheck) (global-flycheck-mode) (setq-default flycheck-disabled-checker '(emacs-lisp-checkdoc)) ``` Only flycheck and its dependencies are enabled. `emacs-lisp-checkdoc` is in the disabled checker list but flycheck still lists errors: > ``` > 0 warning The first line should be of the form: ";;; package --- Summary" (emacs-lisp-checkdoc) > 0 warning You should have a section marked ";;; Commentary:" (emacs-lisp-checkdoc) > 2 1 error Cannot open load file: no such file or directory, flycheck (emacs-lisp) > 3 warning You should have a section marked ";;; Code:" (emacs-lisp-checkdoc) > 5 warning The footer should be: (provide 'test)\n;;; test.el ends here (emacs-lisp-checkdoc) > > ``` I'm using Emacs 24.5.1 and the latest flycheck in the git repository (26snapshot). # Answer Add `emacs-lisp-checkdoc` to `flycheck-disabled-checkers`: ``` (setq-default flycheck-disabled-checkers '(emacs-lisp-checkdoc)) ``` > 16 votes # Answer Here's the format that the checker is actually expecting: ``` ;;; init.el --- Initialization file for Emacs ;;; Commentary: Emacs Startup File --- initialization for Emacs ``` If you place this at the top of your init.el it'll remove the warning. You can get emacs to insert this for you automatically by going to the menu and selecting Emacs-Lisp-\>Check Documentation Strings and fill in the requested fields. Source: https://github.com/purcell/emacs.d/issues/152 > 12 votes # Answer The answer by @mpettigr is mostly correct, the given lines will satisfy flycheck for the file header (except that flycheck expects a newline after `Commentary:`). Especially if you start a new elisp file, you could also use the `header` snippet for the `yasnippet` template package, instead of choosing *Emacs-Lisp* \> *Check Documentation Strings* from the menu. This snippet expands to the following code to which also adds the required last line `;;; foo.el ends here` to your file: ``` ;;; foo.el --- Some summary -*- lexical-binding: t -*- ;; Author: quazgar ;; Maintainer: quazgar ;; Version: version ;; Package-Requires: (dependencies) ;; Homepage: homepage ;; Keywords: keywords ;; This file is not part of GNU Emacs ;; This file is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3, or (at your option) ;; any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; For a full copy of the GNU General Public License ;; see <http://www.gnu.org/licenses/>. ;;; Commentary: ;; My commentary ;;; Code: (message "Hello World!") (provide 'foo) ;;; foo.el ends here ``` > 3 votes --- Tags: flycheck ---
thread-62926
https://emacs.stackexchange.com/questions/62926
How to font-lock only strings and comments (syntactic font-locking)?
2021-01-21T17:13:38.207
# Question Title: How to font-lock only strings and comments (syntactic font-locking)? I generally want font-locking only for comments and strings. This would seem easy to do: customize the relevant font lock faces to make them identical to `default`. That unfortunately is not satisfactory, because many other places which actually benefit from some highlighting (dired, org, probably magit) reuse the font lock faces. The next best solution seems to be adding some buffer-local face remaps in `prog-mode` buffers. I've been using this for some time, and it mostly works fine. One problem with this approach is that the font lock colors "leak" into other buffers that copy the original buffer's content (since my face remaps are buffer local). This is particularly bad for Swiper, consult-lines and the like, since the superposition of match highlights with the font locking becomes quite disconcerting (to me at least). Is there a (simple, major-mode indepedent) way to tell `font-lock-mode` to actually not add any face properties except for those I want? # Answer > 5 votes Following Drew's suggestion in the comments, here's a simple solution that can also be adapted to more specific needs: ``` (defun boring-font-lock () "Activate font lock only for strings and comments." (interactive) (font-lock-mode) (setq-local font-lock-keywords nil)) (add-hook 'prog-mode-hook 'boring-font-lock) ``` --- Tags: font-lock ---
thread-62958
https://emacs.stackexchange.com/questions/62958
Manage JSON (comments) with org literate programming and tangle
2021-01-23T13:11:17.163
# Question Title: Manage JSON (comments) with org literate programming and tangle I would like to manage a `JSON` config file with added comments on some key-value-pairs and explain options. Since it is not possible to comment in `JSON`, I thought about using `org-mode` literate programming and tangle to manage the file. Questions are: * there is no specific `JSON` code block, because `JSON` is not really a language. Which language block should I use instead? * Can I tangle code parts to one single `JSON` file? Does tangleing insert characters like return between two blocks? * is there a smarter way to manage / comment `JSON` files in a literate kind of way? # Answer Here is a way to do this with literate programming in org. ``` #+BEGIN_SRC json :tangle config.json {"key1": "value", #+END_SRC For key2 I prefer 0 instead of 1 #+BEGIN_SRC json :tangle config.json "key2": 0} #+END_SRC Here we automate tangling, and then show it is valid json. #+BEGIN_SRC emacs-lisp :var tangle=(org-babel-tangle) (json-read-file "config.json") #+END_SRC #+RESULTS: : ((key1 . value) (key2 . 0)) ``` Is there a smarter way? I guess it depends on where you want your comments. You could use elisp to do it like this. ``` #+BEGIN_SRC emacs-lisp (let ((data '((key-1 . value) ;; I like another-value for key-2 (key-2 . another-value)))) (with-temp-file "config-2.json" (insert (json-encode data)))) (json-read-file "config-2.json") #+END_SRC ``` You could also use noweb, and define your own execute function like this. ``` #+BEGIN_SRC emacs-lisp (defun org-babel-execute:config-json (body params) (message "%S" params) (let* ((vars (seq-filter (lambda (x) (eq (car x) :var)) params)) (config (cl-loop for var in vars if (eq (car (cdr var)) 'config) return (cddr var)))) (with-temp-file config (insert (org-babel-expand-body:generic body params))))) #+END_SRC #+RESULTS: : org-babel-execute:config-json #+name: key-value-1 #+BEGIN_SRC config-json "key1": 0 #+END_SRC #+name: key-value-2 #+BEGIN_SRC config-json "key2": 1 #+END_SRC When you "execute" this block it will write out config3.json. #+name: config #+BEGIN_SRC config-json :noweb yes :var config="config3.json" {<<key-value-1>>, <<key-value-2>>} #+END_SRC #+RESULTS: config #+BEGIN_SRC sh :results raw cat config3.json #+END_SRC #+RESULTS: {"key1": 0, "key2": 1} ``` > 1 votes --- Tags: org-mode, literate-programming, tangle, json ---
thread-62946
https://emacs.stackexchange.com/questions/62946
What is the mechanism by which org-export collates links for the summary?
2021-01-22T21:39:19.950
# Question Title: What is the mechanism by which org-export collates links for the summary? I use `org-export` to generate my end of week email reports. One of the links I have in those reports is for mu4e searches. I have a helper function to translate them into something more useful: ``` ;; Exporting (defvar my-org-mu4e-index-links (rx (: (or "query:i:" "msgid:") (group-n 1 (one-or-more any)))) "A regex to match mu4e links of the form: query:i:20170228171921.21602-1-ale+qemu@clearmind.me ") (defun my-org-mu4e-export (path desc format) "Format mu4e links for export." (when (string-match my-org-mu4e-index-links path) (cond ((eq format 'html) (format "<a href=\"%s%s\">%s</a>" "https://www.google.com/search?q=" (match-string 1 path) desc)) ((eq format 'jira) (format "[%s|%s%s]" desc "https://www.google.com/search?q=" (match-string 1 path))) ((eq format 'ascii) (format "%s\nMessage-Id: <%s>" desc (match-string 1 path)))))) (use-package ox :config (org-link-set-parameters "mu4e" :export 'my-org-mu4e-export)) ``` However what I really want is what happens with other links where the link text is surrounded by `[]` and the link is displayed at the bottom of the section. e.g.: ``` Task 1 ====== - posted message [about foo] to mailing list [foo] Message-Id: <bar> ``` However I've not been able to work out where in the exporter transcoders and filters this is done. I assume I should be able to set some sort of parameter for mu4e style links to deal do this. *EDIT TO ADD* The overall export is slightly more complex as it involves parsing and filtering out lines that are no longer relevant. This is done by calling org-export-as with the following code block: ``` #+name: get-task-list-as-exported-text #+begin_src emacs-lisp :exports code (defun my-filter-out-done-lines (s backend info) "Filter out lines ending in :done" (apply 'concat (--remove (s-matches? (rx ":done" (zero-or-more blank) eol) it) (s-slice-at (rx bol "-") s)))) ; headline _back-end _info (defun my-filter-out-old-completed-todos (s backend info) "Filter out DONE items if they where completed over a week ago." (let ((date (plist-get info :with-date)) (todo (plist-get info :with-todo-keywords)) (todo-type (org-element-property :todo-type s)) (output s)) ;; getting there (setq my-global-debug-var (add-to-list 'my-global-debug-var (list :string s :date date :todo todo :todo-type todo-type))) ;; strip ~~~\n lines (let ((start (string-match "~+\n" output))) (if start (concat (substring s 0 start) (substring s (match-end 0))) output)))) (org-export-define-derived-backend 'my-status-report 'ascii :options-alist '((:with-todo-keywords nil) (:num nil)) :filters-alist '((:filter-plain-list . my-filter-out-done-lines) (:filter-headline . my-filter-out-old-completed-todos))) ;; Snarf the weeks activities (save-excursion (goto-char (point-min)) (when (re-search-forward "* Tasks") (goto-char (match-beginning 0)) (org-export-as 'my-status-report t nil t ))) #+end_src ``` # Answer > 1 votes For me an org file like ``` - Read this [[mu4e:msgid:07DE09F4-70FC-4C03-B3BC-E3DE56F70FD5@andrew.cmu.edu][foo]] - a query [[query:msg:2][my description]] exports to this ascii text - Read this [foo] - a query [my description] [foo] <mu4e:msgid:07DE09F4-70FC-4C03-B3BC-E3DE56F70FD5@andrew.cmu.edu> [my description] <query:msg:2> ``` That is not what happens in html though, neither link is shown in the summary. That section doesn't appear to be generated in the function `org-html-inner-template` but you could easily advise that function to add this I think. There doesn't seem to be a uniform approach to doing this for all backends. It sort of looks like you are trying to turn the links into footnotes. You can do that in a preprocessing hook like this. I don't have a query link, so I used mu4e links here. The idea is to map over them, and replace each one with the appropriate footnote syntax, then continue with your export. Note this only works for mu4e links, and not for other kinds of links. ``` #+BEGIN_SRC emacs-lisp (defun mu4e-to-footnote (_) (let ((mu4e-links (reverse (org-element-map (org-element-parse-buffer) 'link (lambda (lnk) (when (string= (org-element-property :type lnk) "mu4e") lnk))))) (path) (desc)) (cl-loop for lnk in mu4e-links do (setq path (org-element-property :path lnk) desc (buffer-substring (org-element-property :contents-begin lnk) (org-element-property :contents-end lnk))) (setf (buffer-substring (org-element-property :begin lnk) (org-element-property :end lnk)) (format "%s[fn:: %s]" desc path))))) (let ((org-export-before-processing-hook '(mu4e-to-footnote))) (browse-url (org-html-export-to-html))) #+END_SRC ``` --- Tags: org-mode, org-export, mu4e ---
thread-57638
https://emacs.stackexchange.com/questions/57638
How could "C-x 4 b "which pop-up-window but display to the right?
2020-04-07T01:17:00.733
# Question Title: How could "C-x 4 b "which pop-up-window but display to the right? In `emacs -Q`, I strike `C-x 4 b` which invoke `(switch-to-buffer-other-window)` and display the other window vertically as I reference it's source code ``` (defun switch-to-buffer-other-window (buffer-or-name &optional norecord) (interactive (list (read-buffer-to-switch "Switch to buffer in other window: "))) (let ((pop-up-windows t)) (pop-to-buffer buffer-or-name t norecord))) ``` It apply the procedure of `pop-up-window`. How could use "C-x 4 b" pop up the other window which display horizontally instead of vertically? # Answer Try setting the value of split-width-threshold as it works for me when I have wide frames: switching to a buffer in another window splits to the right. > 1 votes # Answer Try `M-x` `windmove-display-right` `RET` `C-x` `4` `b`. In general, other than binding `windmove-display-*` functions, you can evaluate `(windmove-display-default-keybindings '(control meta shift))`, then you can use `C-M-S-arrow key` to tell Emacs where to open the next buffer. For instance, `C-M-S-right` `C-x` `4` `b`. I think `windmove-display-default-keybindings` is available only on Emacs 27 or newer, but AFAIK `windmove-display-*` may be available in older versions. > 0 votes --- Tags: buffers, window-splitting ---
thread-62984
https://emacs.stackexchange.com/questions/62984
How to disable the logging of timestamps for repeated tasks?
2021-01-24T21:00:17.977
# Question Title: How to disable the logging of timestamps for repeated tasks? For example, if I have a repeating TODO such as ``` * TODO item 1 SCHEDULED: [date] - State "DONE" from "TODO" [timestamp] ``` How do I keep the third line from displaying? It clutters up the buffer after a while, and I have to keep deleting the lines. I don't need to have a log of the date and time I completed the task. I can tell from the agenda whether it's done or overdue. # Answer > 1 votes Check the setting of `org-log-done` with `C-h v org-log-done RET`. It is probably set to the symbol `time`. You can set it to `nil`: ``` (setq org-log-done nil) ``` As @lawlist mentions in a comment, `org-log-repeat` can also be the culprit here. You can use per file settings to enable/disable these things: ``` #+STARTUP: nologdone #+STARTUP: logdone #+STARTUP: nologrepeat #+STARTUP: logrepeat ``` which makes it easy to experiment. Another possibility to avoid the clutter is to keep the logging but put the state change items into a a drawer. If you want to do that, you can set the variable `org-log-into-drawer` to the name of a drawer (`LOGBOOK` is the conventional name): ``` (setq org-log-into-drawer "LOGBOOK") ``` --- Tags: org-mode ---
thread-62981
https://emacs.stackexchange.com/questions/62981
error: Invalid face, org-level-1
2021-01-24T18:41:26.627
# Question Title: error: Invalid face, org-level-1 ``` (dolist (face '((org-level-1 . 1.2) (org-level-2 . 1.1) (org-level-3 . 1.05) (org-level-4 . 1.0) (org-level-5 . 1.1) (org-level-6 . 1.1) (org-level-7 . 1.1) (org-level-8 . 1.1))) (set-face-attribute (car face) nil :font "Cantarell" :weight 'regular :height (cdr face))) ``` when I evaluate this code, emacs doesn't complain but when I load a new instance of emacs it gives me an error of: `error: Invalid face, org-level-1`. emacs: v27.1, org: v9.3 # Answer > 5 votes The error message `Invalid face` comes from an internal C function `lface_from_face_name_no_resolve` within `xfaces.c` A face must be defined before an attribute thereof may be changed with `set-face-attribute`. The library that defines the `org-level-...` faces is named `org-faces`, with the Lisp version being `org-faces.el` and the byte-compiled version being `org-faces.elc`. The main library of `org-mode` is `org.el`, and it expressly calls the `org-faces` library with the line `(require 'org-faces)`. The function `with-eval-after-load` (see the doc string of the function with `C-h f with-eval-after-load` and the Elisp Manual for more details) can be used to ensure the `org-faces` library is loaded before attributes of faces defined therein are changed: ``` (with-eval-after-load 'org-faces ...) ``` The `dolist` statement proposed by the O.P. can be inserted/replaced in lieu of the `...` hereinabove. The second argument to `with-eval-after-load` is looking for BODY, which is interpreted to mean just one form ... Where more than one statement is required, consider using `(progn ...)` to wrap one or more statements; e.g., `(progn [SOMETHING] [SOMETHING ELSE])` --- Tags: org-mode, faces ---
thread-26703
https://emacs.stackexchange.com/questions/26703
How can I make Emacs function 'browse-url-at-point work on a tablet running Android?
2016-08-30T23:10:59.427
# Question Title: How can I make Emacs function 'browse-url-at-point work on a tablet running Android? How can I make Emacs function 'browse-url-at-point work on a tablet running Android? Following advice I found at "http://endlessparentheses.com/running-emacs-on-android.html" I installed 'Termux and 'Hacker's keyboard on my Android tablet, started 'Termux and ran: apt update apt install emacs I then started emacs. In the Emacs scratch buffer I wrote "http://www.google.com" and invoked 'browse-url-at-point. It said "No usable browser found". I did some investigating of this subject on the Internet, but so far have found nothing helpful. The table is a HP Touchpad running Android 5.1.1 via CyanogenMod version "12.1-20160109-SNAPSOT-jcsullins-tenderloin. **Added after reading the comment by Jack, and further investigation:** For a while I thought that turning on root access on my HP Touchpad (running CyogenMod Android 12) and using command "su" was necessary, but someone referred me to "termux-open-url" and its source code suggested to me to add "--user 0" to what Jack suggested. My first test was to run the command am start --user 0 -a android.intent.action.VIEW -d http://www.google.com in the Termux terminal window. That worked. I then started up Emacs inside Termux and issued the same command inside the shell buffer. That also worked. # Answer Based on this adding something like this to your config *should* work: ``` (advice-add 'browse-url-default-browser :override (lambda (url &rest args) (start-process-shell-command "open-url" nil (concat "am start -a android.intent.action.VIEW -d " url)))) ``` > 3 votes # Answer ``` (setq browse-url-browser-function 'browse-url-xdg-open) ``` seems to make things open up in the right browser for me. > 1 votes --- Tags: android ---
thread-62868
https://emacs.stackexchange.com/questions/62868
How to use C header files in org-mode source code blocks?
2021-01-19T00:14:34.607
# Question Title: How to use C header files in org-mode source code blocks? I have a C code block in my org-mode document like the following: ``` #+begin_src C :exports both #include "my_header.h" int main(void) { function_from_my_header(); return 0; } #+end_src ``` When I have point inside the code block and `C-c C-c` to compile + generate results, I get the following error. ``` /var/folders/bc/2wq0dn651ys844kp5cz459mc0000gn/T/babel-SktA20/C-src-RnWgKS.c:8:10: fatal error: 'my_header.h' file not found #include "my_header.h" ^~~~~~~~~~~~~ 1 error generated. zsh:1: permission denied: /var/folders/bc/2wq0dn651ys844kp5cz459mc0000gn/T/babel-SktA20/C-bin-DWq2ho ``` How do I get org-mode to recognize the header file (which is contained in the same directory as the org file? It is worth noting: everything has worked fine so far if I don't have (custom) headers (e.g., includes for `stdio.h` etc. work fine). It is also worth noting that if I save the source code block to a file and compile using gcc, then the file compiles fine. Ergo, it seems the missing piece is determining how to get org-mode to recognize `my_header.h`, which lies in the same directory as the org file itself. --- ## Edit: Solved I did as NickD suggested but still got an error. To be precise, I have the three files * `my_header.c` ``` #include <stdio.h> #include "my_header.h" void my_function(void) { printf("I can C clearly now.\n"); } ``` * `my_header.h` (contains only the prototype for `my_function`. * `my_test.c` ``` #include "my_header.h" int main(void) { my_function(); return 0; } ``` When I compile and link from the command line (from within the directory in which these files reside), I run: ``` gcc my_test.c my_header.c -o my_test && ./my_test ``` Everything works perfectly. Now, if I run the following code block from within an org-mode document (residing in the same directory): ``` #+begin_src C :flags -I . #include "my_header.h" int main(void) { my_function(); return 0; } #+end_src ``` I get the following error message from the compiler: ``` Undefined symbols for architecture x86_64: "_my_function", referenced from: _main in C-src-fboHG7-40f2c1.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) zsh:1: no such file or directory: /var/folders/bc/2wq0dn651ys844kp5cz459mc0000gn/T/babel-SktA20/C-bin-9wLHvS ``` The fix (in addition to setting `:flags -I.` was to also set `:includes my_header.c` **The following works perfectly for me when I** `C-c C-c` **in org:** ``` #+begin_src C :flags -I . :includes my_header.c int main(void) { my_function(); return 0; } #+end_src ``` ## Question summary *How do I get org-mode to recognize the header file (which is contained in the same directory as the org file?* You don't. You point it to the *source file* corresponding to the header (i.e., `my_header.c`) by `include`-ing `my_header.c`. Why is this the expected behaviour? My understanding is that this flag creates an `#include "my_header.c"` line in the temporary `.c` file, and that this is not standard practice when writing C code (one usually includes the `.h` file). # Answer The correct solution involves a step beyond what was described in NickD's answer. The following is correct - both in terms of C style and org-mode style. ``` #+begin_src C :flags -I. my_header.c #include "my_header.h" int main(void) { function_from_my_header(); return 0; } #+end_src ``` Equivalently, one could write ``` #+begin_src C :flags -I. my_header.c :includes my_header.h function_from_my_header(); #+end_src ``` This can be gleaned from how the `#+CALL` is described in the org manual, noting that the call to `gcc` should look like: ``` gcc -o <executable_name> <code_block_name.c> my_header.c -I. ``` (In particular, `my_header.c` needs to appear in the call to `gcc`, and `:flags` is the appropriate place to include that. Importantly, `my_header.c` should **not** be placed in the `:includes` header arg. This is bad C practice and can have unintended consequences.) > 1 votes # Answer You need to arrange that `gcc` is called with the flag `-I .` that tells the preprocessor to look in the current directory (as well as the default directories). You can do that with ``` #+begin_src C :exports both :flags -I . #include "my_header.h" int main(void) { function_from_my_header(); return 0; } #+end_src ``` Why that is needed and why you don't need anything like that when you invoke `gcc` from the command line is a bit subtle: Org babel creates a temporary file `/var/folders/bc/2wq0dn651ys844kp5cz459mc0000gn/T/babel-SktA20/C-src-RnWgKS.c` (as you can see in the error message), with the source code from the code block inserted, but note it's in some temporary directory, *not* in the directory where your Org mode file and `my_header.h` are. So the compilation fails. Try copying your C file to some other directory and then on the command line saying `gcc -o /path/to/other/directory/foo /path/to/other/directory/foo.c`: it will fail the same way. By giving it the `-I .` flag, you are saying "search for include files in the current directory, as well as in the standard include directories", i.e. you are effectively executing `gcc -o /path/to/other/directory/foo -I . /path/to/other/directory/foo.c` *from the directory where your Org mode file and your `my_header.h` file are*: since your current directory does contain `my_header.h`, the preprocessor can find it and everything works. There are several other header arguments for C code blocks that are described in the relevant Babel Language page on Worg (`:libs` e.g. will be useful whenever you try to link with an external library). And if you venture to other languages, you might want to look at their language-specific pages. > 2 votes --- Tags: org-mode, org-babel, c, file-header ---
thread-62947
https://emacs.stackexchange.com/questions/62947
gnus-dired-attach <return> based keybinding does not work
2021-01-22T22:00:38.563
# Question Title: gnus-dired-attach <return> based keybinding does not work I am on gnu emacs 26.3 linux mint 20.1 and since my last OS update I cannot attach multiple files via dired using the key-binding `C-c RET C-a`. The message buffer indicates that `C-c <return> C-a is undefined`. Strangely, the supposedly equivalent `C-c C-m C-a` does work. Is there any way to debug what is happening? To be clear, I have a message and dired buffers open, I mark some files on dired, and hit `C-c RET C-a`, but the files do not get attached to the message buffer. # Answer Well...this solution works. The question still lingers though, over why this happened in the first place. Thank you @Drew ``` (global-set-key (kbd "C-c <return> C-a") 'gnus-dired-attach) ``` > 0 votes --- Tags: key-bindings ---
thread-58148
https://emacs.stackexchange.com/questions/58148
Enlarge pictures in image-dired
2020-04-29T07:27:44.277
# Question Title: Enlarge pictures in image-dired When I use the `image-dired` but find pictures displays in very small size. How could enlarge them? # Answer You can select the picture in the `*image-dired*` buffer and press `+` to increase the size of the selected picture. > 1 votes # Answer If you mean the thumbnails size, you can set the variable `image-dired-thumb-size`. For example: ``` (setq image-dired-thumb-size 80) ``` > 0 votes --- Tags: image-dired ---
thread-18336
https://emacs.stackexchange.com/questions/18336
Why am I getting an error while downloading Melpa packages in Emacs on Win7 OS
2015-11-23T14:01:46.567
# Question Title: Why am I getting an error while downloading Melpa packages in Emacs on Win7 OS I am using Emacs on a Win7 machine. I have added the Melpa repo. in `init.el`. When I do `M-x list-packages`, I do get a buffer listing the packages from Melpa. But, when i try to download them, I get an error: `open-network-stream: make client process failed: connection timed out, :name, melpa.milkbox.net, :buffer, #<killed buffer>, :host, melpa.milkbox.net, :service, 80, :nowait, nil...` Please note that I am using Emacs behind a corporate proxy. Emacs is able to download the list of packages but not able to install any. Please find below snippet from my init.el: ``` (require 'package) (add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/")) (add-to-list 'package-archives '("org" . "http://orgmode.org/elpa/") t) (add-to-list 'package-archives '("gnu" . "https://elpa.gnu.org/packages/")) (package-initialize) ;; line numbers in emacs everywhere (global-linum-mode t) (set-face-attribute 'default nil :font "Consolas-12") ;; set proxy (defun proxy-activate () (interactive) (let ((proxy "unrealproxy:8080") (credentials "unrealusername:unrealpwd")) (setq url-proxy-services `(("no_proxy" . "^\\(localhost\\|10.*\\)") ("http" . ,proxy) ("https" . ,proxy))) (setq url-http-proxy-basic-auth-storage (list (list proxy (cons "Input your LDAP UID !" (base64-encode-string credentials))))))) (provide 'proxy-activate) ``` # Answer MELPA moved to melpa.org, so use this in your .emacs: ``` (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) ``` > 2 votes # Answer I know this is really old, but in case this helps someone else, as of November 2020, Melba is now located at `http://melpa.milkbox.net/packages`: ``` (add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/")) ``` Reference: https://melpa.org/#/getting-started > 0 votes --- Tags: init-file, microsoft-windows, package-repositories ---
thread-62892
https://emacs.stackexchange.com/questions/62892
`auth-source-search` cannot deal with multiple consecutive searches
2021-01-20T05:15:40.297
# Question Title: `auth-source-search` cannot deal with multiple consecutive searches I am a heavy user of https://github.com/yuya373/emacs-slack, and I noticed a weird behavior of `auth-source-search`: If I call this function multiple times, querying the second info always returns `nil`. This is my slack configuration: ``` (let ((auth1 (car (auth-source-search :host "team1.slack.com"))) (auth2 (car (auth-source-search :host "team2.slack.com")))) (slack-register-team :name "Team 1" :user "some_email1@example1.com" :token (funcall (plist-get auth1 :secret))) (slack-register-team :name "Team 2" :user "some_email2@example2.com" :token (funcall (plist-get auth2 :secret))) ``` And the second call to `auth-source-search` fails, making `auth2` `nil`. So, Emacs cannot evaluate the expression `(funcall (plist-get auth2 :secret))` since `(plist-get auth2 :secret)` is `nil`. I am certain that `auth-source-search` is somehow broken, and have found a prior question to this: \`auth-source-search\` returns nil for valid queries . A comment to this question suggested to add `:port` keyword argument to `auth-source-search`, but in this case I cannot because the Slack auth info does not contain any `port` fields. How can I solve this issue? Edit: My `.authinfo` looks roughly like this: ``` host team1.slack.com user some_email1@example1.com password ... machine imap.gmail.com login ... port ... password ... machine smtp.gmail.com login ... port ... password ... host team2.slack.com user some_email2@example2.com password ... ``` That is, the entry of `team1.slack.com` comes before that of `team2.slack.com`. My Emacs is of version 27.1, configured with Spacemacs at the develop branch's latest commit. # Answer > 0 votes Yay, solved it: use `machine` instead of `host` for both `authinfo.gpg` and the keyword argument. --- Tags: authinfo ---
thread-27467
https://emacs.stackexchange.com/questions/27467
Way to hide SRC block delimiters
2016-09-30T11:09:20.103
# Question Title: Way to hide SRC block delimiters is there a way to keep only source code inside source code, that is make #+BEGIN\_SRC and #+END\_SRC invisible? It's cosmetic but it makes things clearer when one have to deal with a lot of short code snippets. For exemple: ``` (defun org-xor (a b) "Exclusive or." (if a (not b) b)) ``` instead of : ``` #+BEGIN_SRC emacs-lisp (defun org-xor (a b) "Exclusive or." (if a (not b) b)) #+END_SRC ``` # Answer > 13 votes The face for all lines starting with `#+` is called `org-meta-line`. You can customize this face smaller, darker, etc. to make it less visible. # Answer > 4 votes I use the following piece of code that goes some of the way. It's not perfect. Maybe it will become a proper `minor-mode` some day. (source). ``` (with-eval-after-load 'org (defvar-local rasmus/org-at-src-begin -1 "Variable that holds whether last position was a ") (defvar rasmus/ob-header-symbol ?☰ "Symbol used for babel headers") (defun rasmus/org-prettify-src--update () (let ((case-fold-search t) (re "^[ \t]*#\\+begin_src[ \t]+[^ \f\t\n\r\v]+[ \t]*") found) (save-excursion (goto-char (point-min)) (while (re-search-forward re nil t) (goto-char (match-end 0)) (let ((args (org-trim (buffer-substring-no-properties (point) (line-end-position))))) (when (org-string-nw-p args) (let ((new-cell (cons args rasmus/ob-header-symbol))) (cl-pushnew new-cell prettify-symbols-alist :test #'equal) (cl-pushnew new-cell found :test #'equal))))) (setq prettify-symbols-alist (cl-set-difference prettify-symbols-alist (cl-set-difference (cl-remove-if-not (lambda (elm) (eq (cdr elm) rasmus/ob-header-symbol)) prettify-symbols-alist) found :test #'equal))) ;; Clean up old font-lock-keywords. (font-lock-remove-keywords nil prettify-symbols--keywords) (setq prettify-symbols--keywords (prettify-symbols--make-keywords)) (font-lock-add-keywords nil prettify-symbols--keywords) (while (re-search-forward re nil t) (font-lock-flush (line-beginning-position) (line-end-position)))))) (defun rasmus/org-prettify-src () "Hide src options via `prettify-symbols-mode'. `prettify-symbols-mode' is used because it has uncollpasing. It's may not be efficient." (let* ((case-fold-search t) (at-src-block (save-excursion (beginning-of-line) (looking-at "^[ \t]*#\\+begin_src[ \t]+[^ \f\t\n\r\v]+[ \t]*")))) ;; Test if we moved out of a block. (when (or (and rasmus/org-at-src-begin (not at-src-block)) ;; File was just opened. (eq rasmus/org-at-src-begin -1)) (rasmus/org-prettify-src--update)) ;; Remove composition if at line; doesn't work properly. ;; (when at-src-block ;; (with-silent-modifications ;; (remove-text-properties (match-end 0) ;; (1+ (line-end-position)) ;; '(composition)))) (setq rasmus/org-at-src-begin at-src-block))) (defun rasmus/org-prettify-symbols () (mapc (apply-partially 'add-to-list 'prettify-symbols-alist) (cl-reduce 'append (mapcar (lambda (x) (list x (cons (upcase (car x)) (cdr x)))) `(("#+begin_src" . ?✎) ;; ➤ ➟ ➤ ✎ ("#+end_src" . ?□) ;; ⏹ ("#+header:" . ,rasmus/ob-header-symbol) ("#+begin_quote" . ?») ("#+end_quote" . ?«))))) (turn-on-prettify-symbols-mode) (add-hook 'post-command-hook 'rasmus/org-prettify-src t t)) (add-hook 'org-mode-hook #'rasmus/org-prettify-symbols)) ``` # Answer > 4 votes The org-present package does this. Specifically, it is taken care of by `(org-present-add-overlays)`, which then uses `(overlay-put)` to make the text invisible. This approach is further described in section 39.6 of the Emacs Lisp manual. # Answer > 2 votes Yet another way to do this is using hide-lines. The following code is from my emacs config (with a few modifications because I have a lot of self-written macros). ``` (use-package hide-lines :commands hide-lines hide-lines-matching) ;; The line ~(overlay-put overlay 'invisible 'hl)~ in [[helpfn:][hide-lines-add-overlay]] wouldn't ;; work with the argument =hl=. It works when you set it to =t= instead. Maybe =hl= is ;; depreciated. (define-advice hide-lines-add-overlay (:override (start end) fix-adding-overlay) "Add an overlay from `start' to `end' in the current buffer. Push the overlay into `hide-lines-invisible-areas'." (let ((overlay (make-overlay start end))) (setq hide-lines-invisible-areas (cons overlay hide-lines-invisible-areas)) (overlay-put overlay 'invisible t))) (defun org/hide-source-block-delimiters () "Hide property drawers." (interactive) (let (selective-display-ellipses org-ellipsis) ;; If properties are folded, ellipsis will show. (org-show-all) (hide-lines-matching (rx "#+" (or "begin" "end") "_src" (* nonl) "\n")))) ``` # Answer > 1 votes The face for `#+BEGIN` is `org-block-begin-line` and for `#+END` is `org-block-end-line`. If you already have a dark theme, something like this will make it well nigh invisible, and can be tweaked to your liking or to fit a light theme (*hint* for light, start with `#ffffff`): ``` (set-face-attribute 'org-block-begin-line nil :foreground "#000000") (set-face-attribute 'org-block-end-line nil :foreground "#000000") ``` For example, here is the code you posted, with these face attributes set, on top of the Spacemacs dark theme: Note that this will apply not only to `SRC` blocks but also to `QUOTE` blocks, etc. # Answer > 1 votes ``` ;; Org mode (add-hook 'org-mode-hook '(lambda () ;; Hide org block lines ;; Unset any previous customization for the background color (set-face-attribute 'org-block-begin-line nil :background 'unspecified) (set-face-attribute 'org-block-end-line nil :background 'unspecified) ;; Set the foreground color to the value of the background color (set-face-attribute 'org-block-begin-line nil :foreground (face-background 'org-block-begin-line nil 'default)) (set-face-attribute 'org-block-end-line nil :foreground (face-background 'org-block-end-line nil 'default)) )) ``` Sets the foreground color to the background color, which effectively means hiding the text. Note: you might need to restart emacs (instead of just reloading the config) for the changes to take effect. --- Tags: org-mode ---
thread-63006
https://emacs.stackexchange.com/questions/63006
How to disable the / character prefix in Cyrillic input mode?
2021-01-26T08:13:45.513
# Question Title: How to disable the / character prefix in Cyrillic input mode? When I switch to Cyrillic input method (by pressing `C-\`), the `/` key starts to act as a prefix to enter extended characters. For example: * `/o` -\> `њ` * `/a` -\> `ќ` * `/y` -\> `ї` etc... Is there a way to disable this behavior? I'd prefer to switch it off permanently for all modes, so pressing the `/` always enters the same character independently of what I typed after it. # Answer I assume you mean the `cyrillic-translit` input method. The supported way is to identify each binding with a slash as prefix by looking at `quail/cyrillic.el` and unbind it individually: ``` (quail-defrule "/d" nil "cyrillic-translit") [...] (quail-defrule "/t" nil "cyrillic-translit") ``` The unsupported way is to look at quail's code to perform introspection on the input method, find where the slash is defined in its keymap and unset it: ``` (quail-select-package "cyrillic-translit") (dolist (binding (cdr (quail-map))) (when (= (car binding) ?/) (setcdr binding nil))) ``` To defer evaluation of that code inside your init file: ``` (with-eval-after-load "leim/quail/cyrillic" (quail-select-package "cyrillic-translit") (dolist (binding (cdr (quail-map))) (when (= (car binding) ?/) (setcdr binding nil)))) ``` One last issue with this is that there doesn't seem to be any supported way of temporarily working with a quail package. Whether that is a problem in practice, you tell me. > 2 votes --- Tags: input-method, quail ---
thread-63012
https://emacs.stackexchange.com/questions/63012
How to change Emacs' word movement behaviour?
2021-01-26T11:50:46.960
# Question Title: How to change Emacs' word movement behaviour? I want to do this on `forward-word`: (`|` shows the cursor position) Normal Behaviour: ``` int main(int argc, char *args[]) { int a = 45|; printf|("%i", a); } ``` What I want to do: ``` //forward-word first int main(int argc, char *args[]) { int a = 45|;| printf("%i", a); } //forward-word second int main(int argc, char *args[]) { int a = 45;| printf|("%i", a); } ``` # Answer I use these commands to skip words but stop around symbols, ``` (defun reluctant-forward (&optional arg) "Skip spaces and tabs following the point, then move past all characters with the same syntax class. Do it ARG times if ARG is positive, or -ARG times in the opposite direction if ARG is negative. ARG defaults to 1." (interactive "^p") (if (> arg 0) (dotimes (_ arg) (when (looking-at-p "[ \t]") (skip-chars-forward " \t")) (unless (= (point) (point-max)) (forward-same-syntax))) (dotimes (_ (- arg)) (when (looking-back "[ \t]") (skip-chars-backward " \t")) (unless (= (point) (point-min)) (forward-same-syntax -1))))) (defun reluctant-backward (&optional arg) "Skip spaces and tabs preceding the point, then move before all characters with the same syntax class. Do it ARG times if ARG is positive, or -ARG times in the opposite direction if ARG is negative. ARG defaults to 1." (interactive "^p") (reluctant-forward (- arg))) ``` and I've bound them to `M-left` and `M-right`: ``` (global-set-key (kbd "M-<right>") #'reluctant-forward) ; replaces ‘right-word’. (global-set-key (kbd "M-<left>") #'reluctant-backward) ; replaces ‘left-word’. ``` Here are the places where `reluctant-forward` would place the point if called repeatedly starting from within the square brackets ``` int main(int argc, char *args[|])| |{| |int| a| =| 45|;| |printf|(|"|%i|"|,| a|)|;| |}| ``` Notice that as it is it stops at the beginning of the first word that follows a newline (e.g. at the beginning of `printf`), differently from what you asked. I should be able to fix that if you want. --- **Update** I thought I had to fiddle with syntax classes, instead it was just a matter of adding the newline to the characters to skip. ``` (defun reluctant-forward (&optional arg) "Skip whitespace following the point, then move past all characters with the same syntax class. Do it ARG times if ARG is positive, or -ARG times in the opposite direction if ARG is negative. ARG defaults to 1." (interactive "^p") (if (> arg 0) (dotimes (_ arg) (when (looking-at-p "[ \t\n]") (skip-chars-forward " \t\n")) (unless (= (point) (point-max)) (forward-same-syntax))) (dotimes (_ (- arg)) (when (looking-back "[ \t\n]") (skip-chars-backward " \t\n")) (unless (= (point) (point-min)) (forward-same-syntax -1))))) (defun reluctant-backward (&optional arg) "Skip whitespace preceding the point, then move before all characters with the same syntax class. Do it ARG times if ARG is positive, or -ARG times in the opposite direction if ARG is negative. ARG defaults to 1." (interactive "^p") (reluctant-forward (- arg))) ``` Stops from `|[])` to `printf|`: ``` int main(int argc, char *args|[|])| {| int| a| =| 45|;| printf|("%i", a); } ``` --- **Update 2** Not as tested as the other version (I might have missed some corner cases) but it seems to do what you want ``` (defun reluctant-forward (&optional arg) "Move point to the end of the next word or string of non-word-constituent characters. Do it ARG times if ARG is positive, or -ARG times in the opposite direction if ARG is negative. ARG defaults to 1." (interactive "^p") (if (> arg 0) (dotimes (_ arg) ;; First, skip whitespace ahead of point (when (looking-at-p "[ \t\n]") (skip-chars-forward " \t\n")) (unless (= (point) (point-max)) ;; Now, if we're at the beginning of a word, skip it… (if (looking-at-p "\\sw") (skip-syntax-forward "w") ;; …otherwise it means we're at the beginning of a string of ;; symbols. Then move forward to another whitespace char, ;; word-constituent char, or to the end of the buffer. (if (re-search-forward "\n\\|\\s-\\|\\sw" nil t) (backward-char) (goto-char (point-max)))))) (dotimes (_ (- arg)) (when (looking-back "[ \t\n]") (skip-chars-backward " \t\n")) (unless (= (point) (point-min)) (if (looking-back "\\sw") (skip-syntax-backward "w") (if (re-search-backward "\n\\|\\s-\\|\\sw" nil t) (forward-char) (goto-char (point-min)))))))) (defun reluctant-backward (&optional arg) "Move point to the beginning of the previous word or string of non-word-constituent characters. Do it ARG times if ARG is positive, or -ARG times in the opposite direction if ARG is negative. ARG defaults to 1." (interactive "^p") (reluctant-forward (- arg))) ``` Stops (starting from the beginning, and using `reluctant-forward` with positive `ARG`): ``` int| main|(|int| argc|,| char| *|args|[])| {| int| a| =| 45|;| printf|("%|i|",| a|);| }| ``` > 3 votes --- Tags: motion, config, words ---
thread-63003
https://emacs.stackexchange.com/questions/63003
org-babel-tangle error
2021-01-26T00:16:11.270
# Question Title: org-babel-tangle error I am experiencing a very unusual (concerning) error with my org-mode installation, and I am afraid that something might be broken. First, I have this setup in my .emacs file ``` ;; Use my org-mode file as an init emacs file (org-babel-load-file (expand-file-name "~/my_NOTES_file.org" user-emacs-directory)) ``` and when I try to load emacs there is an error in that org file. Starting with --debug-init reveals ``` Debugger entered--Lisp error: (wrong-type-argument stringp nil) string-match("emacs-lisp\\|elisp" nil nil) org-babel-tangle-collect-blocks("emacs-lisp\\|elisp" nil) org-babel-tangle(nil "/home/username/my_NOTES_file.el" "emacs-lisp\\|elisp") org-babel-tangle-file("/home/username/my_NOTES_file.org" "/home/username/my_NOTES_file.el" "emacs-lisp\\|elisp") org-babel-load-file("/home/username/my_NOTES_file.org") eval-buffer(#<buffer *load*> nil "/home/username/.emacs" nil t) ; Reading at buffer position 1404 load-with-code-conversion("/home/username/.emacs" "/home/username/.emacs" t t) load("~/.emacs" t t) #f(compiled-function () #<bytecode 0x1e0f4d>)() command-line() normal-top-level() ``` so it seems that the functions following `org-babel-tangle` are receiving a `nil` for some reason. I have tried several things, including * a full reinstallation of emacs * tangled the emacs-lisp source blocks in the org file. * isolate the emacs-lisp code blocks in a separate org-mode file and use that one instead. The last solution does work, but I'd rather have all my configuration in my main org file. This main file is rather large (31128 lines) and has source blocks from several other programming languages. However, these two factors shouldn't be an impediment right? Thank you in advance for any help. # Answer > 4 votes A good tool for finding errors in Org mode files is `org-lint`: just visit the file, say `M-x org-lint` and fix any problems it finds. There is no guarantee that it will find everything, so you might still end up having to debug your file using other methods, but it is a quick and easy first step that just might solve the problem, as it did here. The doc string of the function is a bit too concise: > Check current Org buffer for syntax mistakes. > > By default, run all checkers. With a ‘C-u’ prefix ARG, select one category of checkers only. With a ‘C-u C-u’ prefix, run one precise checker by its name. > > ARG can also be a list of checker names, as symbols, to run. leaving one with questions about what checkers are available. For that, you will have to consult the Commentary section in `org-lint.el`. For the record, here's the bare list: * duplicate CUSTOM\_ID properties * duplicate NAME values * duplicate targets * duplicate footnote definitions * orphaned affiliated keywords * obsolete affiliated keywords * missing language in source blocks * missing back-end in export blocks * invalid Babel call blocks * NAME values with a colon * deprecated export block syntax * deprecated Babel header properties * wrong header arguments in source blocks * misuse of CATEGORY keyword * "coderef" links with unknown destination * "custom-id" links with unknown destination * "fuzzy" links with unknown destination * "id" links with unknown destination * links to non-existent local files * SETUPFILE keywords with non-existent file parameter * INCLUDE keywords with wrong link parameter * obsolete markup in INCLUDE keyword * unknown items in OPTIONS keyword * spurious macro arguments or invalid macro templates * special properties in properties drawer * obsolete syntax for PROPERTIES drawers * Invalid EFFORT property value * missing definition for footnote references * missing reference for footnote definitions * non-footnote definitions in footnote section * probable invalid keywords * invalid blocks * misplaced planning info line * incomplete drawers * indented diary-sexps * obsolete QUOTE section * obsolete "file+application" link * spurious colons in tags Consult the doc string of the constant `org-lint--checkers` (do `C-h v org-lint--checkers`) for the names that you can use in the `org-lint` invocation, if you want to run a particular checker, although in that case, it's easier to do `C-u M-x org-lint TAB` or `C-u C-u M-x org-lint TAB` and use completion (category completion in the first case, checker completion in the second). --- Tags: org-mode, init-file, org-babel, string ---
thread-63015
https://emacs.stackexchange.com/questions/63015
Reverting back to higher heading
2021-01-26T15:03:54.777
# Question Title: Reverting back to higher heading Here is a sample text to illustrate my difficulty: ``` * H1 L1 Some introductory text for H1 ** H2 L2 Some text relating to H2 L3 This is part of H2. But I would like it to be part of H1 only, not part of H2 ``` How do I get lines such as L3 out of H2 and into H1 without moving them around? Is there some kind of 'End of H2' marker? # Answer > 4 votes If you need H2 to have heading like features (eg you can tag, put properties, etc), you can use inline tasks for this as @NickD suggested (see `M-x find-library org-inlinetask`). You insert one with `C-c C-x t`. These are like regular headings but not part of the hierarchy. ``` * H1 L1 Some introductory text for H1 *************** H2 L2 Some text relating to H2 *************** END L3 This is part of H2. But I would like it to be part of H1 only, not part of H2 ``` If you just want something like folding, you can use drawers I think. ``` * H1 L1 Some introductory text for H1 :H2: L2 Some text relating to H2 :END: L3 This is part of H2. But I would like it to be part of H1 only, not part of H2 ``` --- Tags: org-mode, outline-mode, outline ---
thread-51603
https://emacs.stackexchange.com/questions/51603
I see "Unnecessary call to ‘package-initialize’ in init file" but can't find the call to `package-initialize`
2019-07-14T12:04:35.830
# Question Title: I see "Unnecessary call to ‘package-initialize’ in init file" but can't find the call to `package-initialize` I'm running Emacs from `HEAD` on Mac OS. I installed `emacs-plus` using the `--HEAD` argument with homebrew. I did a whole grep for `(package-initialize)` in `~/.emacs.d/`. The only reference I found to it is in `elpa/flycheck`, and I odn't require it at all, so it shouldn't run. Just to be safe, I customize the `flycheck-emacs-lisp-initialize-packages` variable to `nil`, meaning that `flycheck` shouldn't run `package-initialize` at all. Is there anything I'm missing? Is there another place I should be checking? # Answer > 5 votes Thanks to the comment by @wvxvw, this is how I finally ended up solving the problem. Initially, I tried going to `package-initialize`, and instrumenting it (by pressing `C-u C-M-x`) which causes it to open the debugger whenever it's called. Unfortunately, evaluating my init file by opening it and running `M-x eval-buffer <RET>` didn't cause the debugger to open. I guess this is because the piece of code that calls `package-initialize` was not being called any more. So I put this at the top of my init file: ``` (debug-on-entry 'package-initialize) ``` Then I restarted Emacs and voila! I finally saw the debugger, which pointed me to the emacspeak package I've already reported this to the author, but I'll go ahead and ignore this for now. # Answer > 1 votes I had the same problem, and the solution was pretty simple. I checked my .emacs file (the init file with all my customization), and found that I had entered `(package-initialize)` twice. So I commented out the first one by `;; (package-initialize)` and the error went away. --- Tags: init-file, package, debugging ---
thread-62956
https://emacs.stackexchange.com/questions/62956
Workflow to collect TODO notes from various files into an org agenda
2021-01-23T09:33:11.667
# Question Title: Workflow to collect TODO notes from various files into an org agenda I often want to add TODO notes inside of my latex files I am currently working on or inside of other source code files scattered around in my filesystem. The problem with this is that those TODO notes doesn't appear in my org agenda file obviously. So is there any clever way to make TODO notes inside non org files (in my case mainly latex and python but I guess that shouldn't matter) and then collect them in my org agenda? In particular it would be great if the TODO notes could also contain timestamps as in regular org files. Is there an alternative workflow I should consider for this? # Answer > 3 votes Don't nest Org syntax inside your LaTeX files. Do it the other way around instead: nest LaTeX syntax in code blocks inside Org files, add each of those Org files to `org-agenda-files`, and tangle (export) the nested LaTeX code to pure-LaTeX files whenever you need to build. Don't worry if that means you're creating Org files that are 99% LaTeX; Org will handle it just fine. https://orgmode.org/manual/Working-with-Source-Code.html The same goes for Python and other languages supported by Org Babel. --- Tags: org-mode, todo ---
thread-63004
https://emacs.stackexchange.com/questions/63004
SES does not initialize properly when opening existing spreadsheet files
2021-01-26T01:11:55.517
# Question Title: SES does not initialize properly when opening existing spreadsheet files When I attempt to open an existing SES (Simple Emacs Spreadsheet) file in GNU Emacs 24.3.1 (i386-mingw-nt6.1.7601), the file comes up, but SES has not been properly initialized, even though the file extension is `.ses`, and there is an apparent (SES) mode-indicator in the emacs mode-line. The header row doesn't show any column letters A, B, C, ..., and standard SES keys are *not* bound to their proper SES commands (e.g., `M-k` is bound to the default Emacs `kill-sentence` instead of the correct `ses-delete-column`, etc.). The file incorrectly comes up in a full height (i.e., un-narrowed) buffer, but the SES command `ses-renarrow-buffer` is unavailable because its standard key `C-c C-n` is undefined. In short, this version of SES can create spreadsheet files from scratch, but once the file is closed, SES will not properly re-open it. Typing `M-x ses-mode` to a freshly opened existing SES file gives the error message "Invalid printer function". Update -- Just before taking a suggestion of phils to try starting Emacs with the option -Q, I added three simple lines of code to my .emacs file which completely solved my immediate problem, but do not provide a basis for diagnosing the exact nature of the problem. This new code loads a file defining a non-trivial printer function which is used to print most of the columns in my speadsheets, and adds that function to SES's list of "safe-functions". Designating the function as "safe" avoids the need for a safety dialog that SES would otherwise insist on having at "find-file" time, in which the same question is asked for each column in my spreadsheets that use the function. I strongly suspect that something about my impatient `y/n` responses to those questions led to the problem, but I haven't been able to reproduce the original problem in about 45 minutes of trying. The mere occurrence of the dialog does not lead to the problem. Given that the problem no longer stands in my way, I am unwilling to spend more time trying to find out exactly what triggered it in the first place, and why it was so persistent. # Answer > 1 votes I have found a satisfactory solution (of a sort) to the problem, without being able to exactly diagnose it, as explained in the above Update. The code I added to my .emacs file (which was needed anyway in order to avoid a frustratingly repetitive safety dialogue) is as follows: ``` ;; load the code file defining the printer function num-to-cash (load-file "c:/ . . . /SES-functions.elc") ;; add the SES printer function num-to-cash to the list safe-functions (setq safe-functions (cons 'num-to-cash (if (boundp 'safe-functions) safe-functions nil ))) ``` --- Tags: spreadsheet ---
thread-63023
https://emacs.stackexchange.com/questions/63023
Like pressing "q", but from the other window
2021-01-27T09:32:21.380
# Question Title: Like pressing "q", but from the other window I run a command that takes over another window, and maybe resizes it a little, but doesn't focus it. Let's say `C-h e` or `C-x C-b`. I can go to that window and press `q` there, and everything goes back to the previous state (the window resizes back, its previous content is restored, focus is back to the original window). I want to be get the same effect without having to go to that window. Instead of `C-h e C-x o q` I want to be able to do `C-h e <some keystroke that will close the most recently opened closeable-by-pressing-q window>`. --- (Months later) I found a simpler and more straightforward way... sometimes the simpler things elude us... (I'm leaving the "solved" mark where it is anyway): ``` (defun quit-other-window () (interactive) (other-window 1) (quit-window)) (global-set-key (kbd "C-c q") #'quit-other-window) ``` # Answer You have a couple of options. You can use the `windmove-delete-up`, `-down`, `-left` and `-right` functions. I use them with these bindings: ``` (global-set-key (kbd "C-c W") #'windmove-delete-up) (global-set-key (kbd "C-c S") #'windmove-delete-down) (global-set-key (kbd "C-c A") #'windmove-delete-left) (global-set-key (kbd "C-c D") #'windmove-delete-right) ``` Say I type `C-h e` and it opens the \*Messages\* buffer in a window below the current one, which remains selected, then I can type `C-c S` to delete the \*Messages\* buffer's window. Otherwise you can enable `winner-mode` and use `winner-undo`, which will undo the latest change to the arrangement of the windows. `winner-mode` binds some keys by default when it is loaded, so if you want to have `winner-undo` always available but use your own key bindings, you could add this to your init file ``` (setq winner-dont-bind-my-keys t) (winner-mode) ``` and then, for example ``` (define-key winner-mode-map (kbd "C-c q") #'winner-undo) (define-key winner-mode-map (kbd "C-c e") #'winner-redo) ``` > 2 votes --- Tags: window, keystrokes ---
thread-63020
https://emacs.stackexchange.com/questions/63020
Changing file names automatically generated by save-buffer
2021-01-27T05:04:52.663
# Question Title: Changing file names automatically generated by save-buffer When I create an email message in Emacs (`C-x m`) I generally save the file before sending it. Emacs generates an automatic filename usually with this format: ``` \*message\*-20210127-065515 ``` How can I customise this file name? I would like to remove the asterisks from the word "message". # Answer Based upon the current question posed by the O.P., and based upon a prior question by the same O.P. about a week prior thereto wherein he stated that he had recently switched to GNUS mail Opening Gnus messages to the full height of the screen , it seemed appropriate to `grep` the Emacs source code looking for likely suspects that would generate the stated buffer-name of `*message*-20210127-065515`. I expected to find a variable with a default value containing the string `*message*` that is concatenated with the date ..., which could hopefully be customized. Instead, I found that `message-set-auto-save-file-name` hard-codes the buffer-name with a slight programmatic variation depending upon whether the `system-type` is a `memq` of `'(ms-dos windows-nt cygwin)`. As such, modifying the function directly appears to be the most viable method to achieve the desired change. Because the question was a little unclear as to what the O.P. wants to achieve (i.e., the question title states "*Changing file names automatically generated by save-buffer*"), I chose not to take the chance of guessing incorrectly as to the proposed modification. As such, this answer is generic in that the O.P. can change the buffer name within the function at issue as he sees fit. We wrap the modified function in a `with-eval-after-load` statement so that the modified function gets loaded *after* the stock/built-in version loads -- otherwise, the stock/built-in version would replace the *modified* version if it loads subsequent to its attempted redefinition. The `.emacs` / `init.el` could contain the following form with the modified function at issue: `(with-eval-after-load 'message (defun message-set-auto-save-file-name ...))` > 2 votes --- Tags: email, save ---
thread-63029
https://emacs.stackexchange.com/questions/63029
How to produce UTF8 info file with makeinfo on osx?
2021-01-27T16:12:57.890
# Question Title: How to produce UTF8 info file with makeinfo on osx? In the texi file I have the directive `@documentencoding UTF-8` but makeinfo gives me a warning: unrecognized encoding name \`UTF-8' ``` raoul@MacBook-Pro-de-Raoul oef-mode % makeinfo oef-mode.texi oef-mode.texi:6: avertissement: nom d'encodage non reconnu « UTF-8 ». ``` ``` raoul@MacBook-Pro-de-Raoul oef-mode % whereis makeinfo /usr/bin/makeinfo ``` ``` raoul@MacBook-Pro-de-Raoul oef-mode % makeinfo --version makeinfo (GNU texinfo) 4.8 Copyright (C) 2004 Free Software Foundation, Inc. ``` # Answer > 2 votes The solution is to: 1. Install makeinfo with homebrew ``` raoul@MacBook-Pro-de-Raoul oef-mode % brew install texinfo raoul@MacBook-Pro-de-Raoul oef-mode % brew info texinfo texinfo: stable 6.7 (bottled) [keg-only] ``` As explained during installation, texinfo is keg-only, which means it was not symlinked into /usr/local, because macOS already provides this software and installing another version in parallel can cause all kinds of trouble. 2. So you need to have texinfo first in your PATH with this command: ``` echo 'export PATH="/usr/local/opt/texinfo/bin:$PATH"' >> ~/.zshrc ``` 3. Don't use eshell but the Terminal or shell in emacs. --- Tags: osx, utf-8 ---
thread-63028
https://emacs.stackexchange.com/questions/63028
Syntax highlighting in C++ fails in user-defined literals
2021-01-27T16:08:00.723
# Question Title: Syntax highlighting in C++ fails in user-defined literals The C++11 way to separate the parts of a user-defined numeric (integer or floating point) literal with `'` as e.g. in `1'500ms` stalls parsing for syntax highlighting. I couldn't find anything on the net about this - my new team makes heavy use of this and I am the only Emacs user, so it is me who has to adapt. Is there a way to make the parser for C++ recognize the new syntax without too much hassle? See also: https://en.cppreference.com/w/cpp/language/user\_literal # Answer What version of emacs do you use? I'm not able to reproduce the problem in Emacs 27.1, using this test program: ``` #include <iostream> #include <chrono> int main() { using namespace std::chrono; std::chrono::milliseconds t = 1'234ms; std::cout << t.count() << '\n'; } ``` > 0 votes --- Tags: syntax-highlighting, c++ ---
thread-45792
https://emacs.stackexchange.com/questions/45792
Can I automatically see pre-commit hook output when committing with magit?
2018-11-06T16:00:57.163
# Question Title: Can I automatically see pre-commit hook output when committing with magit? A coworker has just set up our main repo to use overcommit. It's lovely, and keeps us from invoking long CI builds which will fail for trivial reasons by warning us about issues using pre-commit hooks. But I don't feel it integrates as well with magit as I would like. Right now, my workflow looks like: 1. hit `c c` in magit to commit 2. quickly hit `$` to pop open the process buffer and watch the checks run (and they're a bit ugly too because of escape codes for color) 3. enter my commit message if successful 4. move on with my life. Hooray! What I'd *like* would be: 1. hit `c c` in magit to commit 2. magit automatically opens a buffer containing the pre-commit output, respecting color codes 3. magit lets me enter my commit message as usual Surely there's a way to get here. How would you approach it? --- N.B. I have seen "Magit show git hook output" on Emacs StackExchange, but the answer was given in 2015 and doesn't work any more! # Answer > 3 votes Magit's process buffer does not respect color codes and other control sequences and it won't do so anytime soon. Your best option is check if your githook can be told to not use those. You could automatically show the process buffer the same way the appropriate diff is automatically shown: ``` (add-hook 'server-switch-hook 'magit-commit-diff) ``` Grep Magit's source to learn about complications. One complication will be that the diff buffer will likely replace the process buffer or vice-versa. You might get around that by showing one of them in a new frame. Ah, I see the answer you linked too boils down to essentially the same approach. That answer isn't obsolete, it just doesn't address the hard problem of preventing the three buffers from stepping on each others toes. Much like this answer doesn't either. You will have to come up with a solution for that yourself. # Answer > 2 votes I solved the color issue with: ``` (with-eval-after-load 'magit (setq magit-git-environment (append magit-git-environment (list "OVERCOMMIT_COLOR=0")))) ``` This sets the `OVERCOMMIT_COLOR` env variable when running the git command, which instructs Overcommit to not format with color codes that magit-process doesn't understand. --- Tags: magit ---
thread-63026
https://emacs.stackexchange.com/questions/63026
How to apply flycheck right after a new file is opened
2021-01-27T13:32:52.427
# Question Title: How to apply flycheck right after a new file is opened I am using flycheck for for Python. I want `flycheck` to detect any errors right away when any Python file is opened. Currently it can detect if there is a modification and save operation is performed. Let's say I have following code in `hello.py` file: ``` #!/usr/bin/env python3 import os print(os.getpid()) ``` Than I have commented out `print(os.getpid())` and close the file and reopened it. At this stage flycheck does not detect that `'os' imported but unused [F401]`. I have to make some moditifications and save the file for it do detect it. --- my setup: ``` (require 'flycheck) (require 'flycheck-mypy) (setq python-shell-interpreter "python3" python-shell-prompt-detect-failure-warning nil flycheck-python-pycompile-executable "python3" python-shell-completion-native-enable nil python-shell-completion-native-disabled-interpreters '("python3") elpy-shell-echo-output nil ; ) (add-hook 'python-mode-hook (lambda () ;; (setq flycheck-mypyrc "~/venv/bin/pylint") (setq flycheck-python-pylint-executable "~/venv/bin/pylint") (local-set-key (kbd "C-c C-b") 'break-point) (setq flycheck-pylintrc "~/.pylintrc"))) ``` I am also using Getting flycheck “jump to next/previous error” to cycle, it won't also able to detect it till save is done. # Answer > 2 votes You can try the following: ``` (setq flycheck-check-syntax-automatically '(save idle-buffer-switch idle-change new-line mode-enabled) flycheck-idle-buffer-switch-delay 0) ``` This tells `flycheck` to run immediately "after you switch to a buffer". The other choices like `save`, `idle-change`, `new-line`, and `mode-enabled` are already configured as the default choices. The second option reduces the delay before the check is triggered. There is also `flycheck-idle-change-delay` which you can reduce if you want. --- Tags: python, flycheck ---
thread-58015
https://emacs.stackexchange.com/questions/58015
How to stop lsp-mode including headers automatically for C/C++ code?
2020-04-24T03:12:47.440
# Question Title: How to stop lsp-mode including headers automatically for C/C++ code? Every now and then lsp-mode is adding a header to the C source code I'm working on. How can this functionality be disabled? # Answer > 8 votes Maybe this is a bit late, but I'm also annoyed by this problem and clangd seems to have trouble working with multiple files. You can use `lsp-clients-clangd-args` to configure your clangd. Add the following: ``` (setq lsp-clients-clangd-args '("--header-insertion=never")) ``` For more flags, see `clangd --help`. --- Tags: lsp-mode ---
thread-60228
https://emacs.stackexchange.com/questions/60228
Cannot access ELPA from Emacs behind a corporate proxy (Mac)
2020-08-19T21:10:20.903
# Question Title: Cannot access ELPA from Emacs behind a corporate proxy (Mac) I'm having trouble accessing ELPA on my Mac from behind a corporate proxy. Emacs 27.1. I have `http_proxy` and `https_proxy` configured appropriately (I've also tried setting `url-proxy-services`). **From Emacs** (`M-x package-refresh-contents`): ``` Using a proxy for https... Contacting host: elpa.gnu.org:443 elpa.gnu.org/0 nodename nor servname provided, or not known Package refresh done Failed to download ‘gnu’ archive. ``` **From Terminal**: ``` hostname:~ 000$ gnutls-cli -V --ca-verification --x509cafile=/tmp/master.pem elpa.gnu.org Processed 205 CA certificate(s). Resolving 'elpa.gnu.org:443'... Cannot resolve elpa.gnu.org:443: nodename nor servname provided, or not known hostname:~ 000$ nslookup elpa.gnu.org Server: XXX.XXX.XXX.XXX Address: XXX.XXX.XXX.XXX#53 ** server can't find elpa.gnu.org: NXDOMAIN ``` It looks like `gnutls` and `nslookup` are having trouble resolving the domain (`nodename nor servname provided, or not known` is the same error that Emacs is throwing). However `curl` has no issues: ``` hostname:~ 000$ curl elpa.gnu.org|head <!doctype html> <html> <head> <title>GNU Emacs Lisp Package Archive</title> ``` What am I missing? # Answer I was able to work around this issue by using Squid as described here. Note that I still see the `elpa.gnu.org/0 nodename nor servname provided, or not known` error. > 1 votes # Answer Emacs `package.el` supports local package repo. So here is the solution, ``` (setq package-archives '(("myelpa" . "~/myelpa/"))) ``` > 1 votes --- Tags: package-repositories, gnutls, proxy ---
thread-63043
https://emacs.stackexchange.com/questions/63043
Debuggable emacs and vanilla emacs binaries
2021-01-28T05:43:57.933
# Question Title: Debuggable emacs and vanilla emacs binaries I'm running Ubuntu 20.04. I would like to build an emacs binary for general usage (no debug symbols) and another emacs binary (when something goes wrong). The build is pretty straight-forward, but I don't know how to have both debug and non-debug binaries exist at the same time. Is it enough to `./autogen.sh && ./configure -ggdb3 -O0 && make` \- and then copy the resulting `src/emacs` debuggable binary to a temporary directory. Followed by `./autogen.sh && ./configure && make && make install` which will create (in my case) a `/usr/local/bin/emacs-28.0.50` Finally, can I simply copy the binary I configured with debug flags to /usr/local/bin/emacs-28.0.50-debug and call that file when needed? Or - do I have to included other emacs-related files when I debug emacs? # Answer Why not just leave the debug symbols in place? They don't use up any extra memory, or slow the program down. I suspect that what you really want is an optimized and an unoptimized build, both with symbols. It is frequently the case that optimizations can make a program more difficult to debug, often by rearranging the order of operations or making it more difficult to discover the values of variables. If that's the case, then you could install the optimized build as normal and then just leave the unoptimized build in the source directory. When you need it you can just run it from there. Another option is to install the Ubuntu Emacs packages as usual, and keep an unoptimized copy you've built yourself. Keep in mind that for every Ubuntu package there are corresponding source and debug symbol packages that you can also install. Installing them will enable you to have the exact source code and debug symbols for the Emacs you have installed via the deb package as well as for the version you've built yourself. > 0 votes --- Tags: debugging, ubuntu, build, debug ---
thread-63034
https://emacs.stackexchange.com/questions/63034
How to save vim registers in evil mode for use after restarting emacs
2021-01-27T19:17:20.357
# Question Title: How to save vim registers in evil mode for use after restarting emacs In evil mode, I can save text in named registers with `"ay` etc. These registers are lost whenever emacs is restarted. Is there a way to save these registers? Vim seems to do this automatically. # Answer There are several ways of persisting data in Emacs, such as using desktop.el or savehist. If you have enabled `savehist-mode` in your init file (like by adding `(add-hook 'after-init-hook 'savehist-mode)`), it's a matter of defining one extra variable to save: ``` (setq savehist-additional-variables '(register-alist)) ``` > 4 votes --- Tags: evil ---
thread-18536
https://emacs.stackexchange.com/questions/18536
Can't remove cursor blinking in console mode
2015-12-01T22:32:28.227
# Question Title: Can't remove cursor blinking in console mode Emacs 24.3.1, OS: Linux Slackware 14.1. In my ~/.bash\_profile file I have the following: ``` # If on console, change cursor colour according to # /usr/src/linux/Documentation/VGA-softcursor.txt # Reset using echo -e '\033[?2c' if [ $TERM = 'linux' -a $SHELL == '/bin/bash' ] ; then echo -e '\033[?17;0;64c' fi ``` This makes cursor non-blinking and makes it red. When I start Emacs the cursor becomes a blinking dash. In Displaying the Cursor chapter I read this: > On a text terminal, the cursor’s appearance is controlled by the terminal, largely out of the control of Emacs. Some terminals offer two different cursors: a “visible” static cursor, and a “very visible” blinking cursor. By default, Emacs uses the very visible cursor, and switches to it when you start or resume Emacs. If the variable visible-cursor is nil when Emacs starts or resumes, it uses the normal cursor. So in ~/.emacs I wrote: ``` (setq visible-cursor nil) ``` And restarted Emacs. But it didn't help: the cursor is still blinking, and when I close Emacs it destroys my previous non-blinking cursor. How to fix? # Answer > 2 votes This is an old question but I ran to this issue just today, in Debian 10. Terminals used are Konsole in Debian on the metal and wsltty in WSL. For me setting `visible-cursor` variable to `nil` worked. The cursor stopped blinking in terminal Emacs. Outside of Emacs, the cursor was not blinking anyway since that's what I had configured. `blink-cursor-mode` was off already too. --- Tags: terminal-emacs, cursor ---
thread-59473
https://emacs.stackexchange.com/questions/59473
noqa does not suppress the warning for flake8
2020-07-05T21:03:39.507
# Question Title: noqa does not suppress the warning for flake8 The example warning I am getting is `Item "None" of "Optional[IO[bytes]]" has no attribute "close"]`, as making the line bold and red. This usually occurs if Python cannot detect the type or its function. The way I imported: `from subprocess import PIPE, STDOUT, CalledProcessError, Popen, check_output` --- * Using `# NOQA`, `# flake8: noqa` did not help, represented as `flycheck-warning'`. I still want to see the warning for unused imports but if I use `# noqa` I want them to go away. --- Setup file, complete section for flycheck is here: https://gist.github.com/avatar-lavventura/e8713d871696538bf59a0c0245a878ec : ``` (use-package flycheck-pycheckers :after flycheck :ensure t :init (with-eval-after-load 'flycheck (add-hook 'flycheck-mode-hook #'flycheck-pycheckers-setup) ) (setq flycheck-pycheckers-checkers '( mypy3 pyflakes ) ) ) ``` --- In my configuraiton I believe `flake8` is enabled. ``` Elpy Configuration Emacs.............: 26.3 Elpy..............: 1.34.0 Virtualenv........: venv (/home/alper/venv) Interactive Python: python3 3.7.5 (/home/alper/venv/bin/python3) RPC virtualenv....: rpc-venv (/home/alper/.emacs.d/elpy/rpc-venv) Python...........: python 3.7.5 (/home/alper/.emacs.d/elpy/rpc-venv/bin/python) Jedi.............: 0.17.2 Rope.............: 0.16.0 Autopep8.........: 1.5.4 Yapf.............: 0.30.0 Black............: 20.8b1 Syntax checker....: flake8 (/home/alper/.local/bin/flake8) ``` --- Update: Output of `flycheck-verify-setup`: ``` Syntax checkers for buffer Driver.py in python-mode: First checker to run: python-flake8 - may enable: yes - executable: Found at /Users/alper/venv/bin/python3 - configuration file: Not found - `flake8' module: Found at "/Users/alper/venv/lib/python3.7/site-packages/flake8/__init__.py" - next checkers: python-mypy, python-pylint Checkers that may run as part of the first checker's chain: python-pylint - may enable: yes - executable: Found at /Users/alper/venv/bin/pylint - configuration file: Found at "/Users/alper/.pylintrc" - next checkers: python-mypy python-mypy - may enable: yes - executable: Found at /Users/alper/venv/bin/mypy - configuration file: Found at "/Users/alper/eBlocBroker/setup.cfg" Checkers that could run if selected: python-pycompile select - may enable: yes - executable: Found at /Users/alper/venv/bin/python3 - next checkers: python-mypy Checkers that are compatible with this mode, but will not run until properly configured: python-pyright (automatically disabled) reset - may enable: no - executable: Not found Flycheck Mode is enabled. Use C-u C-c ! x to enable disabled checkers. -------------------- Flycheck version: 32snapshot (package: 20201023.1716) Emacs version: 26.3 System: x86_64-apple-darwin19.6.0 Window system: nil ``` --- Output of `M-x -> describe-variable` AND `flycheck-checkers`: ``` flycheck-checkers is a variable defined in ‘flycheck.el’. Its value is (python-pycheckers solium-checker solidity-checker ada-gnat asciidoctor asciidoc awk-gawk bazel-buildifier c/c++-clang c/c++-gcc c/c++-cppcheck cfengine chef-foodcritic coffee coffee-coffeelint coq css-csslint css-stylelint cuda-nvcc cwl d-dmd dockerfile-hadolint elixir-credo emacs-lisp emacs-lisp-checkdoc ember-template erlang-rebar3 erlang eruby-erubis eruby-ruumba fortran-gfortran go-gofmt go-golint go-vet go-build go-test go-errcheck go-unconvert go-staticcheck groovy haml handlebars haskell-stack-ghc haskell-ghc haskell-hlint html-tidy javascript-eslint javascript-jshint javascript-standard json-jsonlint json-python-json json-jq jsonnet less less-stylelint llvm-llc lua-luacheck lua markdown-markdownlint-cli markdown-mdl nix nix-linter opam perl perl-perlcritic php php-phpmd php-phpcs processing proselint protobuf-protoc protobuf-prototool pug puppet-parser puppet-lint python-flake8 python-pylint python-pycompile python-pyright python-mypy r-lintr racket rpm-rpmlint rst-sphinx rst ruby-rubocop ruby-standard ruby-reek ruby-rubylint ruby ruby-jruby rust-cargo rust rust-clippy scala scala-scalastyle scheme-chicken scss-lint scss-stylelint sass/scss-sass-lint sass scss sh-bash sh-posix-dash sh-posix-bash sh-zsh sh-shellcheck slim slim-lint sql-sqlint systemd-analyze tcl-nagelfar terraform terraform-tflint tex-chktex tex-lacheck texinfo textlint typescript-tslint verilog-verilator vhdl-ghdl xml-xmlstarlet xml-xmllint yaml-jsyaml yaml-ruby yaml-yamllint) Original value was (ada-gnat asciidoctor asciidoc awk-gawk bazel-buildifier c/c++-clang c/c++-gcc c/c++-cppcheck cfengine chef-foodcritic coffee coffee-coffeelint coq css-csslint css-stylelint cuda-nvcc cwl d-dmd dockerfile-hadolint elixir-credo emacs-lisp emacs-lisp-checkdoc ember-template erlang-rebar3 erlang eruby-erubis eruby-ruumba fortran-gfortran go-gofmt go-golint go-vet go-build go-test go-errcheck go-unconvert go-staticcheck groovy haml handlebars haskell-stack-ghc haskell-ghc haskell-hlint html-tidy javascript-eslint javascript-jshint javascript-standard json-jsonlint json-python-json json-jq jsonnet less less-stylelint llvm-llc lua-luacheck lua markdown-markdownlint-cli markdown-mdl nix nix-linter opam perl perl-perlcritic php php-phpmd php-phpcs processing proselint protobuf-protoc protobuf-prototool pug puppet-parser puppet-lint python-flake8 python-pylint python-pycompile python-pyright python-mypy r-lintr racket rpm-rpmlint rst-sphinx rst ruby-rubocop ruby-standard ruby-reek ruby-rubylint ruby ruby-jruby rust-cargo rust rust-clippy scala scala-scalastyle scheme-chicken scss-lint scss-stylelint sass/scss-sass-lint sass scss sh-bash sh-posix-dash sh-posix-bash sh-zsh sh-shellcheck slim slim-lint sql-sqlint systemd-analyze tcl-nagelfar terraform terraform-tflint tex-chktex tex-lacheck texinfo textlint typescript-tslint verilog-verilator vhdl-ghdl xml-xmlstarlet xml-xmllint yaml-jsyaml yaml-ruby yaml-yamllint) ``` # Answer > 1 votes You have some problem(s) in your code - you did not show how you imported the subprocess module - my guess is you just written `import subprocess`, which is not what you want. Instead use `from subprocess import popen, PIPE`. The reason is if you do not import PIPE, stdout is not declared/recognised, so `p1.stdout.close()` does not exist; this also explains the message `Item "None" of "Optional[IO[bytes]]" has no attribute "close"`. --- Tags: flycheck, warning ---
thread-53974
https://emacs.stackexchange.com/questions/53974
Python for set globals()[''] variables having undefined name warning message
2019-11-25T08:18:35.520
# Question Title: Python for set globals()[''] variables having undefined name warning message I am using flycheck for for Python. For global files that I set using ( `globals()['variable']`), and later used, it gives the following warning message: `undefined name <variable> [F821]` Example: ``` globals()['var1'] = "hello_world" print(var1) # undefined name 'fID' [F821] ``` --- It underlines and colors it with red color. --- Added lines to `.emacs` ``` (require 'flycheck) (add-hook 'after-init-hook #'global-flycheck-mode) (setq-default flycheck-flake8-maximum-line-length 160) (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3") (setq flycheck-emacs-lisp-load-path 'inherit) ``` # Answer A turnaround is to declare the variable. ``` # Make flake8 happy if "var1" not in globals(): var1 = None globals()['var1'] = "hello_world" print(var1) ``` > 0 votes --- Tags: python, flycheck ---
thread-63037
https://emacs.stackexchange.com/questions/63037
Fast way to copy a link at point in org mode
2021-01-27T21:33:24.183
# Question Title: Fast way to copy a link at point in org mode If the point is on a link on org mode, how can I copy the link (complete link, including url and description) directly into the kill ring without marking the whole link, killing it and yanking it again? # Answer > 5 votes Here is an implementation using the Org mode parser in `org-element.el` as mentioned in my comment to Firmin Martin's answer: ``` (defun ndk/link-fast-copy () (interactive) (let* ((context (org-element-context)) (type (org-element-type context)) (beg (org-element-property :begin context)) (end (org-element-property :end context))) (when (eq type 'link) (copy-region-as-kill beg end)))) (define-key org-mode-map (kbd "C-c z") #'ndk/link-fast-copy) ``` I prefer it because it uses the Org mode parser, not ad-hoc regular expressions which are difficult to understand and error-prone. Also, there is some checking that I'm actually in the context of the link and if not the function does nothing. To be sure, the parser uses regexps underneath the covers for its lexical analysis, but they are presumably well-tested and robust enough that I, as a user, do not have to worry about their correctness. # Answer > 1 votes Try this function. Constraint: you should be positioned after "\[\[". ``` (defun my/org-link-copy-at-point () (interactive) (save-excursion (let* ((ol-regex "\\[\\[.*?:.*?\\]\\(\\[.*?\\]\\)?\\]") (beg (re-search-backward "\\[\\[")) (end (re-search-forward ol-regex)) (link-string (buffer-substring-no-properties (match-beginning 0) (match-end 0)))) (kill-new link-string) (message "Org link %s is copied." link-string)))) ``` --- Tags: org-mode ---
thread-63047
https://emacs.stackexchange.com/questions/63047
How to suppress `When done with a buffer, type C-x #` warning message?
2021-01-28T12:09:16.870
# Question Title: How to suppress `When done with a buffer, type C-x #` warning message? When I open a buffer I keep seeing following message in the minibuffer: `When done with a buffer, type C-x #` . Is it possible completely to suppress this message? --- I'm using `emacsclient -t -q` to open `GNU Emacs 26.3`. Following lines are in the `.zshrc` file. ``` export ALTERNATE_EDITOR="" export EDITOR="emacsclient -t" ``` # Answer The only way to avoid that message with Emacs earlier than 28.1 is to invoke `emacsclient` with the `-n` (`--nowait`) option. --- Starting with Emacs 28.1 (basically, current upstream at the time of writing), there is a variable to do that: Customizing `server-client-instructions` and toggling it off *should* turn off that message, ~~but I cannot confirm: either my emacs session is curdled or there is something else that's funky~~. The doc string of the variable says: > Documentation: > > If non-nil, display instructions on how to exit the client on connection. > > If nil, no instructions are displayed. EDIT: after restarting emacs (actually, a newer version that I had installed - this was an opportunity to kill the old emacs and start with the new version), I can see the variable and it does seem to work as described. The explanation here is that I went from a version that did not have the variable to a version that did. Here's the commit that added the variable. EDIT (in response to the OP's comment): to customize the variable, ask for its description with `C-h v server-client-instructions RET`, hit the `customize` link where it says "You can `customize` this variable" and when the customize interface comes up, hit the `Toggle` button to toggle it off (nil) and then hit `Apply and Save` to save it permanently. > 6 votes --- Tags: emacsclient, echo-area, message ---
thread-63054
https://emacs.stackexchange.com/questions/63054
How do I open an inferior Python process in a full window from the command line?
2021-01-28T17:20:34.403
# Question Title: How do I open an inferior Python process in a full window from the command line? From the command line, I want to open an inferior Python process in a full window. I have tried: `emacs --eval '(run-python)'`, but when Emacs opens, the `*scratch*` buffer is shown instead of the inferior Python process buffer. The Python process is started, but it is not the focused buffer. From the command line, how do I focus the inferior Python process in a full window when starting Emacs? Assume that I am using GNU Emacs 26.3 with no custom configuration (i.e. `emacs --no-site-file --no-init-file ...`). # Answer I have found a solution: ``` emacs --eval '(progn (pop-to-buffer (process-buffer (run-python))) (delete-other-windows))' ``` This starts an inferior Python process, focuses it, and makes it take up the whole frame. > 1 votes --- Tags: python, command-line-arguments ---
thread-63057
https://emacs.stackexchange.com/questions/63057
Bindings just for text buffers created by magit?
2021-01-29T02:23:00.470
# Question Title: Bindings just for text buffers created by magit? I'm trying to create a different keybinding to abort a commit in magit. Right now, when you're editing a commit message `C-c C-k` is bound to `with-editor-cancel`, which does the trick. But I'm an evil user and prefer vim-style keybindings, and I actually use evil-escape to set most of my bail-out keybindings to `ESC ESC`. My first thought was to just provide a different keybinding for `with-editor-cancel`, like to bind it in normal state to `ESC ESC` to match the rest of my escape keys. But here's the problem: Magit commit edit buffers appear to run under *text major mode* which a bunch of other modes I use constantly inherit from (markdown, org, etc.) And `with-editor-cancel` appears to be super-dangerous to have bound to a key normally. I tried it out on an org file just to see what would happen, and it *not only killed the buffer without any confirmation, but also deleted the underlying file from the file system* (!!!). This is not something I want to accidentally call. So, like, is there some way to define a keybinding only on those text-mode buffers that happen to have been created by magit? (Most of my keybindings are defined with general, but I'm happy to do it some other way.) # Answer > But here's the problem: Magit commit edit buffers appear to run under text major mode See `C-h``v` `git-commit-major-mode` You can use `define-derived-mode` to make a custom major mode, and define bindings for that major mode. > 2 votes --- Tags: key-bindings, magit, major-mode ---
thread-63060
https://emacs.stackexchange.com/questions/63060
C-x C-f Problem:
2021-01-29T08:12:10.690
# Question Title: C-x C-f Problem: When i want to create a new file with `C-x C-f` (`ido-find-file`), and type `main.lua`, Emacs does not create a new file in the current directory (`default-directory`). Instead, it visits an existing `main.lua` which is in another directory. Similarly when I want to create a new directory `src`, instead of creating a new directory Emacs visits a `src` directory in another project. This means I can never create a new file or a new directory. I've installed the package `tree-emacs`. I have the same problem when I right-click a tree-emacs buffer and try to create a new file or a new directory - Emacs visits an existing file or directory which I do not want. How can I stop Emacs from looking outside the current directory for an existing file or dir, instead of creating a buffer for a new one in the current directory? # Answer > 3 votes If you're using Ido, you can hit `C-f` whenever you want to fall back to regular `find-file`, thus preventing Ido from doing fancy things. If you want to disable the feature that lets Ido retrieve files from subdirectories for good, add ``` (setq ido-auto-merge-work-directories-length -1) ``` to your init file. Then you can always use `M-s` to invoke it manually. --- Tags: find-file, ido-find-file, treemacs ---
thread-63025
https://emacs.stackexchange.com/questions/63025
Doom Emacs -- Use a library
2021-01-27T10:19:41.653
# Question Title: Doom Emacs -- Use a library Running Doom Emacs 2.0.9 on Emacs 27.1. A library org-inlinetask provides some functionality I need. I can `SPC h P org-inlinetask` to open the library. Then I can `SPC c e` to evaluate buffer. This makes the functionality available to me. But all is lost when I restart Emacs. And I have to do these two steps again. How do I ensure that the functionality provided by the library is available on starting Emacs? # Answer > 2 votes Add `(require 'org-inlinetask)` to your init.el file. --- Tags: start-up, doom, libraries ---
thread-34657
https://emacs.stackexchange.com/questions/34657
How to limit the length of function name shown by (which-function-mode t)
2017-08-04T04:28:38.093
# Question Title: How to limit the length of function name shown by (which-function-mode t) I am using `(which-function-mode t)` to show current function name / org-heading on the mode line. I would like to limit the number of characters it shows on the mode line, but I couldn't find any option like `max-func-name` in `which-func.el`. I can limit the string by redefining `which-func-update-1` with `(which-function)` replaced by `(truncate-string-to-width (which-function) 30)`: ``` (defun which-func-update-1 (window) "Update the Which Function mode display for window WINDOW." (with-selected-window window (when which-func-mode (condition-case info (let ((current (truncate-string-to-width (which-function) 30))) (unless (equal current (gethash window which-func-table)) (puthash window current which-func-table) (force-mode-line-update))) (error (setq which-func-mode nil) (error "Error in which-func-update: %S" info)))))) ``` But it is too hacky.. I tried to use `advice` as follow: ``` (defadvice which-func-update-1 (around testing activate) (cl-letf (((symbol-function 'which-function) (lambda () (truncate-string-to-width (which-function) 30)))) ad-do-it)) ``` But it generates infinite loop. Anyone know how to limit the string length without modifying `which-func.el`? Thanks. # Answer > 3 votes By inspecting `which-function`'s source, this was found at the end of the definition: ``` ;; Filter the name if requested. (when name (if which-func-cleanup-function (funcall which-func-cleanup-function name) name)) ``` (I have no idea whether this was added in a recent Emacs version.) Therefore, setting `which-func-cleanup-function` seems to be the "official" way to customize it's output now. For example: ``` (defun my-which-func-cleanup-function (str) (truncate-string-to-width str 30)) (setq which-func-cleanup-function #'my-which-func-cleanup-function) ``` Edit: Correct argument usage Edit2: Correctly use `defun` outside of `setq` # Answer > 8 votes Instead of `around` advice use `filter-return` which will get the return value of the advised function and can do what it likes with it: ``` (advice-add 'which-function :filter-return (lambda (s) (truncate-string-to-width s 30))) ``` --- Tags: which-function-mode ---
thread-63067
https://emacs.stackexchange.com/questions/63067
how to automatically clean indented blank lines?
2021-01-29T18:04:25.997
# Question Title: how to automatically clean indented blank lines? In python mode when I'm done with an inner indented block I hit return, then backspace to return to the previous indentation and then another return so that there's a blank line before I start the code following that indented block. This leaves a blank line that has only tabs or spaces. I try and find them and remove the tabs and spaces with M-\ but it would be more convenient if there was a save file hook that would find all of them and do this cleanup. Is there something that does that? # Answer Call `delete-trailing-whitespace` from `before-save-hook`: ``` (defun my-python-mode-setup () (add-hook 'before-save-hook #'delete-trailing-whitespace nil 'local) ;; Maybe this could be helpful too (local-set-key (kbd "RET") #'reindent-then-newline-and-indent)) (add-hook 'python-mode-hook #'my-python-mode-setup) ``` This setting makes `delete-trailing-whitespace` run on save but only in in Python Mode buffers. The binding makes `RET` reindent the current line (which should remove all indentation in an empty line) before making a new one. (You can set `delete-trailing-lines` to nil to suppress the deletion of trailing empty lines, if you want.) > 4 votes --- Tags: save ---
thread-63070
https://emacs.stackexchange.com/questions/63070
Different folder for .emacs (not HOME)
2021-01-29T19:05:02.800
# Question Title: Different folder for .emacs (not HOME) My company's I.T. department has assigned our HOME directory to a network server. With the COVID-19 pandemic we are now using VPN to connect to the company's network. Having to to go through VPN to access the HOME directory is slowing the initializing of Emacs. (I have to access the HOME drive through Windows Explorer at least once or Emacs won't find it.) I would like to have Emacs access the `.emacs` file in my local user folder *without changing the HOME environment variable*. (I can't change the HOME directory because other applications use it.) How do I tell Emacs to use a different folder for initialization, without command line? (I invoke Emacs by double clicking files in the Windows 10 Explorer.) *Note: The research of changing the `.emacs` location all use the HOME environment variable.* *I'm using Emacs 27.1 on Windows 10* # Answer I use Emacs's "HOME" directory designator `~/` (as in `~/.emacs`) in Emacs 24.3.1 on MS Windows 7 to locate my .emacs file. `~/` is translated by Emacs into `c:/Users/MYUSERNAME/AppData/Roaming/` on my machine, *regardless of my current connected directory*. To see whether something like this could work for you, there are two steps you can take: 1. In Emacs, run the directory editor `dired` on the directory `~/` (by typing `C-x d ~/ RET`) to find out where Emacs thinks your home directory is located. Dired will list the files in this "home" directory, and will show the directory's full pathname on the first line. 2. Locate and read Sec. **G.5** of your built-in Emacs documentation, entitled **HOME and Startup Directories on MS Windows**. This is the fifth section of **Appendix G: Emacs and Microsoft Windows/MS-DOS** of the documentation. Sec. **G.5** is also available online at https://www.gnu.org/software/emacs/manual/html\_node/emacs/Windows-HOME.html#Windows-HOME . These steps will help you to determine whether your company's assignment of the `HOME` directory to a location *not on* your local computer has left open any possibility of locating your .emacs file *on* your local computer, in a place where Emacs will know to find and use it. One final suggestion: There is a cleaner, design-supported way to invoke Emacs, namely, include Emacs on your Windows 10 Start Menu rather than just clicking on an executable file. A Google search for "windows 10" "start menu" will bring up a lot of useful material relevant to this task. > -1 votes --- Tags: init-file, microsoft-windows, remote, networking ---
thread-63072
https://emacs.stackexchange.com/questions/63072
Why doesn't font lock work in the minibuffer?
2021-01-29T21:41:58.940
# Question Title: Why doesn't font lock work in the minibuffer? If you invoke `M-x eval-expression` then you can evaluate elisp expressions there, but there is no syntax highlight. If I turn on `emacs-lisp-mode` in the `eval-expression` prompt then the major mode is switched to emacs-lisp, but the typed expression is still not highlighted. Why is that? Why doesn't font lock work in the minibuffer? # Answer A guess is that the basic functions that read minibuffer input are defined in C, and they just don't allow/account for that. (They're also old - predating even font-lock. But that's not necessarily a/the reason they don't support font-lock.) FWIW, there's a `FIXME` comment in the code defining `read--expression`, which asks whether it should turn on `emacs-lisp-mode`. ``` (defun read--expression (prompt &optional initial-contents) (let ((minibuffer-completing-symbol t)) (minibuffer-with-setup-hook (lambda () ;; FIXME: call emacs-lisp-mode? (add-function :before-until (local 'eldoc-documentation-function) #'elisp-eldoc-documentation-function) (eldoc-mode 1) (add-hook 'completion-at-point-functions #'elisp-completion-at-point nil t) (run-hooks 'eval-expression-minibuffer-setup-hook)) (read-from-minibuffer prompt initial-contents read-expression-map t 'read-expression-history)))) ``` But as you've discovered, turning on `emacs-lisp-mode` there won't support font-lock. And neither will explicitly turning on `font-lock-mode`. > 2 votes --- Tags: font-lock, minibuffer ---
thread-63073
https://emacs.stackexchange.com/questions/63073
Is there a way to create a web link in an org-mode file which would cause the browser to load a page and then search for a text in it?
2021-01-29T21:45:48.990
# Question Title: Is there a way to create a web link in an org-mode file which would cause the browser to load a page and then search for a text in it? Running the command `org-open-at-point` on an external link such as ``` [[./file.txt::foo][Link]] ``` causes the file `file.txt` to be opened in a separate buffer and the cursor to be placed on the first occurrence of the string "foo", if such a search is successful. Unfortunately the same principle does not apply for a web link such as ``` [[http://site.com::foo][Link]] ``` as the external browser is fed the whole text of the link, in this case `http://site.com::foo`, doing no a posteriori search. Is there a way to create a web link in an org-mode file which would cause the browser to load a page and then search for a text in it? # Answer > 1 votes I think this feature is not about Org. The first example works because the link opens in emacs, and emacs supports search. You can also open a PDF in an external app and jump to a page because the apps support opening on a page. Browsers generally don't support the behavior you described. If you can script this behavior from outside of Emacs, for example with apple script or a shell script, then you could have a link open that script with the URL and the keyboard. --- Tags: org-mode ---
thread-51861
https://emacs.stackexchange.com/questions/51861
How to save clipboard or (car kill-ring) as string
2019-07-26T10:30:31.390
# Question Title: How to save clipboard or (car kill-ring) as string OS Debian GNU/Linux 7 emacs-24.3 I want to save the content of the clipboard or the last item of the kill-ring (depending whats newer) as a string so that I can do stuff with it in a eLisp function. At the moment I use this: ``` (setq zwischenablage (car kill-ring)) ``` I have 2 problems at the moment: 1. When the text was copied in emacs and was highlighted something like "#("Wechseln" 0 8 (fontified t face font-lock-doc-face))" is saved in the string. For some reason yank-handled-properties seems not to be applied. 2. When I copy text from outside emacs like the browser or so it is not used. I have to yank it and after this my function works fine. Does anyone know any solution for these problems? # Answer According to documentation of the `kill-ring` variable, interact with the kill ring directly is not recommended: > Since the kill ring is supposed to interact nicely with cut-and-paste facilities offered by window systems, use of this variable should interact nicely with `interprogram-cut-function` and `interprogram-paste-function`. The functions `kill-new`, `kill-append`, and `current-kill` are supposed to implement this interaction; you may want to use them instead of manipulating the kill ring directly. In this case solution is `(setq zwischenablage (current-kill 0 t))` > 3 votes # Answer I'm on Windows 10, and I'm not sure if this answer applies to other OSs; but it may help. I'm currently using Emacs 27.1, and I'm working on my `init.el`. I had a line at the bottom of the file which was preventing the startup screen showing. I wanted a way to move the line to somewhere at the top of my configuration file. While there are some neat functions to do this (in another Stack Exchange answer), I wanted an out of the box solution. The command `Ctrl` \+ `K` kills a line from the cursor and it seems to also copy the contents of that line to the clipboard. What I ended up doing was pressing `Ctrl` \+ `A`, `Ctrl` \+ `K`. And to paste, I did `Ctrl` \+ `Y`. > 0 votes --- Tags: yank, clipboard ---
thread-63074
https://emacs.stackexchange.com/questions/63074
Link string to url and make it clickable
2021-01-29T21:52:19.273
# Question Title: Link string to url and make it clickable In my LaTeX code I have strings like: ``` \arXivid{1602.00735} ``` that create, in the generated PDF file, a link to, e.g. https://arxiv.org/abs/1602.00735. I'd like to have the string `\arXivid{1602.00735}` clickable, like urls in `goto-address-mode`, opening the relative url in the browser. How can I do it? Do I need to use a text-property? I don't really need to fontify the string like `goto-address-mode` does. # Answer > 4 votes The standard way to define clickable text is explained in the manual. * put an appropriate face, e.g. `link` and the text property `keymap` on the link text. * bind the `follow-link` event in that keymap to a function, e.g. `arXivid-follow`, that transforms the text into a link * the function gets an event that leads you to the click position where you can extract the id and transform it into a link * follow the link with `browse-url` As lawlist indicated in his comment, you can let `font-lock` find and propertize the link text in the buffer. The following code defines a minor mode `arXivid-mode` that adds the required keyword to `font-lock-keywords`. ``` (defun arXivid-link-at-point (&optional point) "Return \\arXivid{ID} link at POINT or nil if there is none." (save-excursion (when point (goto-char point)) (skip-chars-backward "^[:space:]\\\\") (and (eq (char-before) ?\\) (looking-at "arXivid{\\([0-9.]+\\)}") (concat "https://arxiv.org/abs/" (match-string 1))))) (defun arXivid-follow (event) "Follow \\arXivid{ID} links." (interactive "e") (let ((window (posn-window (event-end event))) (pos (posn-point (event-end event))) link) (if (not (windowp window)) (error "Something is very wrong...")) (with-current-buffer (window-buffer window) (goto-char pos) (let ((link (arXivid-link-at-point))) (when link (browse-url link)))))) (defvar arXivid-keymap (let ((map (make-sparse-keymap))) (define-key map [follow-link] #'arXivid-follow) map) "Keymap for \\arXivid{ID} links.") (defvar arXivid-keywords '(("\\\\arXivid{\\([0-9.]+\\)}" (0 `(face link keymap ,arXivid-keymap) prepend))) "Additional font lock keywords for `arXivid-mode'.") (define-minor-mode arXivid-mode "Minor mode making \\arXivid{ID} clickable." :lighter " arX" (if arXivid-mode (font-lock-add-keywords nil arXivid-keywords t) (font-lock-remove-keywords nil arXivid-keywords)) (font-lock-flush) (font-lock-ensure)) ``` --- Tags: hyperlinks ---
thread-62804
https://emacs.stackexchange.com/questions/62804
Org agenda daily grid view showing wrong date
2021-01-16T05:10:00.327
# Question Title: Org agenda daily grid view showing wrong date I am trying to configure a daily agenda grid view like shown below, but for some reason it keeps showing 3 days in the past instead of the current date (at the time of posting this, it is Saturday, 16 January). ``` Wednesday 13 January 2021 Today 6:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 8:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 10:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 12:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 14:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 16:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ personal: 16:12...... Closed: DONE Clean litter box 18:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 20:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ wgu: 22:00...... Deadline: DONE Recreate virtual lab environment because I am a dumbass. 22:00...... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` Interestingly, when I open the calendar it defaults to the wrong date, but it does show "today" as having the correct date. See the bottom of this picture: Creating a new journal entry also uses the correct date. I'm not really sure why I can't get my agenda grid to show today's date. My config is as follows: ``` (use-package! org-super-agenda :hook (after-init . org-super-agenda-mode) :config (setq org-agenda-time-grid (quote ((daily today) (600 800 1000 1200 1400 1600 1800 2000 2200) "......" "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")) org-agenda-include-deadlines t org-agenda-include-diary t org-agenda-block-separator nil org-agenda-compact-blocks t org-agenda-start-with-log-mode t org-deadline-warning-days 4 calendar-latitude 34.034520 calendar-longitude -84.456010 calendar-location-name "Marietta, GA") (setq org-agenda-custom-commands '(( "z" "Super view" ((agenda "" ((org-agenda-span 'day) (org-super-agenda-groups '((:name "Today" :time-grid t :date today :scheduled today :order 1) (:name "Clocked Today" :log t))))) (alltodo "" ((org-agenda-overriding-header "~~~~~~~~~~~~~~~~~~~~ Let's get some shit done ~~~~~~~~~~~~~~~~~~~~") (org-super-agenda-groups '((:name "Due today" :deadline today :order 1) (:name "Important" :tag "important" :order 1) (:name "Overdue" :deadline past :scheduled past :order 1) (:name "Daily Habits" :tag "daily" :order 1) (:name "Habits" :habit t :order 2) (:name "Due soon" :deadline future :order 2) (:name "Working on" :todo "STARTED" :order 3) (:name "Next to do" :todo "NEXT" :order 4) (:name "Quickies" :effort< "0:30" :order 5) (:discard (:tag("bible"))) (:name "Projects" :children todo :order 6) (:discard (:anything t)))) ))))))) ``` # Answer > 0 votes Late to the party but I had the same issue and solved it following the configuration here. The trick is to specify the agenda starting day by adding `org-agenda-start-day` to your initial configuration, like so : ``` (use-package! org-super-agenda ;; ... :config *(setq org-agenda-start-day nil ; today* ;; ... )) ``` --- Tags: org-agenda, org-super-agenda ---
thread-63086
https://emacs.stackexchange.com/questions/63086
How do I move the cursor to the *Warnings* buffer whenever there is a new warning?
2021-01-30T13:00:26.357
# Question Title: How do I move the cursor to the *Warnings* buffer whenever there is a new warning? I want to focus the `*Warnings*` buffer whenever there is new warning. I tried this: ``` (add-hook 'special-mode-hook (lambda () (when (string= (buffer-name (current-buffer)) "*Warnings*") (pop-to-buffer (current-buffer))))) ``` However, the cursor only moves to the `*Warnings*` buffer on the first warning. Subsequent warnings do not move to the cursor to the `*Warnings*` buffer. What do I need to do to move the cursor to the `*Warnings*` buffer whenever there is a new warning? Emacs version: GNU Emacs 26.3. # Answer I am a strong believer in not polluting hooks, especially something so fundamental like `special-mode` that is used by countless other major-modes. As such, I would recommend *not* using the `special-mode-hook`. The following example adds an entry to the `display-buffer-alist` that will trigger a custom `display-buffer-...` function when a matching regexp exists. \[The internal function `window--display-buffer` has five (5) arguments in Emacs 25 and Emacs 26, but only four (4) arguments in Emacs 27. This example should work on all of the aforementioned versions of Emacs.\] ``` (defun display-buffer-fn (buffer-or-name alist direction &optional size pixelwise) "BUFFER: The buffer that will be displayed. ALIST: See the doc-string of `display-buffer' for more information. DIRECTION: Must use one of these symbols: 'left 'right 'below 'above SIZE: See the doc-string for `split-window'. PIXELWISE: See the doc-string for `split-window'. There are three possibilities: - (1) If a window on the frame already displays the target buffer, then just reuse the same window. - (2) If there is already a window in the specified direction in relation to the selected window, then display the target buffer in said window. - (3) If there is no window in the specified direction, then create one in that direction and display the target buffer in said window." (let* ((buffer (if (bufferp buffer-or-name) buffer-or-name (get-buffer buffer-or-name))) (window (cond ((get-buffer-window buffer (selected-frame))) ((window-in-direction direction)) (t (split-window (selected-window) size direction pixelwise))))) (window--display-buffer buffer window 'window alist) window)) (defun display-buffer-right--select-window (buffer alist) (select-window (display-buffer-fn buffer nil 'right))) (add-to-list 'display-buffer-alist '("^[*]warnings[*]$" . (display-buffer-right--select-window))) ``` \__ **TEST**: After evaluating the above code, test it by evaluating the following snippet: ``` (display-warning :warning "hello-world") ``` > 2 votes # Answer Try this ``` (add-hook 'special-mode-hook (lambda () (let ((buffer-name-list (mapcar 'buffer-name (buffer-list)))) (when (member "*Warnings*" buffer-name-list) (pop-to-buffer "*Warnings*"))))) ``` > 0 votes --- Tags: hooks, warning ---
thread-63080
https://emacs.stackexchange.com/questions/63080
How to highlight back-tick quoted strings in code-comments?
2021-01-30T05:02:06.307
# Question Title: How to highlight back-tick quoted strings in code-comments? Since back-ticks are often used for literals, is there a way I can highlight these in code comments? So this: ``` # This is a comment, this is a literal: `4 + 4`. # let's make things interesting (`literal_a`,`literal_b`). ``` Can display like this: # Answer Use `font-lock-add-keywords` for to add extra fontification. See the documentation of `font-lock-keywords`. You especially need the `OVERRIDE` flag to override the normal fontification of the comment. Use a function as `MATCHER`. That function should search for the next comment or make sure that you are in one. Afterwards it should search for your literals. The following lisp code demonstrates the procedure. It defines a minor mode `clit-mode` that highlights the literals more-or-less as you specified them. (Currently, it does not highlight ``4 + 4``. But I am confident that you can fiddle around with the code until it does exactly what you want.) Note that this code assumes that the character syntax is used for delimiting comments. It works on the basis of `syntax-ppss`. ``` (defcustom clit-regexp "`\\_<[^[:space:]]+\\_>`" "Regular expression matching literals in comments." :type 'regexp :group 'comment) (defcustom clit-face 'hi-red-b "Face for matching literals in comments." :type 'face :group 'comment) (defun clit-matcher (limit) "Search for `literal` in comments up to LIMIT." (let (found) (while (and (null found) (or (ppss-comment-depth (syntax-ppss)) (comment-search-forward limit 1))) (unless (setq found (re-search-forward clit-regexp (min (line-end-position) limit) t)) (forward-line))) found)) (defvar clit-keywords '((clit-matcher (0 clit-face t))) "Font lock keywords for `clit-mode'.") (define-minor-mode clit-mode "Minor mode for highlighting literals in comments." :lighter " `" (if clit-mode (font-lock-add-keywords nil clit-keywords t) (font-lock-remove-keywords nil clit-keywords)) (font-lock-flush) (font-lock-ensure)) ``` > 3 votes --- Tags: font-lock, backquote ---
thread-63094
https://emacs.stackexchange.com/questions/63094
Adding unicode special characters
2021-01-31T08:21:59.707
# Question Title: Adding unicode special characters I wanted to add a latin capital `O` with circumflex \[`ô`\] to a file in emacs, but for some reason all my attempts lead to the character being replaced by a question mark `?`. I tried : * `M-x` insert-char LATIN CAPITAL O WITH CIRCUMFLEX * `M-x` insert-char u00D4 * `M-x` insert-char U+00D4 * `C-x 8 RET` LATIN CAPITAL O WITH CIRUMFLEX * `C-x 8 RET` u00D4 * `C-x 8 RET` d4 * `C-x 8 RET` U+00D4 I am not sure what the problem is. When I use UNICODE hex instead of its full name the error `wrong type argument: characterp nil` comes up # Answer Those mostly work for me in Emacs 27.1, though you should note that correct name is "LATIN CAPITAL LETTER O WITH CIRCUMFLEX". If you don't have autocompletion in this prompt (there is none by default) you do have to get the name exactly correct. It supports using either the character name or the codepoint number (in hex), but not the u00D4 or U+00D4 forms. If you try the latter then you should get an "Invalid character" error. If you still can't get it to work, try running emacs -Q. If that works, then the problem is in your Emacs configuration. > 1 votes --- Tags: unicode, characters, insert-char ---
thread-63010
https://emacs.stackexchange.com/questions/63010
How can I edit the beginning of the counsel-find-file filename whilst preserving the rest
2021-01-26T09:18:59.343
# Question Title: How can I edit the beginning of the counsel-find-file filename whilst preserving the rest I work on projects with deep directory structures and have several copies in different top-level directories. I sometimes find myself wanting to open the corresponding file in one of the other directories. For example, I might have `~/tree1/a/deep/directory/structure/file.txt` open and want to open `~/tree2/a/deep/directory/structure/file.txt`. When I press C-x C-f `counsel-find-file` I'm unable to move my cursor back to the `1` to change it to a `2` \- I need to use backspace to delete each path component which I'll need to re-enter (with completion to help me) afterwards. This is a pain for long path names. Something I used previously (perhaps ido or helm, but I can't seem to find it now) let me press C-x C-f again whilst in the minibuffer to go back to stock `find-file`, which was sufficient to solve this problem. I've read the ivy documentation, but I've been unable to find a way to edit the start of the filename with `counsel-find-file`. Is there something I've missed? # Answer > 6 votes Press `C-M-y` (`ivy-insert-current-full`) to yank the current directory on to the end of the current path. This can then be edited as usual and then hitting tab goes back to normal ivy completion. Thanks to Basil for providing this in the comments to the question. --- Tags: ivy, counsel ---
thread-63098
https://emacs.stackexchange.com/questions/63098
orgmode - calculate difference between two remote tables
2021-01-31T15:31:51.427
# Question Title: orgmode - calculate difference between two remote tables I use below code to calculate the difference between two columns from remote tables but the output is all zero! ``` #+name: tbl1 | x | | 1 | | 2 | | 3 | #+name: tbl2 | y | | 1 | | 1 | | 1 | #+name: tbl3 | diff | | 0 | | 0 | | 0 | #+TBLFM: @2$1..@>$1=remote(tbl1,$1) - remote(tbl2,$1) ``` # Answer > 1 votes ``` #+name: tbl1 | x | | 1 | | 2 | | 3 | #+name: tbl2 | y | | 1 | | 1 | | 1 | #+name: tbl3 | diff | | 0 | | 1 | | 2 | #+TBLFM: @2$1..@>$1=remote(tbl1,@@#$1) - remote(tbl2,@@#$1) ``` --- Tags: org-mode, org-table ---
thread-21713
https://emacs.stackexchange.com/questions/21713
How to get property values from org file headers
2016-04-19T06:02:37.297
# Question Title: How to get property values from org file headers Is it possible to get property values from org file headers? For example, I have a file named `something.org` with following content: ``` #+TITLE: Awesome File #+AUTHOR: My Name #+XYZ: xyz /content/ ``` How could one get title or `XYZ`? I want to get those values for some buffer-local variables. # Answer > 11 votes You could use a slight modification of the answer to another question. After trying the full stuff in some org-file you can put `https://emacs.stackexchange.com/questions/21459/programmatically-read-and-set-buffer-wide-org-mode-property` into your init file and just use `org-global-props` in your org-file. ``` #+TITLE: Awesome File #+AUTHOR: My Name #+XYZ: xyz /content/ #+BEGIN_SRC emacs-lisp ;; Definition of `org-global-props' that could go into your init file: (defun org-global-props (&optional property buffer) "Get the plists of global org properties of current buffer." (unless property (setq property "PROPERTY")) (with-current-buffer (or buffer (current-buffer)) (org-element-map (org-element-parse-buffer) 'keyword (lambda (el) (when (string-match property (org-element-property :key el)) el))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Stuff for your org-file: (mapcar (lambda (prop) (list (org-element-property :key prop) (org-element-property :value prop))) (org-global-props "\\(AUTHOR\\|TITLE\\|XYZ\\)")) #+END_SRC #+RESULTS: | TITLE | Awesome File | | AUTHOR | My Name | | XYZ | xyz | ``` In order to get value of first property with `key` you can use following function. ``` (defun org-global-prop-value (key) "Get global org property KEY of current buffer." (org-element-property :value (car (org-global-props key)))) ``` For example, `(org-global-prop-value "author")` returns `My Name`. Keep in mind, that `key` respects case sensitivity rules for search. # Answer > 4 votes `org-collect-keywords` will do this for you. In your document, `(org-collect-keywords '("TITLE" "XYZ"))` will return `(("TITLE" "Awesome File") ("XYZ" "xyz"))`. --- Tags: org-mode ---
thread-21723
https://emacs.stackexchange.com/questions/21723
How can I delete mu4e drafts on successfully sending the mail?
2016-04-19T23:47:14.830
# Question Title: How can I delete mu4e drafts on successfully sending the mail? As I'm composing mail, mu4e automatically saves drafts to the `mu4e-drafts-folder`. When I send the mail, these drafts persist. I expected mu4e to delete from the folder. I'm unable to find any documentation in the mu4e manual, and I'm afraid I'm still too new to this codebase to see how to hack together what I want. Is there a user option to enable deletion on send? Or an obvious function I can drop into, say, `message-sent-hook`? # Answer If you use offlineimap (like I do) then your drafts likely accumulate because offlineimap syncs emacs' #autosave# files (kept in Drafts/cur folder). As offlineimap can only ignore files starting with '.' (and it's not configurable) the solution is to change the way draft autosaves are named: ``` (defun draft-auto-save-buffer-name-handler (operation &rest args) "for `make-auto-save-file-name' set '.' in front of the file name; do nothing for other operations" (if (and buffer-file-name (eq operation 'make-auto-save-file-name)) (concat (file-name-directory buffer-file-name) "." (file-name-nondirectory buffer-file-name)) (let ((inhibit-file-name-handlers (cons 'draft-auto-save-buffer-name-handler (and (eq inhibit-file-name-operation operation) inhibit-file-name-handlers))) (inhibit-file-name-operation operation)) (apply operation args)))) (add-to-list 'file-name-handler-alist '("Drafts/cur/" . draft-auto-save-buffer-name-handler)) ``` Other possible option would be to store all autosaves in a dedicated folder (check auto-save-file-name-transforms variable). > 7 votes # Answer I was suffering from the same problem. The solution I chose is to disable `auto-save-mode` in mu4e-compose so that drafts do not accumulate: ``` (add-hook 'mu4e-compose-mode-hook #'(lambda () (auto-save-mode -1))) ``` Plus obviously, set `mu4e-sent-messages-behavior` to `delete`, as suggested by previous answers (especially in Gmail since Gmail takes care of sent messages): ``` (setq mu4e-sent-messages-behavior 'delete) ``` > 5 votes # Answer I like the answer above (with 0 votes; can't help, reputation = 1). I was having exactly this problem, and didn't like the idea of temp and autosaves accumulating locally, even if offlineimap didn't sync them. What I did was prepend an `rm` statement to the `mu4e-get-mail-command` variable set in `~/.emacs`. This assumes you're using maildir format locally. So for me, with offlineimap and an otherwise typical GmailMailDir setup, this was: ``` (setq mu4e-get-mail-command "rm -f ~/.mail/\[Gmail\].Drafts/cur/*~ ; rm -f ~/.mail/\[Gmail\].Drafts/cur/cur/\#* ; /usr/local/bin/offlineimap -o") ``` in my `~/.emacs`. This catches the temp files (affixed with `~`) and autosaves (bracketed with `#`). There are two drawbacks: 1. Your emacs buffer temp and autosaves for drafts will be deleted every time you check your mail. 2. If you have silly drafts already synced, they'll back-sync to your local repo (and not look like emacs buffer autosaves). I had to delete mine on Gmail. If you wanted to "replicate" the better answer above in a Bash way instead of emacs, you could change this strategy to an `mv` instead of an `rm`. > 1 votes # Answer Jordan He's solution works great, but I didn't like the idea of possibly loosing a draft in case of a crash (and manually saving the draft with `save-buffer` leads to the same problem of leaving a draft behind). event's suggestion to rename the auto-save files didn't work for me for some reason, so I decided to follow their second suggestion, namely have all auto-save files in a dedicated folder. It works very well and, as an added benefit, I find that it makes it easier to clean auto-save files left behind in contexts that have nothing to do with emails and I like not having those auto-save files all over the place, cluttering all directories. So this is what I have in my init file: ``` (setq auto-save-file-name-transforms `((".*" "~/.emacs.d/auto-save/" t))) ``` > 1 votes # Answer You should set `mu4e-sent-messages-behavior` to the desired value (from the docs): ``` * `sent' move the sent message to the Sent-folder (`mu4e-sent-folder') * `trash' move the sent message to the Trash-folder (`mu4e-trash-folder') * `delete' delete the sent message. ``` You probably want to do `(setq mu4e-sent-messages-behavior 'sent)`, unless you use Gmail, in which case you want `'delete`. > -1 votes --- Tags: mu4e ---
thread-29918
https://emacs.stackexchange.com/questions/29918
Dictation in Mac OS doesn’t leave spaces between words in Emacs
2017-01-10T07:14:14.920
# Question Title: Dictation in Mac OS doesn’t leave spaces between words in Emacs I have tried to use the dictation feature of Mac OS in Emacs and it works quite well, except that it doesn’t seem to recognise spaces between words if I pause shortly and also omits spaces between sentences. Example: > This is a testAnd dictation in Emacs. It seems like spaces are omittedIf you use the dictation Feature.Is this possible to solve? Reading this answer on apple.stackexchange it seems like it has to do with the interaction between the feature in the OS and the application, in this case Emacs. # Answer > 1 votes I have the same behavior when editing code, but not in fundamental mode (`M-x fundamental-mode`). Probably some language-specific mechanism is interfering, but other than that there doesn't appear a fundamental flaw in Emacs' Dictation integration. --- Tags: osx, text-editing ---
thread-63105
https://emacs.stackexchange.com/questions/63105
User emacs has no home directory
2021-02-01T09:08:26.940
# Question Title: User emacs has no home directory I am an emacs newbie running emacs doom on Linux. I am learning how to use traditional emacs in my free time and have an emacs config file that I want to test out. I launch my traditional emacs by running: ``` emacs -u <path to my handmade emacs file> & ``` It starts up, doesn't load my configuration settings and gives me the error message: > Error (initialization): User emacs has no home directory How can I load my custom files without destroying the existing doom configuration? # Answer > 2 votes You should look at `emacs --help`. The switch to use here should be "-l" instead. Additionally, you also need "-q" so that Doom's `init.el` won't be loaded. --- Tags: init-file, linux, doom ---
thread-63108
https://emacs.stackexchange.com/questions/63108
How to use Magit to git log / git grep to find expressions across all previous commits
2021-02-01T11:38:54.667
# Question Title: How to use Magit to git log / git grep to find expressions across all previous commits I am using Magit and was wondering how to revert to a specific commit that contained a specific expression. First I need to find the expression across all commits content. How to do this? In command line it would be something like git grep / git log. Thanks! # Answer > 24 votes In Magit: * Open the Magit log buffer with `l``l` (lowercase `L` twice). * Customize the log with `L` and search for commit messages with `-``F` or for changes with `-``G`. * Once you entered your search value, press `RET` and refresh the buffer with `g`. You will see only commits that match your search. Or you can directly open the log buffer with your options with `l` → set your options → `l`. In git documentation https://git-scm.com/docs/git-log#Documentation/git-log.txt--Sltstringgt you can find more information about how to use the `-G` option > -G > > Look for differences whose patch text contains added/removed lines that match . To illustrate the difference between -S --pickaxe-regex and -G, consider a commit with the following diff in the same file: > > * return frotz(nitfol, two-\>ptr, 1, 0); ... > > * hit = frotz(nitfol, mf2.ptr, 1, 0); > > While git log -G"frotz(nitfol" will show this commit, git log \>-S"frotz(nitfol" --pickaxe-regex will not (because the number of \>occurrences of that string did not change). > > Unless --text is supplied patches of binary files without a textconv \>filter will be ignored. --- Tags: magit ---
thread-63109
https://emacs.stackexchange.com/questions/63109
How to checkout a specific commit using Magit?
2021-02-01T12:16:42.947
# Question Title: How to checkout a specific commit using Magit? When using `M-x magit-checkout`, I can only select a branch. Is it possible to visit a commit (the stage at the commit) using Magit? Thanks! # Answer > 9 votes From the magit log buffer (`l l` (lowercase `L` twice)), go on the desired commit with the point (cursor) and if you press `b b` (checkout branch/revision) the commit at point will be proposed for checkout. Otherwise with enter on the commit you will see the content of the commit without checkout into it. --- Tags: magit ---
thread-63106
https://emacs.stackexchange.com/questions/63106
Invalid function in font-lock-fontify-keywords-region
2021-02-01T09:39:30.043
# Question Title: Invalid function in font-lock-fontify-keywords-region Why do I get the error: `font-lock-fontify-keywords-region: Invalid function: (concat "\\\\" (regexp-opt (quote ("cs" "hepth" "hepph" "heplat" "hepex" "nuclth" "nuclex" "grqc" "qalg" "dgga" ...))) "{\\([0-9]+\\)}")` when this code is evaluated?: ``` (defvar biblinks-keywords '(((concat "\\\\" (regexp-opt '("cs" "hepth" "hepph" "heplat" "hepex" "nuclth" "nuclex" "grqc" "qalg" "dgga" "accphys" "alggeom" "astroph" "chaodyn" "condmat" "nlinsys" "nlinsi" "nlin" "quantph" "solvint" "suprcon" "mathph" "physics")) "{\\([0-9]+\\)}") (0 `(face link keymap ,oldarXivid-keymap) prepend)))) ``` If I use the following code instead, it works: ``` (defvar biblinks-keywords '(("\\\\\\(?:a\\(?:ccphys\\|lggeom\\|stroph\\)\\|c\\(?:haodyn\\|ondmat\\|s\\)\\|dgga\\|grqc\\|hep\\(?:ex\\|lat\\|[pt]h\\)\\|mathph\\|n\\(?:lin\\(?:s\\(?:i\\|ys\\)\\)?\\|ucl\\(?:ex\\|th\\)\\)\\|physics\\|q\\(?:alg\\|uantph\\)\\|s\\(?:olvint\\|uprcon\\)\\){\\([0-9]+\\)}" (0 `(face link keymap ,oldarXivid-keymap) prepend)))) ``` # Answer > 1 votes The documentation for `font-lock-keywords` tells us: ``` Each element in a user-level keywords list should have one of these forms: MATCHER (MATCHER . SUBEXP) (MATCHER . FACENAME) (MATCHER . HIGHLIGHT) (MATCHER HIGHLIGHT ...) (eval . FORM) where MATCHER can be either the regexp to search for, or the function name to call to make the search ... ``` Your keywords list was: ``` (((concat "\\\\" (regexp-opt '("cs" ...))))) ``` And so the first item of that list is: ``` ((concat "\\\\" (regexp-opt '("cs" ...)))) ``` Which is a cons cell, so the `car` of that value will be `MATCHER` (as it is not `eval`). The car is: ``` (concat "\\\\" (regexp-opt '("cs" ...))) ``` `MATCHER` can either be a regexp or a function name, and it's *not* a regexp (that would be a string), so it has to be a function name. Therefore Emacs tries to call the function with the name: ``` (concat "\\\\" (regexp-opt '("cs" ...))) ``` Hence: ``` Invalid function: (concat "\\\\" (regexp-opt (quote ("cs" ...)))) ``` --- Tags: quote, error ---
thread-63118
https://emacs.stackexchange.com/questions/63118
How to copy a function?
2021-02-01T20:25:14.403
# Question Title: How to copy a function? If I get the function definition with ``` (setq wrapped-copy (symbol-function 'fn)) ``` how can I make a copy such that I can redefine the same function with a wrapped version? like ``` (fset 'fn #'(lambda () (wrapped-copy))) ``` I tried with `copy-seq` but I think it copies by reference, so the anon function looses the function definition in the wrapped copy # Answer > 3 votes Use `funcall` or `apply`: ``` (setq wrapped-copy (symbol-function 'emacs-version)) (fset 'fn (lambda () (funcall wrapped-copy))) (fn) "GNU Emacs 28.0.50 (build 1, x86_64-pc-linux-gnu, GTK+ Version 2.24.32, cairo version 1.16.0) of 2020-06-15" ``` Although, in general, I would use an advice for wrapping a function. --- Tags: aliases ---
thread-63049
https://emacs.stackexchange.com/questions/63049
Doom Emacs start-up problems
2021-01-28T14:31:58.697
# Question Title: Doom Emacs start-up problems Running Doom Emacs 2.0.9 on Emacs 27.1. In my `init.el` I have org-roam enabled like so: ``` :lang (org +roam +journal) ``` In my `config.el` I also load org-habits, hide it in initial agenda view and set-up a keyboard binding like so: ``` (after! org (map! :map evil-org-agenda-mode-map :desc "Save all org buffers" :m "s s" 'org-save-all-org-buffers) (add-to-list 'org-modules 'org-habit) (setq org-habit-show-habits nil)) ``` When I start emacs, at times (and very often) it shows all tasks that are habits as if they are normal tasks. Multiple restarts sets this right. The keyboard binding is never available. I need to select the region and evaluate it to get the keybinding. Lastly, org-roam auto-complete does not work reliably. At times, it does not work. Again, a restart (or several restarts) sets things right. What could be the trouble? How can I ensure that everything works as expected right form the word go? # Answer I've done something similar with evil-org-agenda, I think you want to run it `after! evil-org-agenda` (and not `after! org`) since that's where the key map is set (thus overriding your settings). As for org-habit, try adding `(require 'org-habit)`. > 0 votes --- Tags: org-mode, org-agenda, start-up, doom, org-roam ---
thread-63121
https://emacs.stackexchange.com/questions/63121
How do I focus the Man mode window when it is displayed?
2021-02-02T01:00:26.860
# Question Title: How do I focus the Man mode window when it is displayed? When I open a man page (e.g. `M-x man cat`) I would like to automatically move my cursor onto the man page. I already know how to achieve this behavior for `*Help*` and `*Apropos*`, and I want to get the same behavior for Man mode too. I have tried this: ``` (add-hook 'Man-mode-hook (lambda () (pop-to-buffer (current-buffer)))) ``` This works when opening a man page for the first time. However, when opening the same man page a second time, the Man window will be shown, but the cursor will not be moved to it. For example, if I do `M-x man cat` for the first time, the man page for "cat" will be shown and the cursor will be moved to it. However, if I delete the man page window (`C-x 0`) and ask for the same man page again (`M-x man cat`), the man page for "cat" will be shown, but the cursor will not be moved to it. How do I automatically select the Man mode buffer when it is shown? # Answer > 5 votes See the variable `Man-notify-method`, which can be customized. Specifically, the O.P. may be interested in the value `'aggressive`. The following is a printout of the `*Help*` buffer for `C-h v` aka `M-x describe-variable`: ``` Man-notify-method is a variable defined in ‘man.el’. Its value is ‘friendly’ You can customize this variable. Probably introduced at or before Emacs version 19.29. Documentation: Selects the behavior when manpage is ready. This variable may have one of the following values, where (sf) means that the frames are switched, so the manpage is displayed in the frame where the man command was called from: newframe -- put the manpage in its own frame (see ‘Man-frame-parameters’) pushy -- make the manpage the current buffer in the current window bully -- make the manpage the current buffer and only window (sf) aggressive -- make the manpage the current buffer in the other window (sf) friendly -- display manpage in the other window but don’t make current (sf) polite -- don’t display manpage, but prints message and beep when ready quiet -- like ‘polite’, but don’t beep meek -- make no indication that the manpage is ready Any other value of ‘Man-notify-method’ is equivalent to ‘meek’. ``` --- Tags: window, hooks, focus, man, selected-window ---
thread-63125
https://emacs.stackexchange.com/questions/63125
Org-mode navigate in list
2021-02-02T06:44:55.347
# Question Title: Org-mode navigate in list How to navigate in same level list, with sub list in between? ``` - one (cursor at the beginning) - two - three - four (move to this list) ``` Tried `C-up` and `M-a`, but they go through each sub level, instead of jumping directly to next same level list. # Answer > 2 votes `M-x org-next-item` and `M-x org-previous-item` work like this: they move point to the next (or previous) list item at the same level. You can bind them to keys if you want - e.g. `C-c n` and `C-c p` are not used in the Org mode keymap by default, so you might want to use them for this: ``` (define-key org-mode-map (kbd "C-c n") #'org-next-item) (define-key org-mode-map (kbd "C-c p") #'org-previous-item) ``` --- Tags: org-mode, navigation ---
thread-63127
https://emacs.stackexchange.com/questions/63127
How to disable multiple elpy keybindings?
2021-02-02T12:19:40.183
# Question Title: How to disable multiple elpy keybindings? There are multiple `elpy` keybindings that I am not using. Is there any way to unbind them? Possible bindings that I want to disable `C-c C-t`, `C-c C-p`. I have tried following answer Globally override key binding in Emacs but it did not help. --- I have also tried following, which did not work. Still does keybindings are bind to `elpy`. ``` (global-set-key (kbd "C-c C-t") nil) (global-set-key (kbd "C-c C-p") nil) ``` # Answer `describe-key` (`C-h k C-c C-t`) shows that `C-c C-t` is defined into the `elpy-mode-map`, so you have to unbind the key from this map: ``` (define-key elpy-mode-map (kbd "C-c C-t") nil) ``` > 2 votes --- Tags: elpy ---
thread-63031
https://emacs.stackexchange.com/questions/63031
Emacs org-mode custom agenda view for each project
2021-01-27T16:28:10.517
# Question Title: Emacs org-mode custom agenda view for each project I have a project.org file that as a * Project subtree where each project I'm currently working on is tracked. I'd like to create a custom agenda view that separates out each project by project so I can see what items I have open for each project. I've been able to do something similar for work that has been delegated by using tags, but in this case I don't want to have to tag every item in order to separate it out. How might I go about breaking my agenda view up based on the subtrees in my project file? Example below ``` * Project ** Project 1 *** TODO Task 1 ** Project 2 *** TODO Task 2 * Hiring ** Position 1 *** DONE Job Requirements ** Position 2 *** TODO Job Requirements ``` Should result in something like the following: > Project 1 unfinished tasks: > > ``` > agenda: TODO [#A] Task 1 > > ``` > > ======================================================================================================================= > > Project 2 unfinished tasks: > > ``` > agenda: TODO [#A] Task 1 > > ``` > > ======================================================================================================================= Position 2 unfinished tasks: > > ``` > inbox: TODO Job Requirements > > ``` # Answer You can configure the `org-agenda-custom-commands` variable. This is a setup to create an agenda for two project files: ``` (setq org-agenda-custom-commands '(("p" "Projects" ((agenda "" ((org-agenda-files '("project1.org")))) (agenda "" ((org-agenda-files '("project2.org")))))))) ``` > 0 votes # Answer I don't think what you're trying to do is possible out of the box. I'd suggest using category, project name, and `TODO` entry all on the same line. You will also have to label your level one headings (agenda and inbox respectively) using the `CATEGORY` property by pressing `C-c C-x p`. For example: ``` (setq org-agenda-custom-commands '(("u" "Unfinished tasks" ((tags "LEVEL=3+CATEGORY={agenda\\|inbox}" ((org-agenda-prefix-format " %-12c %-12(car (last (org-get-outline-path)))") (org-agenda-overriding-header "Unfinished tasks"))))))) ``` produces: ``` Unfinished tasks agenda Project 1 TODO Task 1 agenda Project 2 TODO Task 2 inbox Position 1 DONE Job Requirements inbox Position 2 TODO Job Requirements ``` Another options is to indent subtasks under project headings: ``` (setq org-agenda-custom-commands '(("u" "Unfinished tasks" ((tags "LEVEL>1+CATEGORY=\"agenda\"") (tags "LEVEL>1+CATEGORY=\"inbox\"")) ((org-agenda-prefix-format " %-12c %l%l") (org-agenda-overriding-header "Unfinished tasks"))))) ``` ``` Unfinished tasks agenda Project 1 agenda TODO Task 1 agenda Project 2 agenda TODO Task 2 Unfinished tasks inbox Position 1 inbox DONE Job Requirements inbox Position 2 inbox TODO Job Requirements ``` > 0 votes --- Tags: org-mode ---
thread-63133
https://emacs.stackexchange.com/questions/63133
Can you split rx into multiple variables and concatenate the evaluation
2021-02-02T19:24:46.863
# Question Title: Can you split rx into multiple variables and concatenate the evaluation I have a really useful regex for extracting DCOs: ``` (defvar my-dco-tag-re (rx (: bol (zero-or-more (in blank)) ; fresh line (any "RSTA") (one-or-more (in alpha "-")) "-by: " ; tag (one-or-more (in alpha blank "-.")) ; name blank "<" (one-or-more (not (in ">"))) ">")) ; email "Regexp to match DCO style tag.") ``` However I've just recently come up with another use case which doesn't want to start on the begining of the line. Is it possible to evaluate RX variables in RX? I thought I could do this: ``` (defvar my-bare-dco-tag-rx '((any "RSTA") (one-or-more (in alpha "-")) "-by: " ; tag (one-or-more (in alpha blank "-.")) ; name blank "<" (one-or-more (not (in ">"))) ">") ; email "Regexp to match plain DCO tag") (defvar my-dco-tag-re (rx (: bol (zero-or-more (in blank)) ; fresh line (eval my-bare-dco-tag-rx))) "Regexp to match DCO style tag.") ``` but it causes the evaluation to bug out. Any ideas? ``` Debugger entered--Lisp error: (error "Bad rx operator ‘(any \"RSTA\")’") error("Bad rx operator `%S'" (any "RSTA")) rx--translate-form(((any "RSTA") (one-or-more (in alpha "-")) "-by: " (one-or-more (in alpha blank "-.")) blank "<" (one-or-more (not (in ">"))) ">")) rx--translate(((any "RSTA") (one-or-more (in alpha "-")) "-by: " (one-or-more (in alpha blank "-.")) blank "<" (one-or-more (not (in ">"))) ">")) rx--translate-eval((my-bare-dco-tag-rx)) rx--translate-form((eval my-bare-dco-tag-rx)) rx--translate((eval my-bare-dco-tag-rx)) mapcar(rx--translate (bol (zero-or-more (in blank)) (eval my-bare-dco-tag-rx))) ``` # Answer > 2 votes > Any ideas? The `eval` construct in `rx` expects a single `rx` form, but you are giving it a list of `rx` forms. Try sequencing the spliced forms instead (or adding `:` to the beginning of `my-bare-dco-tag-rx`): ``` (defvar my-dco-tag-re (rx (: bol (zero-or-more (in blank)) (eval `(: ,@my-bare-dco-tag-rx)))) "Regexp to match DCO style tag.") ;; Or, equivalently: (defvar my-dco-tag-re (rx (: bol (zero-or-more (in blank)) (eval (cons ': my-bare-dco-tag-rx)))) "Regexp to match DCO style tag.") ``` BTW, Emacs 27 added new macros for defining named and optionally parameterised `rx` constructs, namely `rx-define`, `rx-let`, and `rx-let-eval`; see `(info "(elisp) Extending Rx")`. For example: ``` (rx-define my-bare-dco-tag (: (any "RSTA") (one-or-more (in alpha "-")) "-by: " (one-or-more (in alpha blank "-.")) blank "<" (one-or-more (not (in ">"))) ">")) (rx-define my-dco-tag (: bol (zero-or-more (in blank)) my-bare-dco-tag)) (rx my-bare-dco-tag) ;; => "[AR-T][[:alpha:]-]+-by: [.[:alpha:][:blank:]-]+[[:blank:]]<[^>]+>" (rx my-dco-tag) ;; => "^[[:blank:]]*[AR-T][[:alpha:]-]+-by: [.[:alpha:][:blank:]-]+[[:blank:]]<[^>]+>" ``` --- Tags: rx ---
thread-63112
https://emacs.stackexchange.com/questions/63112
Call apply with a macro
2021-02-01T15:35:25.697
# Question Title: Call apply with a macro Is there a way to expand a macro using a list of arguments? I tried using `apply` but then I get an error that the "function" `my/x-becomes-nil` is invalid. ``` (defmacro my/x-becomes-nil (variable x) `(if (eq ,variable ,x) (setq ,variable nil))) (let ((q 2)) (my/x-becomes-nil q 2) ;;(apply 'my/x-becomes-nil (list q 2)) ;; How to make this work? q) ``` # Answer No. As (elisp) Calling Functions tells us, for `funcall` (and it lets us know that `apply` is the same): > Special forms and macros are not allowed, because they make sense only when given the unevaluated argument expressions. `funcall` cannot provide these because, as we saw above, it never knows them in the first place. I suggest that you think about what you are *really* trying to do, i.e., the reason why you think you need/want to apply a macro to a list of args. There might be an X-Y problem here. > 3 votes # Answer ``` (defmacro my/x-becomes-nil (&rest args) (let* ((two-args (= (length args) 2)) (var (funcall (if two-args #'car #'caar) args)) (val (funcall (if two-args #'cadr #'cadar) args))) `(when (eq ,var ,val) (setq ,var nil)))) ``` Expands identically when called either as `(my/x-becomes-nil q 2)` or `(my/x-becomes-nil (q 2))`. Note that the list literal in the second case is *not* quoted. > 0 votes --- Tags: functions, elisp-macros, apply, funcall ---
thread-63136
https://emacs.stackexchange.com/questions/63136
[up/down]case-region: Skip read-only text; Operate on read-write text; No Error
2021-02-02T21:26:30.650
# Question Title: [up/down]case-region: Skip read-only text; Operate on read-write text; No Error The buffer contains a mixture of text that is read-only (with `'read-only` text properties) and read-write (i.e., no `'read-only` text properties). I want to \[up/down\]case-region as to the read-write sections, but am unable to do so due to the `'read-only` sections. How can I \[up/down\]case everything that is read-write within the defined BEG/END of the region, skipping the read-only text, and not yielding any error message? # Answer > 2 votes You could use this command: ``` (defun on-writeable-portions (fn beg end) "Call FN on all writeable subregions of BEG - END." (interactive "CCommand: \nr") (when (get-text-property beg 'read-only) (setq beg (next-single-property-change beg 'read-only nil (1+ end)))) (while (< beg end) (let ((lim (next-single-property-change beg 'read-only nil (1+ end)))) (funcall fn beg (1- lim)) (setq beg (if (< lim end) (next-single-property-change lim 'read-only nil (1+ end)) end))))) ``` --- Tags: text-properties ---
thread-63141
https://emacs.stackexchange.com/questions/63141
How to make helm follow and show files as I type?
2021-02-03T07:14:59.913
# Question Title: How to make helm follow and show files as I type? My Emacs used to have the ability to display the help buffer of each function everytime I was scrolling through M-x function candidates. How to enable it again? Thanks! # Answer > 1 votes It is called `helm-follow-mode`. According to Helm documentation (`C-h m` from inside an Helm buffer): > When `helm-follow-mode` is on (C-c C-f to toggle it), moving up and down Helm session or updating the list of candidates will automatically execute the persistent-action as specified for the current source. > If `helm-follow-mode-persistent` is non-nil, the state of the mode will be restored for the following Helm sessions. > If you just want to follow candidates occasionally without enabling `helm-follow-mode`, you can use `C-down` or `C-up` instead. Conversely, when `helm-follow-mode` is enabled, those commands go to previous/next line without executing the persistent action. So the easiest way is to navigate with `C-down` or `C-up`. `C-c C-f` allows you to toggle this behaviour and variable `helm-follow-mode-persistent` to make it persistent. --- Tags: helm ---
thread-54768
https://emacs.stackexchange.com/questions/54768
how to convert 4 lines block text to 1 line space interrupted
2020-01-08T11:30:42.370
# Question Title: how to convert 4 lines block text to 1 line space interrupted I have a text file (name, surname, phone number) than I would import in excel and the play with column (name, surname...) The file was previously a docx file. I've converted it on as a text file. But the converted txt file, has a strange format: Repeated 6 lines block, with each field (name, surname, phone, town) ``` xxx yyy 999 zzz xxx1 yyy1 ``` repeated more times. I would compact each block in a single line and separate field by space. NOTE that `xxx1` and `yyy1` are name and surname of next person So I can import it in Excel, taking space as a separator column. How can I do that? I know I can do that in Lisp, but I do not know how. # Answer IIUC you could do that with a keyboard macro. Place the cursor at the beginning i.e. the very first x. Define the macro (and also transform the first block): ``` C-x ( C-SPC C-n C-n C-n M-% C-q C-j RET SPC RET ! C-n C-a C-x ) ``` Transform the rest by calling the macro until it fails. ``` C-u 0 C-x e ``` > 1 votes # Answer I would try with `sed` (unix utility) and regular expressions. > 0 votes # Answer You could use something like this ``` (defun my-join-n-lines (n) (dotimes (_ (1- n)) (delete-indentation t)) (forward-line)) (defun my-join-lines-loop () (interactive "*") (while (= 0 (my-join-n-lines 4)))) ``` The first function joins `n` lines, where `n` is the argument with which the function is called. The second one, which you can call with `M-x my-join-lines-loop`, calls `my-join-n-lines` with argument 4 until the buffer ends. Make sure to call it from the first line of a block otherwise it will merge all the lines with an offset with respect to your desired block-splitting. You can make `my-join-lines-loop` accept a prefix argument by using this definition instead of the simpler one above, ``` (defun my-join-lines-loop (&optional n) (interactive "P*") (while (= 0 (my-join-n-lines (or n 4))))) ``` Here the argument is optional and defaults to 4. > 0 votes --- Tags: text-editing ---
thread-63147
https://emacs.stackexchange.com/questions/63147
Toggle between relative and absolute line numbers: Lisp Syntax
2021-02-03T10:29:56.383
# Question Title: Toggle between relative and absolute line numbers: Lisp Syntax I need to define a function that toggles between value of `display-line-numbers` but can't figure out what's the correct lisp syntax to do so. Here's what I want to do: * Check if value of `display-line-numbers` set to `t` (absolute line numbers), change it to `relative` * Else (it will be set to relative) change it to absolute (`t`). Here's what I tried which is full of errors. Not having a very good hand at lisp ``` (defun cc/toggle-line-numbering () "Toggle line numbering between absolute and relative." (interactive) (if (= (describe-variable display-line-numbers) "relative") (setq display-line-numbers t) (setq display-line-numbers 'relative))) ``` # Answer `describe-variable` retrieves the documentation of a variable, it doesn't do anything with the value of the variable. You just want to test to see if the value of the variable is `eq` to something. ``` (defun cc/toggle-line-numbering () "Toggle line numbering between absolute and relative." (interactive) (if (eq display-line-numbers 'relative) (setq display-line-numbers t) (setq display-line-numbers 'relative))) ``` > 1 votes --- Tags: line-numbers ---
thread-63124
https://emacs.stackexchange.com/questions/63124
MAGIT: "precomposed unicode is not supported"
2021-02-02T03:52:12.113
# Question Title: MAGIT: "precomposed unicode is not supported" I am trying to commit in my Emacs folde, and I get this message below: ``` "precomposed unicode is not supported". ``` I have run on my Terminal "git config core.precomposeunicode false" but the problem persists after restarting Emacs. Anybody with the same problem and a solution? Thanks! # Answer > 1 votes If you want this setting to take effect in all repositories, then you have to use the `--global` (or `--system`) argument: ``` git config --global core.precomposeunicode false ``` --- Tags: magit, character-encoding ---
thread-34093
https://emacs.stackexchange.com/questions/34093
Helm-ag result buffer disappears
2017-07-11T10:36:09.547
# Question Title: Helm-ag result buffer disappears After doing a helm-ag search there is an option to 'save results in buffer'. My issue is that the result buffer disappears if another buffer or file is opened. Is there some way to prevent the buffer from disappearing? Or is there some generic way of saving a buffer to the buffer list? Note that saving the buffer to a file is not an option for me, nor is using helm-resume (in stead of the buffer). # Answer To anyone who might have the same issue, I found a solution: M-x rename-buffer. After the buffer has been given a new name it becomes persistent > 3 votes # Answer For a more persistent solution, you can customize the variable `helm-boring-buffer-regexp-list` and remove the regexes you want so the Helm result buffers stays in your buffer list > 1 votes --- Tags: helm, buffers, ag ---
thread-63149
https://emacs.stackexchange.com/questions/63149
Can't evaluate plantuml in org-mode blocks
2021-02-03T12:54:45.060
# Question Title: Can't evaluate plantuml in org-mode blocks I have this weird error I don't understand : ``` #+begin_src plantuml :file img/example-uml.png @startuml class Example { - value : Integer - other : Double + up() + down() } @enduml #+end_src ``` This fails with a `wrong type argument : char-or-string-p, nil`. It seems to be a problem with the `:file` header arg as using other nonsensical values such as `:file 1` outputs `wrong type argument stringp, 1`. And `:file "example.png"` outputs `wrong type argument : char-or-string-p, nil` as well. If I remove it, the block complains it has to have a `:file` argument. This is the relevant defun in `ob-plantuml`. But it never uses `char-or-string-p` to validate the arguments. So maybe it's something with the org block ? I'll add that I have `org-plantuml-jar-path` set properly and that the creation of the image does work in `plantuml-mode`, which is all the more frustrating. I use emacs 27.1 and org-mode version 9.3. Can someone help me ? Thanks Edit : added the backtrace ``` Debugger entered--Lisp error: (wrong-type-argument char-or-string-p nil) org-babel-execute:plantuml("@startuml\nclass Example {\n- value : Integer\n- othe..." ((:colname-names) (:rowname-names) (:result-params "replace" "file") (:result-type . value) (:results . "replace file") (:exports . "results") (:session . "none") (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no") (:file . "img/example-uml.png"))) org-babel-execute-src-block(nil ("plantuml" "@startuml\nclass Example {\n- value : Integer\n- othe..." ((:colname-names) (:rowname-names) (:result-params "file" "replace") (:result-type . value) (:results . "file replace") (:exports . "results") (:file . "img/example-uml.png") (:tangle . "no") (:hlines . "no") (:noweb . "no") (:cache . "no") (:session . "none")) "" nil 4196 "(ref:%s)")) org-ctrl-c-ctrl-c(nil) funcall-interactively(org-ctrl-c-ctrl-c nil) call-interactively(org-ctrl-c-ctrl-c nil nil) command-execute(org-ctrl-c-ctrl-c) ``` # Answer > 0 votes Updating `org-mode` from 9.3 to 9.4.4 has fixed the issue. --- Tags: org-mode, org-babel ---
thread-63140
https://emacs.stackexchange.com/questions/63140
How to evaluate a list containing strings or un-evaluated blocks into a string? (like format-mode-line)
2021-02-03T06:37:55.650
# Question Title: How to evaluate a list containing strings or un-evaluated blocks into a string? (like format-mode-line) The `mode-line-format` can be a list of strings, but it can also include un-evaluated blocks, e.g: ``` (setq mode-line-format (list "Hello" '(:eval (my-function-call)) "There")) ``` I would like to store a list in a similar format which can be converted into a string. However I don't want to use `format-mode-line` as I don't want `%p` etc.. to have special meanings. Is there a utility function for doing this? Or would I need to implement the logic to extract/evaluate a string from the list myself? # Answer If you really just want a list (and not a tree like `format-mode-line`) that can be evaluated takes element-wise to strings and then concatenated `mapconcat` and `eval` are your friends: ``` (let ((my-list '("Hello, I am " (number-to-string (user-uid)) " and it is " (format-time-string " %T, %F")))) (mapconcat #'eval my-list "")) ``` The output is: ``` Hello, I am 1000 and it is 11:47:45, 2021-02-03 ``` A more general version can also be implemented quite simple in a recursive way: ``` (defun tree-to-string (tree &optional lexical) "Convert TREE recursively to a string. TREE can be one of the following: - lists with car :eval : the cdr is evaluated and the result is passed to `tree-to-string' - other lists: element-wise processed with `tree-to-string' - any other element: transformed to string with `prin1-to-string' The optional argument LEXICAL is passed to `eval'." (if (listp tree) (if (eq (car tree) :eval) (tree-to-string (eval (cons 'progn (cdr tree)) lexical)) (mapconcat (lambda (item) (tree-to-string item lexical)) tree "")) (prin1-to-string tree t))) (tree-to-string '("Hello, I am " (:eval (user-uid)) (" and it is " (:eval (format-time-string "%T, %F"))) ".")) ``` The output is: ``` Hello, I am 1000 and it is 11:47:45, 2021-02-03. ``` > 3 votes # Answer Adding an answer based on @Tobias's answer with changes. * Support `:propertize` (as `mode-line-format` does). * Support symbols (which are resolved into strings). * Call `eval` with lexical binding set to `t`. * Raise an error for unsupported values (instead of converting them into strings), this means mistakes are more easily caught. ``` (defun tree-to-string (tree) "Convert TREE recursively to a string. TREE can be one of the following: - lists with `car' `:eval' - the `cdr' is evaluated and the result is passed to `tree-to-string' - lists with `car' `:propertize' - the `caar' is passed to `tree-to-string'. - the `cddr' is passed to as properties to `propertize'. - other lists: element-wise processed with `tree-to-string' - a symbol, it's value is transformed to string with `prin1-to-string'. - any other element must be a string. " (cond ((stringp tree) tree) ((null tree) "") ((symbolp tree) ;; Support non-string symbols, allows numbers etc to be included. (prin1-to-string (symbol-value tree) t)) ((listp tree) (let ((tree-type (car tree))) (cond ((eq tree-type :eval) (tree-to-string (eval (cons 'progn (cdr tree)) t))) ((eq tree-type :propertize) (pcase-let ((`(,item . ,rest) (cdr tree))) (apply 'propertize (cons (tree-to-string item) rest)))) (t (mapconcat #'tree-to-string tree ""))))) (t (error "Found '%S' (%S), not a string, nil or `:eval' cons or list of these" (type-of tree) tree)))) ``` Example usage: ``` ;; Define a value that can be evaluated into a string at any time. (defvar my-custom-format (list "Hello, User files are in " 'user-emacs-directory " and it is " '(:eval (format-time-string "%T, %F ")) '(:propertize "This text is green" face (:background "green")) ".")) ;; Evaluate and show the string. (message "%s" (tree-to-string my-custom-format)) ``` > 0 votes --- Tags: string, formatting ---
thread-63155
https://emacs.stackexchange.com/questions/63155
How to replace the first element of the `kill-ring` by a modification of it?
2021-02-03T16:31:52.730
# Question Title: How to replace the first element of the `kill-ring` by a modification of it? I am trying to modify the string that is to yanked My goal is to modify certains paths *before* yanking, in order to transform them in relative to path actual buffer file. Following this post, I tried this simple script : ``` (setq tmp (car kill-ring-yank-pointer)) ;;(message tmp) (defun replace-in-string (what with in) (replace-regexp-in-string (regexp-quote what) with in nil 'literal)) (replace-in-string "C:\\Users\\Julien Fernandez\\Dropbox\\JULIEN" "../.." tmp) (message tmp) ``` In my `kill-ring`, I have right now : ``` C:\Users\Julien Fernandez\Dropbox\JULIEN\Screenshots\Emacs\2021-02-03_16-48-43 - Code.png ``` I get as a result : Where the file name has been modified, but obviously not as intended. What should I do ? PS : I discovered that I did not have to substitute *every* `\` in \`'/' in the path, something like : ``` ../..\Path\to\file.txt ``` works fine ... # Answer `replace-regexp-in-string` does *not* do an in-place replacement. `C-h f` tells us that it returns a *new* string: > Return a new string containing the replacements. It sounds like what you want to do is replace the first element of the `kill-ring` by the result of calling `replace-regexp-in-string` (which is a different string from the one that is currently the first `kill-ring` element). You need to do something like this, with the string you've created: ``` (setq kill-ring (cons (replace-in-string "C:\\Users\\Julien Fernandez\\Dropbox\\JULIEN" "../.." (car kill-ring)) (cdr kill-ring))) ``` --- You could instead actually modify the `kill-ring` list structure, like this, but that's generally not a great idea: ``` (setcar kill-ring (replace-in-string "C:\\Users\\Julien Fernandez\\Dropbox\\JULIEN" "../.." (car kill-ring))) ``` > 0 votes --- Tags: regular-expressions, replace, string, kill-ring ---
thread-38718
https://emacs.stackexchange.com/questions/38718
How do I set a custom name for a feed in elfeed?
2018-02-09T12:44:58.003
# Question Title: How do I set a custom name for a feed in elfeed? I use elfeed to follow some blogs and news sites. One on them is Arne Metz's "Simplify C++". This feed does not set its name so in the *elfeed-search* buffer this field is left empty. This makes it difficult to quickly scan the list of feeds to read. I have tried to find information on how to manually set the feed name in my init.el file but failed to find an answer that works. Is it even possible? Configuration of elfeed in my init.el looks like the following: ``` (use-package elfeed :ensure t :config (setq elfeed-feeds '(("http://bobby.clearit.se:8080/jenkins/job/scm/rssAll" build jenkins) ("http://planet.emacsen.org/atom.xml" emacs) ("https://stackoverflow.com/feeds/tag/emacs" emacs stack) ("https://www.masteringemacs.org/feed" emacs) ("http://endlessparentheses.com/atom.xml" emacs) ("https://oremacs.com/" emacs) ("http://pragmaticemacs.com/feed/" emacs) ("https://arne-mertz.de/feed/" cpp) ("https://isocpp.org/blog/rss/category/news" cpp) ("https://www.fluentcpp.com/feed/" cpp))) :bind ("C-x w" . elfeed)) ``` Is it possible to manually set the feed name from within the use-package declaration? # Answer > 1 votes There does not seem to be an easy way to do it using just elfeed and its variables. There is a highly recommended package elfeed-org that has this comment in its readme: "If you want to add a custom title to a feed, that is even more cumbersome..." Elfeed-org makes setting the feed title very easy: Instead of the plain feed URL as a header title, you can use an org link, e.g. `[[https://arne-mertz.de/feed/][Simplify C++]`. # Answer > 1 votes For others looking to change the name of a feed - it seems that this is now possible by using `M-x elfeed-search-set-feed-title`, as described here. --- Tags: elfeed ---
thread-63085
https://emacs.stackexchange.com/questions/63085
Problems with FTP connection via Tramp
2021-01-30T12:58:45.557
# Question Title: Problems with FTP connection via Tramp I try to create FTP connection via Tramp, but the output I get on AngeFTP is: ``` ftp> open android.local ftp: Can't connect to `192.168.0.21:21': Connection refused ftp: Can't connect to `android.local:ftp' ftp> ``` I have tried many different options, but nothing works. SFTP works fine, but I can't get FTP working. Here is my config: /etc/hosts ``` 192.168.0.21 android.local ``` ~/.netrc ``` machine android.local login foo password foo port 2221 ``` init.el ``` (set-register ?a (cons 'file "/ftp:foo@android.local:#2221:/storage/0123-4567")) ``` Any ideas? --- EDIT: I was able to connect via ftp client from the terminal (outside Tramp) with the command `ftp ftp://foo:foo@192.168.0.21:2221`, but can't replicate that via Tramp. # Answer > 1 votes There is a syntax error in the example. `"/ftp:foo@android.local:#2221:/storage/0123-4567"` must be `"/ftp:foo@android.local#2221:/storage/0123-4567"`. --- Tags: osx, tramp, ftp ---
thread-63168
https://emacs.stackexchange.com/questions/63168
Changing language with ispell
2021-02-04T10:25:16.967
# Question Title: Changing language with ispell `M-x ispell` works fine for English. However, when I try to change the dictionary, I run into difficulties. I did `M-x ispell-change-dictionary` and selected one of the options (`francais`) from the list presented. Then when I try to use `M-x ispell`, I get the following message: ``` ispell-init-process: Can't open affix or dictionary files for dictionary named "fr_FR". ``` I have the same problem when I select any language option other than `british` or `american`. I am using emacs on Fedora 33. How do I get ispell to work for other languages than English? # Answer When you run `ispell`, Emacs actually calls an external program that usually requires additional dictionaries to be installed separately. One such program you can use (which is well established and crucially the only one that I know how to set up) is GNU Aspell. Dictionaries for Aspell can be installed with `dnf`: ``` sudo dnf install aspell-fr aspell-de # and so on ``` (Of course if it's not already installed you need to install Aspell itself first: `sudo dnf install aspell`. I think all these commands translate directly for `apt`.) Now you need to tell Emacs to use Aspell instead of the default spell checker. First, call `which aspell` from the shell to get the path to Aspell's executable, then set `ispell-program-name` to that value in Emacs' init file. In Fedora 33 (and most likely a lot of other distros) Aspell's executable is located at `/usr/bin/aspell`, so I'm going to use this value: ``` (setq ispell-program-name "/usr/bin/aspell") ``` With Aspell and its dictionaries installed and Emacs set to use them, you should be good to go. --- One thing that you may find useful if you switch languages often is this snippet I had found on the EmacsWiki: ``` ;; Quickly switch dictionaries ;; Adapted from DiogoRamos' snippet on https://www.emacswiki.org/emacs/FlySpell#h5o-5 (let ((langs '("francais" "deutch" "english"))) (defvar lang-ring (make-ring (length langs)) "List of Ispell dictionaries you can switch to using ‘cycle-ispell-languages’.") (dolist (elem langs) (ring-insert lang-ring elem))) (defun cycle-ispell-languages () "Switch to the next Ispell dictionary in ‘lang-ring’." (interactive) (let ((lang (ring-ref lang-ring -1))) (ring-insert lang-ring lang) (ispell-change-dictionary lang))) (global-set-key [f10] #'cycle-ispell-languages) ; replaces ‘menu-bar-open’. ``` It makes `F10` change dictionary cycling between the languages listed in the first line. > 3 votes --- Tags: ispell ---
thread-63175
https://emacs.stackexchange.com/questions/63175
Yanking into a regexp isearch escapes the metacharacters
2021-02-04T18:59:43.387
# Question Title: Yanking into a regexp isearch escapes the metacharacters I noticed today that when I yank a string containing regexp metacharacters into an active regexp isearch, the metacharacters all get escaped. For example, if I've killed the text `foo*` and yank that string into a search, it becomes `foo\*`. My actual use case involved me generating a list of alternatives I wanted to search for in a temporary buffer, and then joining them together with `\|`. Something like `foo\|bar\|...\|baz`. In the buffer I wanted to search, I started a regexp search and pasted in that string, but it became `foo\\|bar\\|...\\|baz`. I haven't been able to find this behavior described in the docs. I got around it by calling `eval-expression` and providing my string to `search-forward-regexp`, but that's obviously kind of a hassle, and moreover doesn't let me repeat the search with a simple `C-s`. The behavior I described doesn't seem correct to me, or at least not intuitive, but is it documented somewhere? If it is correct, are there any other reasonable workarounds? # Answer You have this option with Isearch+: `isearchp-regexp-quote-yank-flag`: > **`isearchp-regexp-quote-yank-flag`** is a variable defined in `isearch+.el`. > > Its value is `t` > > Documentation: > > Non-`nil` means escape special chars in text yanked for a regexp isearch. > > You can toggle this using `M-= `` during Isearch. > > You can customize this variable. Note that though this is a user option, you can toggle its value anytime during Isearch. The option value, in effect, specifies the *default* behavior. Code is here. > 1 votes --- Tags: isearch ---
thread-63176
https://emacs.stackexchange.com/questions/63176
Open clickable filenames in the same help buffer
2021-02-04T19:31:07.947
# Question Title: Open clickable filenames in the same help buffer I looking for simple solution to open clickable filenames in the same help buffers. For example, when we display help for `add-to-list` variable and click TAB the cursor is placed on the subr.el file link. We can click the link to open this file in other window. I look for solution that will open the file in the same window rather rather than other one. I was looking for a solution to this problem and found Make opening clickable filenames from Help mode in same window, but this is too over complicated in my opinion to use (it involves using timers and killing other buffers), even if the author claim it's working. I wonder if after 4 years of initial questions anyone can propose any better solution to this problem. # Answer The following answer will affect clicking on the filename link in the `*Help*` buffer after calling either `C-h v` aka `M-x describe-variable` or `C-h f` aka `M-x describe-function`. The answer has been tested using Emacs 27, without any user-configuration other than the code snippet hereinbelow. It may also be possible to add an entry to the `display-buffer-alist` with a custom function to achieve the desired behavior, but I chose to modify the code directly instead. A comment by the O.P. in the linked thread, which was cited by the O.P. of the current thread, states (underneath the accepted answer) as follows: "*just a quick note - I made it work just changing in `help-function-def` and `help-variable-def function` calls of `pop-to-buffer` to `switch-to-buffer` ....*" By examining the code at issue, I chose to use `set-window-buffer`. So that anyone who uses this answer in the future can see that this works, I have included some messages at the outset of the functions ... feel free to comment them out *after* testing it "as-is" to verify it works as advertised. Don't forget to copy the last two (2) closing parentheses at the tail end of the code snippet ... I separated them so that we can visualize that they close out the `with-eval-after-load` and `progn` statements ... ``` (with-eval-after-load 'help-mode (progn (defun my-help-function-def--button-function (fun &optional file type) (message "my-help-function-def--button-function: %s %s %s" fun file type) (or file (setq file (find-lisp-object-file-name fun type))) (if (not file) (message "Unable to find defining file") (require 'find-func) (when (eq file 'C-source) (setq file (help-C-file-name (indirect-function fun) 'fun))) ;; Don't use find-function-noselect because it follows ;; aliases (which fails for built-in functions). (let* ((location (find-function-search-for-symbol fun type file)) (position (cdr location))) ;;; The original behavior is to call `pop-to-buffer' commented out hereinbelow: ;;; (pop-to-buffer (car location)) ;;; ;;; The O.P. of the following thread wishes to display the function ;;; definition in the same window as the *Help* buffer: ;;; https://emacs.stackexchange.com/q/63176/2287 (set-window-buffer (selected-window) (car location)) (run-hooks 'find-function-after-hook) (if position (progn ;; Widen the buffer if necessary to go to this position. (when (or (< position (point-min)) (> position (point-max))) (widen)) (goto-char position)) (message "Unable to find location in file"))))) ;;; In Emacs 27, the default behavior is to call `help-function-def--button-function'. ;;; The O.P. of the following thread wishes to display the function definition in ;;; the same window as the *Help* buffer: https://emacs.stackexchange.com/q/63176/2287 (define-button-type 'help-function-def :supertype 'help-xref 'help-function #'my-help-function-def--button-function 'help-echo (purecopy "mouse-2, RET: find function's definition")) (define-button-type 'help-variable-def :supertype 'help-xref 'help-function (lambda (var &optional file) (message "help-variable-def / help-function: %s %s" var file) (when (eq file 'C-source) (setq file (help-C-file-name var 'var))) (let* ((location (find-variable-noselect var file)) (position (cdr location))) ;;; The original behavior is to call `pop-to-buffer' commented out hereinbelow: ;;; (pop-to-buffer (car location)) ;;; ;;; The O.P. of the following thread wishes to display the variable ;;; definition in the same window as the *Help* buffer: ;;; https://emacs.stackexchange.com/q/63176/2287 (set-window-buffer (selected-window) (car location)) (run-hooks 'find-function-after-hook) (if position (progn ;; Widen the buffer if necessary to go to this position. (when (or (< position (point-min)) (> position (point-max))) (widen)) (goto-char position)) (message "Unable to find location in file")))) 'help-echo (purecopy "mouse-2, RET: find variable's definition")) )) ``` > 2 votes # Answer You can use the function `windmove-display-same-window` from `windmove.el` for this. ``` (global-set-key (kbd "M-S-0") #'windmove-display-same-window) ``` Then, in the help buffer, you can type `M-S-0` and click the link with `mouse-2` (i.e. middle click if you have the button, otherwise it's click with the left and right buttons simultaneously) to visit the linked file in the same window. It works with any command that displays a new buffer, so you can also use `M-S-0` before hitting `RET` on the link, or type `M-S-0 C-h f RET add-to-list RET` to replace the buffer you're in with the help buffer, and so on. There are other functions in `windmove.el` that tell Emacs to in what direction to place the window to be created, and more. Have a look a the various `windmove-display-*` function and at the code of `windmove.el` for more information. > 2 votes --- Tags: window, help, help-mode ---
thread-63162
https://emacs.stackexchange.com/questions/63162
Why isnt `(require 'use-package)` triggered when I open Emacs?
2021-02-04T08:42:16.097
# Question Title: Why isnt `(require 'use-package)` triggered when I open Emacs? So, here is my `init.el`: ``` (add-to-list 'load-path "~/.emacs.d/site-lisp/use-package") (require 'use-package) (with-eval-after-load 'info (info-initialize) (add-to-list 'Info-directory-list "~/.emacs.d/site-lisp/use-package/")) ``` `(use-package try :ensure t)` works only when I go next to `(add-to-list ...)` and press `C-x C-e` and then, next to `(require-package 'use-package)`, and pressing `C-x C-e`. Only if do this `use-package` is activated. When I close Emacs and re-open it I have to press `C-x C-e` again, and so on. How I can `use-package` remain active, so to speak; or how can it get triggered everytime I open Emacs? # Answer Like mentioned above your init.el file is probably not loaded properly. Please keep in mind that emacs has an particular order in which it searches for the initial init files. https://www.gnu.org/software/emacs/manual/html\_node/emacs/Find-Init.html#Find-Init `~/.emacs.el` \> `~/.emacs` \> `~/.emacs.d/init.el` That also means if there is an `~/.emacs.el` emacs will not search for `~/.emacs`, or `~/.emacs.d/init.el` anymore If you wish your init file to be `~/.emacs.d/init.el` please make sure that both of the other files don't exist. > 1 votes # Answer It sounds like Emacs doesn't load your `init.el` file at startup. Try to rename it as `~/.emacs`. > 0 votes # Answer I got it to work by removing Emacs27 and installing Emacs26 and then rebooting ie `reboot`. > 0 votes --- Tags: use-package, require ---
thread-63166
https://emacs.stackexchange.com/questions/63166
Tramp hangs indefinitely when using doas on Linux
2021-02-04T10:04:21.227
# Question Title: Tramp hangs indefinitely when using doas on Linux Tramp works fine when I try to edit with sudo or ssh, but when I try to edit with doas it will hang (while also maxing out my cpu). Here is some tramp output: ``` backtrace() tramp-signal-hook-function(quit ("")) signal(quit ("")) tramp-maybe-open-connection((tramp-file-name "doas" "root" nil "localhost" nil "/etc/doas.conf" nil)) tramp-send-command((tramp-file-name "doas" "root" nil "localhost" nil "/etc/doas.conf" nil) "test 0 2>/dev/null; echo tramp_exit_status $?") tramp-send-command-and-check((tramp-file-name "doas" "root" nil "localhost" nil "/etc/doas.conf" nil) "test 0") tramp-get-test-command((tramp-file-name "doas" "root" nil "localhost" nil "/etc/doas.conf" nil)) tramp-run-test("-d" "/doas:root@localhost:/etc/doas.conf") tramp-sh-handle-file-directory-p("/doas:root@localhost:/etc/doas.conf") apply(tramp-sh-handle-file-directory-p "/doas:root@localhost:/etc/doas.conf") tramp-sh-file-name-handler(file-directory-p "/doas:root@localhost:/etc/doas.conf") apply(tramp-sh-file-name-handler file-directory-p "/doas:root@localhost:/etc/doas.conf") tramp-file-name-handler(file-directory-p "/doas:root@localhost:/etc/doas.conf") file-directory-p("/doas:root@localhost:/etc/doas.conf") find-file-noselect("/doas:root@localhost:/etc/doas.conf" nil nil nil) find-alternate-file("/doas:root@localhost:/etc/doas.conf") (if (or arg (not buffer-file-name)) (find-file (concat "/doas:root@localhost:" (ido-read-file-name "Find file(as root): "))) (find-alternate-file (concat "/doas:root@localhost:" buffer-file-name))) er-doas-edit(nil) funcall-interactively(er-doas-edit nil) call-interactively(er-doas-edit record nil) command-execute(er-doas-edit record) execute-extended-command(nil "er-doas-edit" "er-do") funcall-interactively(execute-extended-command nil "er-doas-edit" "er-do") call-interactively(execute-extended-command nil nil) command-execute(execute-extended-command) ``` Tramp also made another buffer called `debug Tramp/ doas root@Southpark` which only contains this line: ``` 11:05:44.458693 tramp-get-connection-property (7) # process-buffer nil ``` Here is Tramp's output to the message buffer: ``` Tramp: Opening connection for root@Southpark using doas... Tramp: Sending command ‘exec doas -u root -s’ Tramp: Waiting for prompts from remote shell...failed Tramp: Opening connection for root@Southpark using doas...failed ``` I set `tramp-verbose` to 10 and this was the output: ``` backtrace() tramp-signal-hook-function(quit ("")) signal(quit ("")) tramp-maybe-open-connection((tramp-file-name "doas" #("root" 0 4 (tramp-default t)) nil #("Southpark" 0 9 (tramp-default t)) nil "/lol" nil)) tramp-send-command((tramp-file-name "doas" #("root" 0 4 (tramp-default t)) nil #("Southpark" 0 9 (tramp-default t)) nil "/lol" nil) "/bin/test -e / 2>/dev/null; echo tramp_exit_status...") tramp-send-command-and-check((tramp-file-name "doas" #("root" 0 4 (tramp-default t)) nil #("Southpark" 0 9 (tramp-default t)) nil "/lol" nil) "/bin/test -e /") tramp-find-file-exists-command((tramp-file-name "doas" #("root" 0 4 (tramp-default t)) nil #("Southpark" 0 9 (tramp-default t)) nil "/lol" nil)) tramp-get-file-exists-command((tramp-file-name "doas" #("root" 0 4 (tramp-default t)) nil #("Southpark" 0 9 (tramp-default t)) nil "/lol" nil)) tramp-sh-handle-file-exists-p(#("/doas:root@Southpark:/lol" 6 10 (tramp-default t) 11 20 (tramp-default t))) apply(tramp-sh-handle-file-exists-p #("/doas:root@Southpark:/lol" 6 10 (tramp-default t) 11 20 (tramp-default t))) tramp-sh-file-name-handler(file-exists-p #("/doas:root@Southpark:/lol" 6 10 (tramp-default t) 11 20 (tramp-default t))) apply(tramp-sh-file-name-handler file-exists-p #("/doas:root@Southpark:/lol" 6 10 (tramp-default t) 11 20 (tramp-default t))) tramp-file-name-handler(file-exists-p #("/doas:root@Southpark:/lol" 6 10 (tramp-default t) 11 20 (tramp-default t))) file-exists-p(#("/doas:root@Southpark:/lol" 6 10 (tramp-default t) 11 20 (tramp-default t))) completion-file-name-table(#("/doas:root@Southpark:/lol" 6 10 (tramp-default t) 11 20 (tramp-default t)) file-exists-p lambda) test-completion(#("/doas:root@Southpark:/lol" 6 10 (tramp-default t) 11 20 (tramp-default t)) completion-file-name-table file-exists-p) completion--file-name-table("/doas::/lol" file-exists-p lambda) complete-with-action(lambda completion--file-name-table "/doas::/lol" file-exists-p) #f(compiled-function (table) #<bytecode 0x156dc8a263a1>)(completion--file-name-table) completion--some(#f(compiled-function (table) #<bytecode 0x156dc8a263a1>) (completion--embedded-envvar-table completion--file-name-table)) read-file-name-internal("/doas::/lol" file-exists-p lambda) test-completion("/doas::/lol" read-file-name-internal file-exists-p) completion--complete-and-exit(12 23 exit-minibuffer #f(compiled-function () #<bytecode 0x156dc8a26381>)) completion-complete-and-exit(12 23 exit-minibuffer) minibuffer-complete-and-exit() funcall-interactively(minibuffer-complete-and-exit) call-interactively(minibuffer-complete-and-exit nil nil) command-execute(minibuffer-complete-and-exit) read-from-minibuffer("Find file: " "~/" (keymap (keymap (32)) keymap (10 . minibuffer-complete-and-exit) (13 . minibuffer-complete-and-exit) keymap (menu-bar keymap (minibuf "Minibuf" keymap (tab menu-item "Complete" minibuffer-complete :help "Complete as far as possible") (space menu-item "Complete Word" minibuffer-complete-word :help "Complete at most one word") (63 menu-item "List Completions" minibuffer-completion-help :help "Display all possible completions") "Minibuf")) (27 keymap (118 . switch-to-completions)) (prior . switch-to-completions) (63 . minibuffer-completion-help) (32 . minibuffer-complete-word) (9 . minibuffer-complete) keymap (menu-bar keymap (minibuf "Minibuf" keymap (previous menu-item "Previous History Item" previous-history-element :help "Put previous minibuffer history element in the min...") (next menu-item "Next History Item" next-history-element :help "Put next minibuffer history element in the minibuf...") (isearch-backward menu-item "Isearch History Backward" isearch-backward :help "Incrementally search minibuffer history backward") (isearch-forward menu-item "Isearch History Forward" isearch-forward :help "Incrementally search minibuffer history forward") (return menu-item "Enter" exit-minibuffer :key-sequence "\15" :help "Terminate input and exit minibuffer") (quit menu-item "Quit" abort-recursive-edit :help "Abort input and exit minibuffer") "Minibuf")) (10 . exit-minibuffer) (13 . exit-minibuffer) (7 . minibuffer-keyboard-quit) (C-tab . file-cache-minibuffer-complete) (9 . self-insert-command) (XF86Back . previous-history-element) (up . previous-line-or-history-element) (prior . previous-history-element) (XF86Forward . next-history-element) (down . next-line-or-history-element) (next . next-history-element) (27 keymap (60 . minibuffer-beginning-of-buffer) (114 . previous-matching-history-element) (115 . next-matching-history-element) (112 . previous-history-element) (110 . next-history-element))) nil file-name-history "~/" nil) completing-read-default("Find file: " read-file-name-internal file-exists-p confirm-after-completion "~/" file-name-history "~/" nil) completing-read("Find file: " read-file-name-internal file-exists-p confirm-after-completion "~/" file-name-history "~/") read-file-name-default("Find file: " nil "~/" confirm-after-completion nil nil) read-file-name("Find file: " nil "~/" confirm-after-completion) find-file-read-args("Find file: " confirm-after-completion) byte-code("\300\301\302 \"\207" [find-file-read-args "Find file: " confirm-nonexistent-file-or-buffer] 3) call-interactively(joe-edit nil nil) command-execute(joe-edit) ``` And the `debug tramp/doas root@Southpark` buffer was enormous, se here's the first few dozen lines ``` ;; Emacs: 27.1 Tramp: 2.4.3.27.1 -*- mode: outline; -*- ;; Location: /usr/share/emacs/27.1/lisp/net/tramp.elc Git: / 11:05:39.354574 tramp-get-file-property (8) # /lol file-exists-p undef 11:05:39.354639 tramp-get-file-property (8) # /lol file-attributes-integer nil 11:05:39.354685 tramp-get-file-property (8) # /lol file-attributes-string nil 11:05:39.354721 tramp-get-connection-property (7) # file-exists undef 11:05:39.354752 tramp-get-file-exists-command (5) # Finding command to check if file exists 11:05:39.354812 tramp-get-connection-property (7) # test undef 11:05:39.354847 tramp-get-test-command (5) # Finding a suitable ‘test’ command 11:05:39.354886 tramp-get-connection-property (7) # process-name nil 11:05:39.354921 tramp-get-connection-property (7) # process-name nil 11:05:39.354952 tramp-get-connection-property (7) # process-buffer nil 11:05:39.354990 tramp-get-connection-property (7) # process-buffer nil 11:05:39.355020 tramp-set-connection-property (7) # process-buffer nil 11:05:39.355090 tramp-maybe-open-connection (3) # Opening connection for root@Southpark using doas... 11:05:39.355176 tramp-call-process (6) # ‘locale -a’ nil *temp* 11:05:39.355887 tramp-call-process (6) # 0 C en_US.utf8 ja_JP ja_JP.eucjp ja_JP.ujis ja_JP.utf8 japanese japanese.euc POSIX 11:05:39.355948 tramp-get-local-locale (7) # locale en_US.utf8 11:05:39.356016 tramp-get-connection-property (7) # login-args undef 11:05:39.356063 tramp-get-connection-property (7) # login-args undef 11:05:39.356112 tramp-get-connection-property (7) # process-name nil 11:05:39.356151 tramp-get-connection-property (7) # process-buffer nil 11:05:39.356394 tramp-maybe-open-connection (6) # /bin/sh -i 11:05:39.356447 tramp-get-connection-property (7) # check-remote-echo nil 11:05:39.356482 tramp-get-connection-property (7) # check-remote-echo nil 11:05:39.362229 tramp-accept-process-output (10) # *tramp/doas root@Southpark* nil run t #$ 11:05:39.362301 tramp-get-connection-property (7) # check-remote-echo nil 11:05:39.362341 tramp-get-connection-property (7) # check-remote-echo nil 11:05:39.362390 tramp-wait-for-regexp (6) # #$ 11:05:39.362439 tramp-get-connection-property (7) # login-program undef 11:05:39.362485 tramp-get-connection-property (7) # login-args undef 11:05:39.362529 tramp-get-connection-property (7) # remote-shell undef 11:05:39.362574 tramp-get-connection-property (7) # async-args undef 11:05:39.362618 tramp-get-connection-property (7) # connection-timeout undef 11:05:39.362658 tramp-get-connection-property (7) # temp-file undef 11:05:39.362738 tramp-set-connection-property (7) # temp-file /tmp/tramp.LaiDu1 11:05:39.362779 tramp-set-connection-property (7) # password-vector (tramp-file-name doas root nil Southpark nil nil nil) 11:05:39.362829 tramp-get-connection-property (7) # session-timeout undef 11:05:39.362872 tramp-get-connection-property (7) # session-timeout undef 11:05:39.362910 tramp-set-connection-property (7) # session-timeout 300 11:05:39.363072 tramp-maybe-open-connection (3) # Sending command ‘exec doas -u root -s’ 11:05:39.363120 tramp-get-connection-property (7) # process-name nil 11:05:39.363162 tramp-get-connection-property (7) # remote-echo nil 11:05:39.363197 tramp-send-command (6) # exec doas -u root -s 11:05:39.363240 tramp-get-connection-property (7) # process-name nil 11:05:39.363280 tramp-get-connection-property (7) # chunksize nil 11:05:39.363317 tramp-set-connection-property (7) # last-cmd-time (24604 17795 363305 774000) 11:05:39.363358 tramp-send-string (10) # exec doas -u root -s 11:05:39.363397 tramp-get-connection-property (7) # process-buffer nil 11:05:39.363454 tramp-get-connection-property (7) # password-vector (tramp-file-name doas root nil Southpark nil nil nil) 11:05:39.363499 tramp-set-connection-property (7) # first-password-request 11:05:39.363548 tramp-process-actions (3) # Waiting for prompts from remote shell... 11:05:39.363641 tramp-accept-process-output (10) # *tramp/doas root@Southpark* 0 run nil ``` This happens when I try to run the following `er-doas-edit` edit function on the (already opened) `/etc/doas.conf`. ``` (defun er-doas-edit (&optional arg) "Edit currently visited file as root With a prefix ARG prompt for a file to visit. Will also prompt for a file to visit if current buffer is not visiting a file." (interactive "P") (if (or arg (not buffer-file-name)) (find-file (concat "/doas:root@localhost:" (ido-read-file-name "Find file(as root): "))) (find-alternate-file (concat "/doas:root@localhost:" buffer-file-name)))) ``` The same error happens no matter how I try to open the file with doas. I'm on Arch Linux. emacs --version reports: `GNU Emacs 27.1` Here is the full tramp debug buffer # Answer > 1 votes See line 178058 of the debug output. Your prompt is not understandable by Tramp, I suppose zsh is in game. Pls read the Tramp manual how to configure zsh properly. --- Tags: debugging, tramp, linux ---
thread-63187
https://emacs.stackexchange.com/questions/63187
Org Babel execute bash via ssh on non-default port; `(wrong-type-argument number-or-marker-p nil)`
2021-02-05T08:45:22.740
# Question Title: Org Babel execute bash via ssh on non-default port; `(wrong-type-argument number-or-marker-p nil)` # Problem In an org file, I have a source code block containing bash code that I want to run on a remote machine: ``` * test :PROPERTIES: :header-args:bash: :dir /ssh:skid@127.0.0.1#2221: :END: #+begin_src bash whoami #+end_src ``` Placing Mark inside the block and pressing `C-c C-c`, I expect an output block containing the username on the remote(`skid`) to appear below, but I get an error: `(wrong-type-argument number-or-marker-p nil)` # Question I'm a bit lost on how and why this fails, so; Any ideas on what goes wrong? Pointers on how to interpret the trace, for a lisp noob, will be very appreaciated. # Details ## SSH server and tramp seems fine on it's own This opens the remote folder in dired mode without errors: `emacs -nw '/ssh:skid@localhost#2221:/home/skid/10.10.10.198/'` ## Backtrace The backtrace (from doing `M-: (setq debug-on-error t)` before the above `C-c C-c`) is too long to include, so the first few lines are below, and the complete one is on pastebin: ``` Debugger entered--Lisp error: (wrong-type-argument number-or-marker-p nil) <(0 nil) (if (< 0 (file-attribute-size (file-attributes error-file))) (progn (save-current-buffer (set-buffer (get-buffer-create error-buffer)) (let ((pos-from-end (- (point-max) (point)))) (or (bobp) (insert "\f\n")) (format-insert-file error-file nil) (goto-char (- (point-max) pos-from-end))) (current-buffer)))) (progn (if (< 0 (file-attribute-size (file-attributes error-file))) (progn (save-current-buffer (set-buffer (get-buffer-create error-buffer)) (let ((pos-from-end (- ... ...))) (or (bobp) (insert "\f\n")) (format-insert-file error-file nil) (goto-char (- (point-max) pos-from-end))) (current-buffer)))) (delete-file error-file)) (if (and error-file (file-exists-p error-file)) (progn (if (< 0 (file-attribute-size (file-attributes error-file))) (progn (save-current-buffer (set-buffer (get-buffer-create error-buffer)) (let ((pos-from-end ...)) (or (bobp) (insert "\f\n")) (format-insert-file error-file nil) (goto-char (- ... pos-from-end))) (current-buffer)))) (delete-file error-file))) (let ((input-file (org-babel-temp-file "ob-input-")) (error-file (if error-buffer (org-babel-temp-file "ob-error-") nil)) (shell-file-name (cond ((and (not (file-remote-p default-directory)) (executable-find shell-file-name)) shell-file-name) ((file-executable-p (concat (file-remote-p default-directory) shell-file-name)) shell-file-name) ("/bin/sh"))) exit-status) (if (file-remote-p default-directory) nil (delete-file error-file)) (let ((swap (< start end))) (goto-char start) (push-mark (point) 'nomsg) (write-region start end input-file) (delete-region start end) (setq exit-status (process-file shell-file-name input-file (if error-file (list t error-file) t) nil shell-command-switch command)) (if swap (progn (exchange-point-and-mark)))) (if (and input-file (file-exists-p input-file) (not (if (boundp 'org-babel--debug-input) (progn org-babel--debug-input)))) (progn (delete-file input-file))) (if (and error-file (file-exists-p error-file)) (progn (if (< 0 (file-attribute-size (file-attributes error-file))) (progn (save-current-buffer (set-buffer (get-buffer-create error-buffer)) (let (...) (or ... ...) (format-insert-file error-file nil) (goto-char ...)) (current-buffer)))) (delete-file error-file))) exit-status) org-babel--shell-command-on-region(1 7 "bash" #<buffer *Org-Babel Error*>) (setq exit-code (org-babel--shell-command-on-region (point-min) (point-max) cmd err-buff)) ... org-ctrl-c-ctrl-c(nil) funcall-interactively(org-ctrl-c-ctrl-c nil) call-interactively(org-ctrl-c-ctrl-c nil nil) command-execute(org-ctrl-c-ctrl-c) ``` ## Emacs version ``` GNU Emacs 27.1 (build 1, x86_64-pc-linux-gnu, X toolkit, cairo version 1.16.0, Xaw scroll bars) ``` ## `*Messages*` buffer This is what is in my `*Messages*`, from launching emacs, to hitting the error: ``` For information about GNU Emacs and the GNU system, type C-h C-a. Starting new Ispell process /run/current-system/sw/bin/aspell with en_GB dictionary...done Setting up indent for shell type bash Indentation variables are now local. Indentation setup for shell type bash t Setting up indent for shell type bash Indentation variables are now local. Indentation setup for shell type bash executing Bash code block... Tramp: Opening connection for skid@127.0.0.1 using ssh... Tramp: Sending command ‘exec ssh -l skid -p 2221 -o ControlMaster=auto -o ControlPath='tramp.%C' -o ControlPersist=no -e none 127.0.0.1’ Tramp: Waiting for prompts from remote shell...done Tramp: Found remote shell prompt on ‘127.0.0.1’ Tramp: Opening connection for skid@127.0.0.1 using ssh...done Tramp: Encoding local file ‘/tmp/tramp.pKJ3ih’ using ‘base64-encode-region’...done Tramp: Decoding remote file ‘/ssh:skid@127.0.0.1#2221:/tmp/ob-input-xciyut’ using ‘base64 -d -i >%s’...done Tramp: Encoding local file ‘/tmp/tramp.TfMrVo’ using ‘base64-encode-region’...done Tramp: Decoding remote file ‘/ssh:skid@127.0.0.1#2221:/tmp/ob-error-PpTmjP’ using ‘base64 -d -i >%s’...done Tramp: Encoding local file ‘/tmp/tramp.5JTsQ8’ using ‘base64-encode-region’...done Tramp: Decoding remote file ‘/ssh:skid@127.0.0.1#2221:/tmp/ob-input-xciyut’ using ‘base64 -d -i >%s’...done Wrote /ssh:skid@127.0.0.1#2221:/tmp/ob-input-xciyut Entering debugger... ``` ## Temp files The following (empty) file is created when going through the above steps: ``` ~$ ssh -X -p2221 skid@localhost 'ls -ltr /tmp/ob-*' -rw-r--r-- 1 skid users 0 Feb 5 09:29 /tmp/ob-error-PpTmjP ``` From `watch -n.1 ssh -X -p2221 skid@localhost 'ls -ltr /tmp/ob-*'` it seems like nothing else is created. At least it wasn't picked up by me watching this command. # Answer 1. Tramp keeps its persistent data in `~/.emacs.d/tramp`. You can either remove this file prior starting Emacs, or trash its contents by `M-x tramp-cleanup-all-connections` any time. 2. I've tried to reproduce your scenario. I've used my own remote machine (obviously), with a non-standard port. In order to minimize interference with other packages, I have started Emacs via `emacs -Q -l org -l ob-shell`. No error, it works as expected. > 1 votes # Answer I cannot reproduce it myself any more. After repeating this tens of times (closing emacs, restarting remote), I tried switching the remote to the default ssh port (22), and it then worked when not specifying a port. It then worked when specifying port 22 in the properties, and also when moving remote back to port 2221. I keep the org file on git, and the remote host is a vm running nixos (https://gitlab.com/kidmose/dotfiles/-/tree/master/nixos/vms/htb-box) so i have no idea how this can happen. Does tramp store some state that can get messed up? > 0 votes --- Tags: org-babel, tramp, bash ---
thread-63167
https://emacs.stackexchange.com/questions/63167
How to stop ivy-switch-buffer from trying to connect
2021-02-04T10:06:01.930
# Question Title: How to stop ivy-switch-buffer from trying to connect I'm using `ivy-use-virtual-buffers` to see both currently and recently visited buffers in Swiper's `ivy-switch-buffer` and it worked great until last month when I opened distant files via ssh/Tramp. Ever since, `ivy-switch-buffer` errors, see below. Questions * How exactly is `ivy-ignore-buffers` (see config below) supposed to work ? On full buffer names (w/ path)? * How is ivy-switch-buffer trying to connect? I can see in the error buffer that is uses some username that I don't use anymore to connect... Where are those connection details stored? * Why is `ivy-switch-buffer` trying to connect in the first place ? `counsel-recentf` does not do that, the distant buffers are sitting quietly in the list, and when selected, Emacs connects (using the right SSH credentials / aliases / keys) and opens the file. Here is my configuration: ``` (use-package swiper :ensure try :bind (([f4] . ivy-switch-buffer) ([(control c) (f)] . counsel-ag) ([(control c) (g)] . counsel-git) ([(control c) (j)] . counsel-git-grep) ([(control c) (l)] . counsel-locate) ([(control d)] . swiper-ag) ([(control f)] . swiper) ([(control h) (control f)] . counsel-describe-function) ([(control h) (control v)] . counsel-describe-variable) ([(control o)] . counsel-find-file) ([(control shift o)] . counsel-recentf) ([f9] . counsel-rhythmbox) :map ivy-minibuffer-map ([(control f)] . ivy-yank-word) :map read-expression-map ([(control r)] . counsel-expression-history)) :config (progn (define-key ivy-switch-buffer-map [(control w)] (lambda () (interactive) (ivy-set-action 'kill-buffer) (ivy-done)))) :init (setq ivy-use-virtual-buffers t ivy-ignore-buffers '("^\\/ssh" ; doesn't seem to work "\\` " "\\`\\*") ivy-display-style 'fancy ivy-count-format "(%d/%d) " ivy-initial-inputs-alist nil ivy-extra-directories nil)) ``` And the errors: ``` Tramp: Opening connection for weird_username@myserver.com using ssh... Tramp: Sending command ‘exec ssh -l weird_username -o ControlMaster=auto -o ControlPath='tramp.%C' -o ControlPersist=no -e none myserver.com’ Tramp: Waiting for prompts from remote shell... Tramp failed to connect. If this happens repeatedly, try ‘M-x tramp-cleanup-this-connection’ Tramp: Waiting for prompts from remote shell...failed Tramp: Opening connection for weird_username@myserver.com using ssh...failed tramp-file-name-handler: Tramp failed to connect. If this happens repeatedly, try ‘M-x tramp-cleanup-this-connection’ ``` # Answer Ok, I found this file : ``` # cat ~/.emacs.d/tramp ;; -*- emacs-lisp -*- <21/02/05 12:48:54 /home/xxxxxx/.emacs.d/tramp> ;; Tramp connection history. Don't change this file. ;; You can delete it, forcing Tramp to reapply the checks. (((tramp-file-name "ssh" nil nil "sbc" nil nil nil) nil) ((tramp-file-name "ssh" "weird_username" nil "myserver.com" nil nil nil) nil)) ``` I did what it says on the tin and deleted it. Then I removed all mentions of `weird_username` and `myserver.com` in both `~/.emacs.d/history` and `~/.emacs.d/recentf`, and now `ivy-switch-buffer` works ; Phew. > 2 votes --- Tags: tramp, ssh, ivy, recentf, history ---
thread-40611
https://emacs.stackexchange.com/questions/40611
Where is ispell private dictionary located on Spacemacs?
2018-03-23T08:41:49.020
# Question Title: Where is ispell private dictionary located on Spacemacs? My Spacemacs help ispell-personal-dictionary says: ``` ispell-personal-dictionary is a variable defined in ‘ispell.el’. Its value is nil Documentation: File name of your personal spelling dictionary, or nil. If nil, the default personal dictionary, ("~/.ispell_DICTNAME" for ispell or "~/.aspell.LANG.pws" for Aspell) is used, where DICTNAME is the name of your default dictionary and LANG the two letter language code. ``` But there is no "~/.ispell\_DICTNAME" or "~/.aspell\_DICTNAME" on my system: ``` $ ls -A .isp* ls: cannot access '.isp*': No such file or directory $ ls -A .asp* ls: cannot access '.asp*': No such file or directory ``` ispell is working and I accidentaly added a misspelled word to it. Now I want to remove the entry from my ispell private dictionary. How to find the ispell private dictionary location? System Info :computer: * OS: gnu/linux * Emacs: 25.3.1 * Spacemacs: 0.200.10 * Spacemacs branch: master (rev. 4bb4cb46) * Graphic display: t * Distribution: spacemacs * Editing style: vim * Completion: ivy * Layers: `elisp (c-c++ emacs-lisp evil-snipe git ivy org shell spell-checking)` * System configuration features: XPM JPEG TIFF GIF PNG RSVG IMAGEMAGICK SOUND DBUS GCONF GSETTINGS NOTIFY ACL LIBSELINUX GNUTLS LIBXML2 FREETYPE M17N\_FLT LIBOTF XFT ZLIB TOOLKIT\_SCROLL\_BARS GTK3 X11 MODULES XWIDGETS **UPDATE 1:** aspell doesn't seem to be on my system: ``` $ aspell -h bash: aspell: command not found. ``` **UPDATE 2:** I found aspell, but it's unresponsive: ``` $ pwd /usr/share/bash-completion/completions $ ls aspell aspell $ aspell --lang=en dump config bash: aspell: command not found... Install package 'aspell' to provide command 'aspell'? [N/y] n $ aspell -h bash: aspell: command not found. $ sudo ./aspell -h sudo: ./aspell: command not found ``` **UPDATE 3:** To uninstall aspell, I commented spell-checking in ~/.spacemacs, and restarted Emacs. Then I reinstalled as described in https://github.com/syl20bnr/spacemacs/tree/master/layers/+checkers/spell-checking#install and restarted Emacs again. Emacs opening page said: ``` Found 3 new package(s) to install... --> refreshing package archive: melpa-stable... [2/2] --> installing package: flyspell-correct-ivy@spell-checking... [3/3] ``` Still have same result with absolute path: ``` $ sudo /usr/share/bash-completion/completions/aspell -h sudo: /usr/share/bash-completion/completions/aspell: command not found ``` **UPDATE 4:** From Spacemacs help - SPC SPC h d v ispell-program-name: ``` ispell-program-name is a variable defined in ‘ispell.el’. Its value is "/usr/bin/hunspell" ``` From command line: ``` $ hunspell -v @(#) International Ispell Version 3.2.06 (but really Hunspell 1.5.4) $ hunspell -h ``` I googled: emacs private dictionary location Still not finding the location of my private dictionary. # Answer > 1 votes First, look at the variable `ispell-personal-dictionary`. If itʼs set, thatʼs your answer. Next, look at the variable `ispell-program-name`. This is the spell-checking backend that Emacs is currently using, and each backend will store your private dictionary in a different place: * Aspell: `~/.aspell.??.pws` * Enchant: `~/.config/enchant/*.dic` * Hunspell: `~/.hunspell_*` In each case, the exact file used will vary based on the language youʼre using. # Answer > 0 votes I never found the Emacs private dictionary on Debian 9. But when I installed Fedora 28, it was easily found at ~/.hunspell\_en\_US # Answer > 0 votes On my Ubuntu system, it's located at `~/.aspell.en.pws` --- Tags: spacemacs, ispell, spell-checking ---
thread-63184
https://emacs.stackexchange.com/questions/63184
fontify autoref and nameref in latex-mode buffers
2021-02-04T23:00:16.937
# Question Title: fontify autoref and nameref in latex-mode buffers When I'm in a `.tex` file, press `M-:` and run ``` (font-latex-add-keywords '(("autoref" "*{") ("Autoref" "{") ("nameref" "*{")) 'reference) ``` the buffer fontifies occurrences of `\nameref` and `\autoref` appropriately (and my custom-defined `\Autoref`. However, if I put this same code in my `.emacs` file (say under the `:config` section of `(use-package auctex ...` or in the `latex-mode-hook`), then those macros are no longer fontified as references in `.tex` buffers. How do I fix this? This is a related question, but I am looking for a simpler solution that, ideally, simply incorporates the one-liner above. # Answer Call your setting from the `LaTeX-mode-hook`. It's not very user friendly but `latex-mode-hook` is defined in `tex-mode.el`, which is built-in but not part of AUCTeX, while `LaTeX-mode-hook` comes from `latex.el` which is part of AUCTeX. So this should work, ``` (defun my-LaTeX-mode-setup () (font-latex-add-keywords '(("autoref" "*{") ("Autoref" "{") ("nameref" "*{")) 'reference)) (add-hook 'LaTeX-mode-hook #'my-LaTeX-mode-setup) ``` > 1 votes --- Tags: latex, auctex, font-lock ---