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-69351
https://emacs.stackexchange.com/questions/69351
Unable to remap mouse under dired in macos emacs
2021-11-14T20:37:10.837
# Question Title: Unable to remap mouse under dired in macos emacs I'm not sure whether this should be considered an appropriate post for `emacs.stackexchange`, or whether this should go to some sort of macos forum. Please let me know if I need to ask the following question elsewhere ... I'm running the following version of Emacs under macos (Big Sur, version 11.6.1) ... ``` GNU Emacs 27.2 (build 1, x86_64-apple-darwin18.7.0, NS appkit-1671.60 Version 10.14.6 (Build 18G95)) of 2021-03-27 Copyright (C) 2021 Free Software Foundation, Inc. ``` I am using `dired`, and I am trying to remap `[mouse-1]` to run my own function. However, I have not been able to get `dired` to recognize this `[mouse-1]` remapping. Here is what I have tried ... ``` (defun my-special-function () (interactive) (message "running my special function") (sit-for 1) ) (require 'dired) (define-key dired-mode-map [mouse-1] 'my-special-function) (dired "/path/to/directory") ``` When I run this when positioned on a `dired` line, clicking there with `mouse-1` still runs the default `dired-find-file` function, instead of my own function. I'm guessing that this might somehow be related to the text properties that `dired` applies within the `dired` buffer. What can I do to under this version of emacs to get `[mouse-1]` to also get remapped to run my special function? # Answer > 0 votes I ended up fixing this in a completely different way. I overrode `dired-find-file` and `dired-mouse-find-file`, as follows ... ``` (defun my-special-function () (interactive) (message "my special function") (sit-for 1) ) (defvar my-dired-advised nil "*my dired stuff is already advised") (defun my-dired-mode-hook () (unless my-dired-advised (defadvice dired-find-file (around dired-find-file-around activate) (my-special-function) ) (defadvice dired-mouse-find-file (around dired-mouse-find-file-around activate) (my-special-function) ) (setq my-dired-advised t) ) ) (require 'dired) (add-hook 'dired-mode-hook 'my-dired-mode-hook) (dired "/path/to/directory") ``` It seems like `dired` maps the mouse stuff under the covers, irrespective of any `define-key` commands involving the mouse. Simply overriding those two `dired` functions appears to be what I need to do. Is there perhaps any other way to solve this? # Answer > 0 votes You replaced the binding for `<mouse-1>` with a binding to your command. That should be fine, but it's not a "remapping" (which is about commands or faces, not keys). Remapping a command is about doing something like this: ``` (define-key dired-mode-map [remap dired-mouse-find-file-other-window] 'my-special-function) ``` That remaps the keys bound to command `dired-mouse-find-file-other-window` (I'm supposing that's the command you want to remap), so that those keys instead invoke your command, `my-special-function`. See (elisp) Remapping Commands. --- Tags: key-bindings, dired, osx, mouse ---
thread-69246
https://emacs.stackexchange.com/questions/69246
Julia mode in MacOS
2021-11-05T20:48:32.480
# Question Title: Julia mode in MacOS I updated my macOS from Big Sur to Monterey and found that my julia command does not work. Specifically, I use the following `init.el`. So far, I could send line using `C-return` but, now I got a message `<C-return> is undefined`. Also, hit `C-c C-c`, `C-c C-c is undefined`. How do I manage this? ``` (use-package julia-mode :config (setq inferior-julia-program-name "/Applications/Julia-1.6.app/Contents/Resources/julia/bin/julia") (add-hook 'ess-julia-mode-hook (lambda() (define-key ess-julia-mode-map (kbd "TAB") 'julia-latexsub-or-indent)))) ``` # Answer > 1 votes In July 2021, the `julia-mode` folks removed their code to communicate with the Julia REPL (known as an inferior process in Emacs terminology), and recommend using a third party package. This is all discussed in this GitHub issue. Based on your hook, I'd assume you're trying to use ESS with Julia. If that's the case this is all I need to get my Julia code buffer working with the Julia REPL. ``` ;; ESS+Julia (use-package julia-mode :ensure t) (use-package ess :ensure t :init (require 'ess-site) :config (when (string= system-type "darwin") (setq inferior-julia-program "/Applications/Julia-1.6.app/Contents/Resources/julia/bin/julia")) (setq inferior-julia-args "--color=yes") (require 'ess-julia)) ``` Note that `inferior-julia-program-name` is deprecated in favor of `inferior-julia-program`. Be sure to configure `ess` after `julia-mode`, or add an `:after` clause to the `ess` form. If you're not using ESS with Julia, try one of the other packages listed in the GitHub issue. --- Tags: debugging, osx ---
thread-69332
https://emacs.stackexchange.com/questions/69332
`C-h` without knowing the type of an object
2021-11-13T14:35:00.110
# Question Title: `C-h` without knowing the type of an object When someone use the Emacs inbuild help via `C-h` she/he has to know and understand if the object of interest is a function (`C-h f`), a variable (`C-h v`), a package (`C-h p`) or something else. The differences between these types are unknown for new users. Isn't there a magic package out there that can check this by itself and do the right thing? E.g. `C-h x` or `C-h h`. # Answer > 6 votes As @Drew mentions, the `apropos` commands are extremely important. The word derives from the French "à-propos" which can be translated as "in connection", "with regard" or "concerning". In other words, *apropos foo* means *concerning foo*. In practice, I frequently use `describe-symbol`, bound to `C-h o` by default, since it describes variables, functions and faces. Emacs' help system is advanced and it may take some time to wrap one's head around it. When in doubt, run `C-h C-h` for a description of all help commands. # Answer > 5 votes 1. The apropos commands are your friend. Command `apropos` is the most general: > **`apropos`** is an autoloaded interactive Lisp function in `apropos.el`. > > It is bound to `<menu-bar> <help-menu> <search-documentation> <find-any-object-by-name>`. > > `(apropos PATTERN &optional DO-ALL)` > > Probably introduced at or before Emacs version 1.8. > > Show all meaningful Lisp symbols whose names match `PATTERN`. > > Symbols are shown if they are defined as functions, variables, or faces, or if they have nonempty property lists. > > `PATTERN` can be a word, a list of words (separated by spaces), or a regexp (using some regexp special characters). If it is a word, search for matches for that word as a substring. If it is a list of words, search for matches for any two (or more) of those words. > > With `C-u` prefix, or if **`apropos-do-all`** is non-`nil`, consider all symbols (if they match `PATTERN`). > > Returns list of symbols and documentation found. 2. **`C-h S`** looks up a symbol in the manuals: > **`C-h S`** runs the command **`info-lookup-symbol`** (found in `global-map`), which is an autoloaded interactive Lisp function in `info-look.el`. > > It is bound to `C-h S`, `<f1> S`, `<help> S`. > > `(info-lookup-symbol SYMBOL &optional MODE)` > > Probably introduced at or before Emacs version 20.1. > > Display the definition of `SYMBOL`, as found in the relevant manual. > > When this command is called interactively, it reads `SYMBOL` from the minibuffer. In the minibuffer, use `M-n` to yank the default argument value into the minibuffer so you can edit it. The default symbol is the one found at point. > > With prefix arg `MODE` a query for the symbol help mode is offered. # Answer > 2 votes Package helpful provides `helpful-callable`, for which you don't need to know whether the thing you're inquiring about is a command, function, or macro because it checks them all, and also `helpful-symbol`, which like `describe-symbol` mentioned previously will > Show help for `SYMBOL`, a variable, function or macro. …by evaluating `SYMBOL` and calling `helpful-callable` or `helpful-variable` as appropriate (and asking which you want if it could be either—though unlike with `describe-symbol` you have to pick one, you don't get both). --- Tags: help ---
thread-69282
https://emacs.stackexchange.com/questions/69282
evil-mode unmap TAB key from evil-jump-forward
2021-11-08T23:59:23.617
# Question Title: evil-mode unmap TAB key from evil-jump-forward I use `evil-mode` and `evil-collection`. The `TAB` key is bound/maped (?) to `evil-jump-forward`. I do not know which of the evil-packages or parts did this. I do not use this function. I need the `TAB` key for `org-mode`. How do I unmap/unbound a key when using `use-package`? ``` ;; === EVIL (use-package evil :init (setq evil-want-integration t) (setq evil-want-keybinding nil) :config (evil-mode 1) ;; Use visual line motions even outside of visual-line-mode buffers (evil-global-set-key 'motion "j" 'evil-next-visual-line) (evil-global-set-key 'motion "k" 'evil-previous-visual-line) ;; Set "normal" vi-mode in specific buffers (evil-set-initial-state 'messages-buffer-mode 'normal) (evil-set-initial-state 'dashboard-mode 'normal) ) (use-package evil-collection :after evil :config (evil-collection-init) ) ``` This question is not specific about `evil` or `org`. It could be any other key or package. This case is just an example where it could be usefull to unmap/unbound a keybinding. And **the question** is how to do that in the context of `use-package`. # Answer > 1 votes I do not understand the details here but when setting this variable for `evil-mode` the `TAB` works in `org-mode`. ``` (setq evil-want-C-i-jump nil) ``` --- Tags: key-bindings, evil ---
thread-59786
https://emacs.stackexchange.com/questions/59786
elfeed + olivetti modes
2020-07-23T05:34:07.020
# Question Title: elfeed + olivetti modes I want the `elfeed-show-mode` to be displayed with the olivetti minor mode `olivetti-mode`, so I do: ``` (add-hook 'elfeed-show-mode-hook 'olivetti-mode) ``` The problem is that the lines are not truncated correctly (see image). I have to invoke `elfeed-show-refresh` every time to obtain the desired effect. Thank you very much in advance for any hint. # Answer I didn't get this to work via the `elfeed-show-mode-hook`. I don't really fully understand what is going on, but I think it is something to do with the margins set by olivetti mode not activating until after the buffer is displayed, but elfeed renders the buffer before that and so the HTML renderer doesn't get the updated text width. However, I was able to solve it another way by setting the `elfeed-show-entry-switch` function. Elfeed calls this function after it sets up the `*elfeed-entry*` buffer. If this is given a function that switches to the buffer, turns on olivetti-mode and then does a refresh, it all seems to work: ``` (defun elfeed-olivetti (buff) (switch-to-buffer buff) (olivetti-mode) (elfeed-show-refresh)) (setq elfeed-show-entry-switch 'elfeed-olivetti) ``` I guess this is a bit inefficient because it does the refresh twice, but I haven't noticed any slowdown when using it. > 1 votes --- Tags: hooks, elfeed ---
thread-69362
https://emacs.stackexchange.com/questions/69362
Defining color for "$"variable in bash
2021-11-15T18:21:12.497
# Question Title: Defining color for "$"variable in bash Unfortunately the dollar-sign in variable-names in the syntax-highlight is in the theme I use defined as 'default' face instead of being part of the variable name. Is there a way to customize this? # Answer Emacs calls syntax highlighting “font lock”. Specifically, font lock is the part of syntax highlighting that parses the text to determine what parts are comments, keywords, variable names, etc., and assigns them font characteristics such as bold, italics, colors, etc. A theme can determine how colors are rendered. Since you want to change how `$` is recognized, not what color is used for variable names, the theme is not relevant: you need to configure font locking. Font locking for a major mode is specified through a list of font lock keywords. Each entry in the list is itself a list, consisting of a regular expression and specifications of the face to use for each group. (I'm just describing the most common case here, see the manual for details.) There's a generic way to add your own keywords: call `font-lock-add-keywords`. So the simplest way to do what you asked is to call this function and tell it to use the variable name face for a regular expression that includes the `$` as well as the variable name. ``` (font-lock-add-keywords 'sh-mode '( ("\\$\\([A-Z_a-z][A-Z_a-z0-9]+\\|[-!$#*0-9?@]\\)" (0 font-lock-variable-name-face)) )) ``` In `${variable}`, the braces are left in the default color. It's trivially easy to highlight the opening brace as well, but it takes more work to also highlight the matching closing brace. Here's code that matches the closing brace as well. It uses the “function” form of font lock keyword locator in an “anchored” matcher. ``` (defun match-closing-brace (limit) "Match the closing brace following the previous opening brace. Move the point just after the closing brace and return non-nil. If no matching closing brace is found, return nil." (and (search-backward-regexp "{[^{}]*\\=" nil t) (condition-case nil (progn (forward-sexp) t) (error nil)) (save-excursion (backward-char) (looking-at "}")))) (font-lock-add-keywords 'sh-mode '( ("\\$\\([A-Z_a-z][A-Z_a-z0-9]+\\|[-!$#*0-9?@]\\)" (0 font-lock-variable-name-face)) ("\\${\\([A-Z_a-z][A-Z_a-z0-9]+\\|[-!$#*0-9?@]?\\)" (0 font-lock-variable-name-face) (match-closing-brace nil nil (0 font-lock-variable-name-face))) )) ``` --- Using the generic mechanism `font-lock-add-keywords` affects all buffers in sh mode, regardless of the sh variant. In this particular case, I don't think this is a problem. If you wanted to customize only a specific variant, you'd have to dig deeper. The font lock specification for a mode `foo-mode` is typically in a variable called `foo-mode-font-lock-keywords` or variations around this theme. This can be more complex for modes that support multiple language variants or multiple levels of syntactic sophistication. Shell mode has both. To find its font lock specification, run `C-h v sh-*font-lock-keywords*` and see what completions are offered. This leads you to `sh-font-lock-keywords-var`. > 4 votes --- Tags: syntax-highlighting ---
thread-69366
https://emacs.stackexchange.com/questions/69366
Highlight words appearing once within a block
2021-11-15T22:13:23.747
# Question Title: Highlight words appearing once within a block I want to highlight every identifier (a sequence of characters matching a certain regexp or, even better, having the default face) appearing once within a block of code (a piece of arbitrary text between two empty lines) for each block in the current buffer. Is there an existing solution to this problem? I don't know any elisp, but I could write a program taking the contents of the buffer and annotating every unique identifier with something that emacs knows how to pick up and turn into highlighting (the annotations should not appear in the text once rendered by emacs). Is there some kind of format for explicit highlighting annotations that emacs understands? Would that be a sensible way of approaching the problem? # Answer > 3 votes I guess you want a two-pass system then, whereby you firstly collect/count identifiers, and secondly discard those which appeared more than once, and then highlight what's left. Here's one approach... ``` (defun my-highlight-unique-symbols () "In each block, highlight all symbols which occur exactly once." (interactive) (font-lock-ensure) (save-excursion (goto-char (point-min)) (let ((regexp "\\_<.+?\\_>") (case-fold-search nil) (blockstart (point)) (blockdelimiter "\n\n\n")) ;; Establish the next block. (while (and (not (eobp)) (or (search-forward blockdelimiter nil t) (goto-char (point-max)))) (let ((blockend (point)) (identifiers (obarray-make))) (goto-char blockstart) (while (re-search-forward regexp blockend t) ;; Have we seen this identifier before? (let* ((sym (intern (match-string 0) identifiers)) (seen (get sym 'region))) (if seen ;; Mark it as a duplicate. (unless (eq seen 'duplicate) (put sym 'region 'duplicate)) ;; This is the first time we've seen this identifier. ;; Store the region boundaries for the match. (put sym 'region (cons (match-beginning 0) (match-end 0)))))) ;; Highlight the unique instances. (with-silent-modifications (obarray-map (lambda (sym) (let ((region (get sym 'region))) (unless (eq region 'duplicate) (put-text-property (car region) (cdr region) 'face 'highlight)))) identifiers)) ;; Prepare for the next block. (setq blockstart blockend) (goto-char blockstart)))))) ``` Which you can run with `M-x` `my-highlight-unique-symbols` This version is not a permanent effect -- you can run it to highlight things, but subsequent edits to the buffer will likely cause font-lock to update the faces for that text, and clobber this highlighting. If you *don't* edit the buffer, then I'm fairly sure that font-lock won't subsequently/stealthily fontify/clobber any of the highlight faces, as I've called `font-lock-ensure` up front; so calling this command should be good enough for read-only purposes. --- Tags: highlighting ---
thread-69359
https://emacs.stackexchange.com/questions/69359
How to export the scheduled date to taskjuggler
2021-11-15T13:03:44.617
# Question Title: How to export the scheduled date to taskjuggler Having `(require 'ox-taskjuggler)` in my init.el and hitting `org-taskjuggler-export-process-and-open` in *foo.org* renders the current date instead the expected scheduled date. Content of *foo.org* ``` *** Foo :taskjuggler_project: :PROPERTIES: :ORDERED: t :scheduled: <2025-12-09 Tue> :END: **** Bar :PROPERTIES: :Effort: 2w :END: **** Acme :PROPERTIES: :Effort: 2w :END: ``` results in https://orgmode.org/worg/exporters/taskjuggler/ox-taskjuggler.html # Answer As mentioned in a comment, `SCHEDULED` is a special property that should *not* go into a properties drawer: just like `DEADLINE`, it has to come right after the headline and before the properties drawer. That's where Org mode is looking for `SCHEDULED` or `DEADLINE` information. So the Org mode file should look like this: ``` *** Foo :taskjuggler_project: SCHEDULED: <2025-12-09 Tue> :PROPERTIES: :ORDERED: t :END: **** Bar :PROPERTIES: :Effort: 2w :END: **** Acme :PROPERTIES: :Effort: 2w :END: ``` `M-x org-lint` should flag problems like this and produce a useful report. > 0 votes --- Tags: org-mode, org-agenda ---
thread-69361
https://emacs.stackexchange.com/questions/69361
How can I apply `noqa` in order to ignore warning messages when lsp-mode is enabled
2021-11-15T16:19:27.913
# Question Title: How can I apply `noqa` in order to ignore warning messages when lsp-mode is enabled I am trying to ignore flycheck warning messages, when `lsp-mode` for the `python-mode` is on. I have tried `["# noqa", "# NOQA", "# flake8: noqa", "# type: ignore"]` but neither of them seems working. --- I am totaly lost how I can fix this . Installation from https://github.com/python-lsp/python-lsp-server `pip install 'python-lsp-server[all]'` my basic configuration is as follows: ``` (require 'package) (setq user-init-file (or load-file-name (buffer-file-name))) (setq user-emacs-directory (file-name-directory user-init-file)) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) (package-initialize) (setq frame-background-mode 'dark) (defun flycheck-python-setup () (flycheck-mode)) (require 'flycheck) (require 'flycheck-mypy) (add-hook 'after-init-hook #'global-flycheck-mode) (add-hook 'after-init-hook #'global-flycheck-mode) (add-to-list 'flycheck-disabled-checkers 'python-flake8) (add-hook 'python-mode-hook (lambda () (setq flycheck-python-pylint-executable "~/venv/bin/pylint") (setq flycheck-pylintrc "~/.pylintrc") (setq indent-tabs-mode nil python-indent-offset 4 tab-width 4) (let ((inhibit-message t)) ))) (use-package python :ensure nil) (add-hook 'python-mode-hook #'flycheck-python-setup) (flycheck-add-next-checker 'python-flake8 'python-pylint 'python-mypy) (require 'lsp-pylsp) (setq lsp-pylsp-plugins-pylint-args ["--rcfile=~/.pylintrc"]) (setq lsp-pylsp-plugins-pylint-enabled t) (add-hook 'python-mode-hook 'lsp) (add-hook 'python-mode-hook #'lsp-deferred) (setq lsp-headerline-breadcrumb-enable nil) (setq lsp-enable-symbol-highlighting nil) (setq lsp-modeline-diagnostics-enable 1) (setq lsp-ui-doc-enable nil) (setq lsp-lens-enable nil) (setq lsp-pyls-plugins-pylint-enabled nil) (setq lsp-ui-sideline-enable nil) (setq lsp-ui-sideline-show-diagnostics nil) (setq lsp-log-io nil) ; if set to true can cause a performance hit (setq lsp-enable-snippet nil) ;; solves to prevent () to be added during completions (setq lsp-file-watch-threshold 2000) (setq lsp-idle-delay 0.500) (setq read-process-output-max (* 1024 1024)) ;; 1mb (setq gc-cons-threshold 402653184 gc-cons-percentage 0.6) ``` Please note that `# noqa` works if `lsp` is disabled. # Answer > 2 votes # tl;dr When trying to figure anything out, simplify! ``` $ pip3 install 'pyparsing<3' $ pip3 install python-lsp-server # use a minimal `~/.emacs.d/init.el`, such as the one listed below ``` Here's my recipe to get `lsp-mode`+`python-lsp-server` working with `flycheck`. ## `python-lsp-server` First we need an lsp server for Python. Following the instructions at https://github.com/python-lsp/python-lsp-server#installation I attempted to install `python-lsp-server` ``` $ pip3 install python-lsp-server ``` Installation failed, because `pip3` wanted to install `pyparsing v3.0.5` while `python-lsp-server` wanted `'pyparsing<3,>=2.0.2'`. This was easily remedied. ``` $ pip3 install 'pyparsing<3' $ pip3 install python-lsp-server ``` ## `lsp-mode` \+ `flycheck` Next I created a *fresh* `~/.emacs.d/init.el`, and following the instructions at https://emacs-lsp.github.io/lsp-mode/page/installation/#use-package I added the recommended `use-package` form. Also, by adding setup for `flycheck` this gives me a *minimal init file* of: ``` ;; -*- mode: emacs-lisp; ; indent-tabs-mode: nil -*- ;; Bootstrap package.el (require 'package) (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3") (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") '("gnu" . "https://elpa.gnu.org/packages/")) (package-initialize) ;; Bootstrap 'use-package' (eval-after-load 'gnutls '(add-to-list 'gnutls-trustfiles "/etc/ssl/cert.pem")) (unless (package-installed-p 'use-package) (package-refresh-contents) (package-install 'use-package)) (eval-when-compile (require 'use-package)) (require 'bind-key) (setq use-package-always-ensure t) ;; setup flycheck (use-package flycheck :config (global-flycheck-mode)) ;; setup lsp-mode, https://emacs-lsp.github.io/lsp-mode/page/installation/#use-package (use-package lsp-mode :init ;; set prefix for lsp-command-keymap (few alternatives - "C-l", "C-c l") (setq lsp-keymap-prefix "C-c l") :hook (;; replace XXX-mode with concrete major-mode(e. g. python-mode) (python-mode . lsp) ;; if you want which-key integration (lsp-mode . lsp-enable-which-key-integration)) :commands lsp) ``` ## Sample python file Now we need a sample python file with known style errors. ``` $ cat > ~/foo/foo.py #!/usr/bin/env python3 import os,sys example = lambda: 'example' ^D $ ``` ## Editing our python file Now we get to work... ``` $ emacs ~/foo/foo.py ``` `lsp-mode` asks us what we want to do.. Naturally, we want to import our new file, so we hit `i`, and `lsp-mode` lets us know it has successfully imported our file. Now, you'll notice that our file has `flycheck`'s familiar arrows and squiggles. If we add `# noqa` to line #5, you'll see its squiggle, and error listing, are gone. You may also have noticed that the "Checker" in `*Flycheck errors*` is "lsp". *This is what we want*. If you want `flake8` to be the primary checker, you can select it for the current session via `C-c``!``v`, selecting "python-flake8", and hitting `q` to close the selection window. When back at your `foo.py` window, run `M-x` `flycheck-error-list-reset-filter`. You'll notice that line #5 continues to be "error free". ## Now what? Continue to build up your configuration until something strange or unexpected happens. Stop. Undo that last change. Read the documentation of what you added and figure out what you did wrong. *Do not* blindly add more and more to your configuration, and dig yourself a deeper hole. --- Tags: flycheck, warning, lsp ---
thread-69220
https://emacs.stackexchange.com/questions/69220
ESS: Turn off [TRUNCATED] in ESS R session
2021-11-04T19:45:52.833
# Question Title: ESS: Turn off [TRUNCATED] in ESS R session I'm running some code in a .Rmd file using M-n v u, but when I do so, my output is truncated. I'd like to turn this feature off, but the only documentation I can find mentioning truncation is for `ess-eldoc-abbreviation-style` and it's related to the mini-buffer. Here's an example of what happens. Code ``` while(my.round <= max.round){ input.restart.file <- paste0(output.dir,"Restart/rstart.round.", my.round - 1, ".rst") output.restart.file <- paste0(output.dir,"Restart/rstart.round.", my.round, ".rst") if(my.round==1){ #initial set up ## Initialize parameter object ## Set initial phi value parameter <- initializeParameterObject( genome = genome, model = which.model, sphi = init_sphi, mutation.prior.mean = mutation.prior.mean, mutation.prior.sd = mutation.prior.sd, ## should try changing this num.mixtures = 1, gene.assignment = rep(1, genome.length), split.serine = TRUE, mixture.definition = mixDef) divergence.iteration <- initial.divergence . . . ``` R Window in Emacs ``` + while(my.round <= max.round){ + + input.restart.file <- paste0(output.dir,"Restart/rstart.round.", my.round - 1, ".rst") + output.restart.file <- paste0(output.dir,"Restart/rstart.round.", my.round, ".rst") + + + if(my.round==1){ #initial set up + ## Initialize parameter object.... [TRUNCATED] ``` UPDATE: I've now downloaded a copy of the emacs source code and searched for "\[TRUNCATED\]" and get nothing. I've also searched my .emacs folders and get the same results. For what it's worth, I'm running 1. Ubuntu-Mate 20.04 2. GNU Emacs 26.3 * (build 2, x86\_64-pc-linux-gnu, GTK+ Version 3.24.14) of 2020-03-26, modified by Debian 3. ESS version 18.10.2 # Answer > 1 votes So it looks like I need to figure out how to modify the options ESS sends to R using `.ess.source()` and `.ess.eval()`. Specifically, I need to change the argument ``` max.deparse.length: integer; is used only if ‘echo’ is ‘TRUE’ and gives the maximal number of characters output for the deparse of a single expression. ``` I can do this including the following in the source file I'm working with. ``` library(default) default(.ess.source) <- list(max.deparse.length=1E5) default(.ess.eval) <- list(max.deparse.length=1E5) ``` (NB: it doesn't work in my `.Rprofile` because R doesn't know about these libraries until they are some how loaded by emacs-ESS.) --- Tags: ess, r ---
thread-69379
https://emacs.stackexchange.com/questions/69379
isdigit in elisp
2021-11-17T11:02:27.253
# Question Title: isdigit in elisp I wanted to check that char is a digit by comparing its code with codes of 0 and 9, presuming that the digits codes are contiguous in code table: ``` (let ((char ?\e)) (if (and (>= char ?\0) (<= char ?\9)) (message "aaa") (message "bbb"))) ``` But it doesn't work: this code returns "aaa", even though `e` is not a digit. What is wrong? # Answer Remove the backslashes before `e`, `0` and `9`. ``` (let ((char ?e)) (if (<= ?0 char ?9) (message "It's a digit") (message "It's not a digit"))) ``` With the backslashes: * `\e` is the escape char - ASCII 27. * `\0` is the null char - ASCII 0. * `\9` isn't special, so it's the same as `9` \- ASCII 57. * 27 is \>= 0 and \<= 57. > 8 votes --- Tags: characters ---
thread-69134
https://emacs.stackexchange.com/questions/69134
What is emacs : daemon, emacsclient, tcp-server?
2021-10-29T14:05:20.380
# Question Title: What is emacs : daemon, emacsclient, tcp-server? I want to know about why they are used? , what are they? what is daemon in emacs, Why Should/shouldnot i use "emacs" instead of "emacsclient --create-frame" ? what is client and server in emacs? please if you know explain me briefly from like childhood to adulthood? # Answer First, I think these things are quite well explained in Chapter 39 of the Emacs manual. So, I would recommend you to read that chapter (again) after reading the 'childhood' info below... Although Emacs is commonly described as an editor, a better description would be to call it 'an Emacs lisp interpreter including', or 'a virtual lisp machine containing', an editor. Now to answer this question it is probably most insightful to view Emacs as a virtual lisp machine, and then provide an analogy with a real PC/workstation. Using the command `emacs` will boot an entire lisp machine, which in this analogy is like starting up a PC/workstation and login in as a user into your desktop environment. If you are using the browser on a PC and you download some text file, you would probably not startup another PC just to read your text file there, because it is much simpler to read the file right in the current desktop session by opening the file in some editor, or for the analogy, by connecting to the desktop session and create a file in the new frame (provided by the editor). Generally, when the editor is already open, you do not even require a new instance of the editor (i.e. no new frame), but you can just open another file by 'connecting to the editor' and open it there. This is what `emacsclient` is for (more below). By starting a daemon (which more or less means starting the Emacs server, without doing anything else, i.e. without starting a graphical user interface), it is like you are preparing your PC to be in 'sleep' mode, so your desktop user session is already loaded, although the computer seems to be turned off. But now you can directly get into your user session by a simple trigger (like pressing a key, or by 'unfolding' your laptop). Commonly, a server is something you connect to, like when you connect to some website, the website was already 'running' on the remote server (it does not have to boot up first). `emacsclient` is the utility that helps you connect to the Emacs server (it provides a graphical user interface). It is somewhat analogous to providing you a monitor, keyboard and mouse to help you connect to your PC (for waking up the sleeping pc and let you interact with it). Finally, the TCP server is just a particular kind of server that lets you 'connect' to Emacs (your 'virtual machine') in a particular way (e.g. from a remote station). Usually you do not need the TCP server because you can simply connect to your Emacs server via some mechanism provided by your OS (like for waking your PC locally, you can just press a key on the keyboard). However, if you want to connect to the Emacs server from far (like booting your PC from another room), then you need some way to connect to it from far for which you can use the TCP(rotocol), like you would probably do for waking your remotely sleeping computer in the other room/house/universe. I would advise starting the Emacs server by adding `(server-start)` to your init file (because then you will also restart the server when restarting Emacs). Then open Emacs once after you have started your PC, and then try to never close it; connect to it using the `emacsclient` (without the `--create-frame` option). Once in a while, you need to restart Emacs, e.g. after updating some packages or after 'polluting the virtual machine(/interpreter) environment'. The above is certainly a very cumbersome and crude 'childhood' explanation, and could probably get much improved (edits are very welcome), but I hope it will help somewhat to understand what is written in Chapter 39 of the Emacs manual, which again, I would strongly recommend you to read (again). Then just start using the server, and you will gradually discover what will be the best workflow for you. > 2 votes # Answer To understand emacs daemon and client it is important to understand the effect of configuration required by both This only hinted to at last paragraph in 44 Saving Emacs Sessions of the emacs manual > When Emacs starts in daemon mode, it cannot ask you any questions, so if it finds the desktop file locked, it will not load it, unless desktop-load-locked-desktop is t. > > Note that restoring the desktop in daemon mode is somewhat problematic for other reasons: e.g., the daemon cannot use GUI features, so parameters such as frame position, size, and decorations cannot be restored. For that reason, you may wish to delay restoring the desktop in daemon mode until the first client connects, by calling desktop-read in a hook function that you add to server-after-make-frame-hook (see Creating Frames in The Emacs Lisp Reference Manual). Some links on the session problem. Emacs Daemon with Version 28.0.5.GTK+ on linux: > 1 votes --- Tags: emacsclient, terminal-emacs, emacs-daemon ---
thread-69344
https://emacs.stackexchange.com/questions/69344
Which-key: change next/previous page keybindings
2021-11-13T23:19:56.723
# Question Title: Which-key: change next/previous page keybindings This question has been edited thanks to dalanicolai. I want to change some of the default `which-key` key binds used to turn the pages. In `which-key.el` they are set like so: ``` (defvar which-key-C-h-map (let ((map (make-sparse-keymap))) (dolist (bind `(("\C-a" . which-key-abort) ;;abbreviated... ("n" . which-key-show-next-page-cycle) ("p" . which-key-show-previous-page-cycle) ;;abbreviated... (define-key map (car bind) (cdr bind))) map) "Keymap for C-h commands.") ``` when I do : ``` (define-key which-key-C-h-map (kbd "z") 'which-key-show-next-page-cycle) ``` I can turn the pages ok. but when I want to use PgUp/PgDown and do : ``` (define-key which-key-C-h-map (kbd "<next>") 'which-key-show-next-page-cycle) ``` I get: `which-key-C-h-dispatch: Wrong type argument: characterp, next` Why can't I use those two keys? # Answer > 1 votes EDIT To briefly answer your edited question also, this happens because `read-key` in `which-key-C-h-dispatch` returns a number for some characters (like 'z') and a symbol for others (like 'next'). A solution for your question is to replace the 'value' for the lexical variable `key` by ``` (let ((k (read-key prompt))) (if (numberp k) (string k) (vector k))) ``` You can open an issue for it at which-key, where it would probably be handy to point/refer to this answer/solution. END EDIT Here follows an answer, following your last comment. What you are trying works like expected. However, you should enter the keybinding correctly and use an existing command. Try ``` (define-key help-map (kbd "<next>") 'which-key-show-next-page-cycle) ``` However, this only binds `[next]` in the `help-map`, if you would like a similar thing in the `C-x` `which-key-mode-map`, you could do ``` (define-key which-key-mode-map (kbd "C-x <next>") 'which-key-show-next-page-cycle) ``` --- Tags: which-key ---
thread-69386
https://emacs.stackexchange.com/questions/69386
How to update beg end with comment-region
2021-11-17T18:33:45.137
# Question Title: How to update beg end with comment-region Scenario: I have *Emacs* open with split window. Top window contains an *R* script. Bottom windows has the interactive *R* session. I want to be able to copy a region from the interactive window to the script window, AND have the copied region be commented. My current approach (below) does this to the region: 1. `comment-region` 2. copy to other window/buffer 3. `uncomment-region` My problem is that `comment-region` does not update beg/end. This causes the copy to other window to not copy the entire commented region (since the commented region is now larger). How do I get comment-region to update beg/end ? ``` (defun duplicate-region-to-other-window-and-comment (beg end) "Duplicate the region to other window. Comment it." (interactive "r") (comment-region beg end) (pcase (window-list) (`(,w0 ,w1) (with-selected-window w1 (insert-buffer-substring (window-buffer w0) beg end))) (_ (user-error "Only works with 2 windows"))) ;; _ is really t (uncomment-region beg end ) ) ``` # Answer You could avoid this problem by commenting the text after you insert it: ``` (defun duplicate-region-to-other-window-and-comment (beg end) "Duplicate the region to other window. Comment it." (interactive "r") (let ((text (buffer-substring beg end))) ;; collect text to copy (pcase (window-list) (`(,w0 ,w1) (with-selected-window w1 (let ((start (point))) ;; store beginning of inserted text (insert text) (comment-region start (point))))) ;; comment inserted region (_ (user-error "Only works with 2 windows"))))) ``` > 1 votes --- Tags: ess, comment ---
thread-39087
https://emacs.stackexchange.com/questions/39087
Error with org-fstree: Symbol's function definition is void: reduce
2018-02-25T22:12:51.000
# Question Title: Error with org-fstree: Symbol's function definition is void: reduce I want to use the package `org-fstree` (MELPA Link). But in a file when I press `C-c C-c` at ``` #+BEGIN_FSTREE: ~/ ``` I get the following **error**: ``` Symbol's function definition is void: reduce ``` I am not sure if I installed the package correctly (this is the first time I am using `MELPA`). So here is all the information that I feel may be relevant: I added the `MELPA repository` by adding the following to my `~/.emacs`: ``` (when (>= emacs-major-version 24) (require 'package) (add-to-list 'package-archives ;; '("melpa" . "http://stable.melpa.org/packages/") ; many packages won't show if using stable '("melpa" . "http://melpa.milkbox.net/packages/") t)) ``` Then I restarted `Emacs`. I pressed `M-x list-packages` and pressed `i` at `org-fstree` to mark it for installation and pressed `x` to complete the installation. I got the following warnings: ``` In org-fstree-extract-path-from-headline: org-fstree.el:271:21:Warning: reference to free variable `org-fstree-heading-regexp' In end of data: org-fstree.el:311:1:Warning: the following functions are not known to be defined: reduce, org-columns-quit ``` Then I added the following lines to my `~/.emacs`: ``` ;; org-fstree (add-to-list 'load-path "~/.emacs.d/elpa/org-fstree-20090723.819/") (require 'org-fstree) ``` I got the above mentioned **error** after these steps. Please advice me on what to do? # Answer > 1 votes The package `org-fstree` is very old. The correction code below fixes several problems in the elisp file `org-fstree.el` of the package. It also prepares the package for autoload. That means that the hooks and functions that work as entry points of the package are marked as auto-loaded. The package is only loaded on demand when one of those is really called. All fixed problems are listed as comments in the correction code. After installation of `org-fstree-20090723.819` you can copy-paste the correction code into your `*scratch*` buffer place point somewhere in the code and call `eval-defun` which is bound to `C-M-x`. ``` (with-current-file "~/.emacs.d/elpa/org-fstree-20090723.819/org-fstree.el" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 1: Add ;;;###autoload at hooks and corresponding functions (goto-char (point-min)) (let ((m (make-marker))) (while (progn (set-marker m (search-forward "(add-hook" nil t)) (marker-position m)) (forward-line 0) (unless (looking-back ";;;###autoload\n") (insert ";;;###autoload\n")) (let* ((form (read (current-buffer))) (fun (nth 1 ;; function in (quote function) (nth 2 form)))) ;; (quote function) in (add-hook (quote hook) (quote function)) (find-function fun) (unless (looking-back ";;;###autoload\n") (insert ";;;###autoload\n")) (goto-char m)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 2: replace `reduce' with `cl-reduce' to autoload the required cl package (goto-char (point-min)) (while (re-search-forward "\\_<reduce\\_>" nil t) (replace-match "cl-reduce")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 3: add `org-colview' required for the used function `org-columns-quit': (goto-char (point-min)) (re-search-forward "^;; *Code:") (unless (looking-at "\n(require 'org-colview)") (insert "\n(require 'org-colview) ; needed for `org-columns-quit'")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 4: Correct order of "defun org-fstree-extract-path-from-headline" and ;; "defconst org-fstree-heading-regexp". (goto-char (point-min)) (let ((pos-defun (re-search-forward "(defun *org-fstree-extract-path-from-headline" nil t)) (pos-defvar (re-search-forward "(defconst *org-fstree-heading-regexp" nil t)) (pos-make-local (re-search-forward "make-variable-buffer-local *'org-fstree-heading-regexp" nil t))) (when (and pos-defun pos-defvar pos-make-local) (transpose-regions (progn (goto-char pos-defun) (forward-line 0) (point)) (progn (forward-sexp) (point)) (progn (goto-char pos-defvar) (forward-line 0) (point)) (progn (goto-char pos-make-local) (up-list) (point))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 5: Installation tasks (write-region nil nil (buffer-file-name)) (package-generate-autoloads "org-fstree" default-directory) (cl-assert (byte-compile-file (buffer-file-name)))) ``` Note that there are some more minor problems reported by `byte-compile-file` for the corrected version of `org-fstree`. Nevertheless, the corrected version of `org-fstree` is running in `emacs-version` 25.3.2 with `org-version` 9.1.6 and does more or less what it is supposed to do (as far as I see). # Answer > 0 votes If anyone gets here because they read Emacs' Wiki: Eshell Prompt and wanted to try their "Summarising the path" prompt but got the same error as this question, you can fix it by replacing `reduce` with `cl-reduce` per @Tobias' comment. But why fix when you can copy? ``` (defun shortened-path (path max-len) "Return a modified version of `path', replacing some components with single characters starting from the left to try and get the path down to `max-len'" (let* ((components (split-string (abbreviate-file-name path) "/")) (len (+ (1- (length components)) (cl-reduce '+ components :key 'length))) (str "")) (while (and (> len max-len) (cdr components)) (setq str (concat str (if (= 0 (length (car components))) "/" (string (elt (car components) 0) ?/))) len (- len (1- (length (car components)))) components (cdr components))) (concat str (cl-reduce (lambda (a b) (concat a "/" b)) components)))) (defun rjs-eshell-prompt-function () (concat (shortened-path (eshell/pwd) 40) (if (= (user-uid) 0) " # " " $ "))) (setq eshell-prompt-function 'rjs-eshell-prompt-function) ``` --- Tags: package, package-repositories, install, symbol-function ---
thread-68993
https://emacs.stackexchange.com/questions/68993
How do I verify a downloaded emacs source tar.gz file?
2021-10-18T21:49:44.893
# Question Title: How do I verify a downloaded emacs source tar.gz file? I downloaded https://ftp.gnu.org/gnu/emacs/emacs-27.2.tar.gz\[.sig\] and tried verifying using the following command gpg --keyserver-options auto-key-retrieve --verify emacs-27.2.tar.gz.sig It failed with the following output: > gpg: Signature made Thu 25 Mar 2021 06:53:10 AM CDT using RSA key ID 01EB8D39 gpg: requesting key 01EB8D39 from hkp server keys.gnupg.net gpgkeys: HTTP fetch error 6: Could not resolve host: keys.gnupg.net; Unknown error gpg: no valid OpenPGP data found. gpg: Total number processed: 0 gpg: Can't check signature: No public key # Answer > gpg: requesting key 01EB8D39 from hkp server keys.gnupg.net gpgkeys: HTTP fetch error 6: Could not resolve host: keys.gnupg.net SKS keyservers such as keys.gnupg.net are no longer a thing (due to an attack on the keyserver network), and consequently programs/procedures which expected them to exist may now fail on that account. Some references are: > 2 votes # Answer I've never had luck with the `auto-key-*` options. Try using two steps. ``` $ ls -la emacs-27* .rw-r--r--@ 67M nega 18 Oct 22:13 emacs-27.2.tar.gz .rw-r--r--@ 473 nega 18 Oct 22:13 emacs-27.2.tar.gz.sig $ gpg --keyserver hkps://keyserver.ubuntu.com --recv-key 91C1262F01EB8D39 gpg: key 91C1262F01EB8D39: public key "Eli Zaretskii (eliz) <eliz@gnu.org>" imported gpg: Total number processed: 1 gpg: imported: 1 $ gpg --verify emacs-27.2.tar.gz.sig gpg: assuming signed data in 'emacs-27.2.tar.gz' gpg: Signature made Thu Mar 25 07:53:10 2021 EDT gpg: using RSA key 91C1262F01EB8D39 gpg: Good signature from "Eli Zaretskii (eliz) <eliz@gnu.org>" [unknown] gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: E6C9 029C 363A D41D 787A 8EBB 91C1 262F 01EB 8D39 ``` Note that as of at least `gpg 2.3.1` `--keyserver-options auto-key-retrieve` is deprecated in favor of `--auto-key-retrieve` (which also didn't work for me). > 2 votes --- Tags: source ---
thread-69390
https://emacs.stackexchange.com/questions/69390
global-set-key hotkeys not updating after reevaluating .ercrc.el file
2021-11-18T14:37:16.990
# Question Title: global-set-key hotkeys not updating after reevaluating .ercrc.el file I am working on configuring ERC. As a starting point I'm copying portions of the sample configuration file. So my .ercrc.el file begins with something this (taken straight from that guide): ``` (global-set-key "\C-cef" (lambda () (interactive) (erc :server "irc.freenode.net" :port "6667" :nick "MYNICK"))) ``` My problem is that if I change any of the parameters to erc inside the lambda, move to the end of the file, and I re-evaluate the file by pressing C-x C-e, the key still contains the old configuration values. The only way to make the change stick is to quit and open emacs again. How can I change what the C-c e f shortcut does without restarting emacs? # Answer > 1 votes > move to the end of the file, and I re-evaluate the file by pressing `C-x C-e` That's not what `C-x``C-e` does. `C-h``k``C-x``C-e` tells you: ``` C-x C-e runs the command eval-last-sexp ... Evaluate sexp before point ``` That's the *single* expression before point; definitely not "the file". You can evaluate the whole buffer with `M-x` `eval-buffer`. --- Tags: erc ---
thread-69393
https://emacs.stackexchange.com/questions/69393
How to know (in Elisp) what buffer was current when a command is invoked?
2021-11-18T18:14:39.840
# Question Title: How to know (in Elisp) what buffer was current when a command is invoked? I want to give an arbitrary command some buffer-local behavior without advising it. (I can do it by advising, but I want to also be able to do it without advising.) E.g., just looking at some property on a command symbol, I want to then do something only in *the buffer that was current when the command was invoked* (however it was invoked). Checking the property value can happen any time (and any number of times) after the command is invoked. The buffer-local behavior needs to change, to reflect the current value of the property. (It's OK to limit this to buffers that are displayed. I tried looking at `window-buffer-change-functions` etc., but I didn't notice anything that might help.) So far, I'm guessing that it's not possible from Lisp. But I'm hoping someone knows better, or at least knows for sure. (I posed this question on help-gnu-emacs@gnu.org, but haven't gotten any response yet.) # Answer Store the current buffer in a dynamic variable, then check `(current-buffer)` against that variable. If they differ, then the buffer was changed. However, I suggest that this is one of those X-Y questions that crop up from time to time. You should ask about what you’re really trying to implement, without constraining yourself to a narrow question about the implementation. > 0 votes --- Tags: buffers, commands, buffer-local, property-lists ---
thread-69396
https://emacs.stackexchange.com/questions/69396
Trouble rendering lilypond source block in org-babel
2021-11-18T22:54:09.410
# Question Title: Trouble rendering lilypond source block in org-babel I am relatively new to org mode and, as someone who enjoys writing about music, i decided to try org-babel-lilypond. I use MacOSx Monterey. I have lilypond installed via Macports, as was recommended in this thread. Lilypond seems to work as a command line interface, but when i try to render a lilypond source block in org-mode I'm met with the following error output: `/Applications/lilypond.app/Contents/Resources/bin/lilypond: No such file or directory` Is there a way to configure emacs/org-babel such that it doesn't have to use this directory to render a lilypond block? # Answer You have to customize the variable `org-babel-lilypond-commands`. You can see the variable's doc string with `C-h v org-babel-lilypond-commands` and you can customize it by clicking on the `Customize` link in that doc string. You can then set up how to start `Lilypond`, the `PDF` viewer and the `MIDI` player as appropriate for your system. Then hit `Apply` to set these options for this session. You can try things out and if everything is OK, you can click on `Apply and Save` to save the settings for future sessions. > 1 votes --- Tags: org-mode, org-babel, lilypond ---
thread-69398
https://emacs.stackexchange.com/questions/69398
How to remap C-w to quit emacs without saving?
2021-11-19T04:22:45.170
# Question Title: How to remap C-w to quit emacs without saving? Similar to how I close tabs in Chrome, I would like emacs to behave as if I pressed C-x C-c when I press C-w alone. Is that possible? I don't care if C-w was previously used to do some command. I am okay with overriding that. I tried this: `(define-key map (kbd "C-w") 'kill-emacs)` But this seems like it's invalid. I get: ``` Warning (initialization): An error occurred while loading ‘/home/user/.emacs’: Symbol's value as variable is void: map To ensure normal operation, you should investigate and remove the cause of the error in your initialization file. Start Emacs with the ‘--debug-init’ option to view a complete error backtrace. ``` # Answer > 2 votes You got it almost right. The error indicates that you tried to use a variable called `map` which isn’t defined; probably you copied it from some code where there was a variable called `map`. You probably want to use `global-map` instead; this is a variable which is predefined, and it holds the global key map: ``` (define-key global-map (kbd "C-w") 'kill-emacs) ``` Additionally, you could also call `global-set-key` instead of `define-key`: ``` (global-set-key (kbd "C-w") 'kill-emacs) ``` `global-set-key` isn’t very much faster to type, but it does have the advantage that it can also be called interactively during an Emacs session. For more information, I recommend reading chapter 49.3.6 Rebinding Keys in Your Init File in the Emacs manual. You can also read the manuals inside of Emacs; type `C-h i` to open the Info viewer. --- Tags: key-bindings, keymap ---
thread-69384
https://emacs.stackexchange.com/questions/69384
Org publish does not load Latex packages
2021-11-17T16:44:01.133
# Question Title: Org publish does not load Latex packages I need the following two packages and I add them to my org file like this, ``` #+LATEX_HEADER: \usepackage{siunitx} #+LATEX_HEADER: \usepackage{cancel} ``` but this does not work. How can I fix this? I tried with another package, it's strange, all instances work but one instance does not work. Screenshots below: ## Here's my setup file: ``` (require 'ox-publish) (setq org-publish-project-alist '( ("org-notes" :base-directory "~/org/" :base-extension "org" :publishing-directory "~/public_html/" :recursive t :publishing-function org-html-publish-to-html :headline-levels 4 ; Just the default for this project. :auto-preamble nil :html-preamble "<div id=\"navbar\"> <ul> <li><a href=\"index.html\">Home</a></li> <li><a href=\"/iletisim.html\">İletişim</a></li> <li><a href=\"/hakkinda.html\">Hakkında</a></li> </ul> <hr> </div> " ) ("org-static" :base-directory "~/org/" :base-extension "css\\|js\\|png\\|jpg\\|gif\\|pdf\\|mp3\\|ogg\\|swf" :publishing-directory "~/public_html/" :recursive t :publishing-function org-publish-attachment ) ("org" :components ("org-notes" "org-static")) ;; ... add all the components here (see below)... )) ``` This is the header and latex in the org file: ``` #+SETUPFILE: ~/.emacs.d/org-templates/level-0.org #+LATEX_HEADER: \usepackage{siunitx} #+LATEX_HEADER: \usepackage{cancel} \begin{align*} \frac{\text{A}}{\text{B}} &= \frac{\frac{\text{G} \times 10.64 \times d \times m}{(8.85)^2}}{\frac{\text{G} \times (41,800,000)^3 \times d' \times m}{(6.41 \times 41,800,000)^2}}\\ \\ &= \frac{\cancel{\text{G}}\times 10.64 \times d \times \cancel{m}}{(8.85)^2} \;\frac{(6\times 41,800,000)^2}{\cancel{\text{G}} \times (41,800,000)^3 \times d'\times \cancel{m} }\\ \\ &= 10.64 \times \left (\frac{6}{8.85}\right )^2 \times \frac{\cancel{(41,800,000)^2}}{(41,800,000)\cancel{^3}} \times \frac{d}{d'}\\ \\ &= \left (\frac{6}{8.85}\right )^2 \times \frac{10.64}{41,800,000} \times \frac{d}{d'}\\ \\ &= 0.4596380 \times \num{2.54e-7} \times \frac{d}{d'}\\ \\ &=\num{1.16998e-7}\frac{d}{d'}\\ \\ &=\frac{1}{\num{1.16998e-7}} = 8547088\times\frac{d'}{d}\\ \end{align*} ``` This is how the published pdf looks like: # Answer > 2 votes Just to summarize and amplify the discussion in the comments: the OP was trying to publish to HTML, not to PDF: that became clear after he posted his `org-publish-project-alist` which specifies `org-html-publish-to-html` as the publishing function. In that case (LaTeX math in the Org mode file that is being exported to HTML), the default method of rendering the math is by using Mathjax: do `C-h i g (org)math formatting in HTML export`). Mathjax is a Javascript display engine for math, so it works in all browsers. It knows a whole lot about LaTeX, but it does not know everything - in particular, if you use a LaTeX package (like `cancel.sty` e.g.) that `Mathjax` does not know about, you have to teach Mathjax to use it. What you have to do is described in this page which you probably should bookmark if you are using LaTeX math in Org mode files. The simplest thing that you can do (which is what the OP describes in a comment) is to add an inline "math" expression to your Org mode file that tells Mathjax to "require" the `cancel` package: ``` #+LATEX_HEADER: \usepackage{siunitx} #+LATEX_HEADER: \usepackage{cancel} * Foo \( \require{cancel} \) \[ (6.41\times 41800000)^2 = \frac{\cancel{G}\times 10.64\times d \times \cancel{m}}{(8.85)^2} \] ``` (don't try to make any sense of the equation: it is meaningless - if you want you can try with OP's complete source, but I set the test up before he had posted that, so I just copied fragments out of his images. The important thing is that the `\cancel`s are rendered incorrectly without the `\require` and they are rendered correctly with it.) BTW, you can test the above by just exporting to HTML: you don't have to have a publishing setup. Publishing is just "export with some copying/moving around of files afterwards" (roughly), so using just `export` to begin with can help with your debugging without having to deal with additional complications: export to an HTML file and then use a `file:///path/to/foo.html` URL to examine it. One problem with this solution is that it breaks PDF export (try it), because `\require` isn't LaTeX, despite appearances. It is a trigger to `Mathjax` to do something and LaTeX complains about an undefined control sequence (although it does produce a PDF file with the additional word `cancel` in it, a remnant of the `\require`). To fix that, just make sure that the `\require` is *only* used in HTML export: ``` ... #+begin_export HTML \( \require{cancel} \) #+end_export ... ``` But if you are going to use the `cancel` package often, you might want to teach Mathjax how to use it once and for all, so you don't have to `\require` anything in your Org mode file. The Org manual, in the `Math formatting in HTML export` section (see above for how to get there), says that you can add: ``` #+HTML_MATHJAX: cancel.js noErrors.js ``` to your Org mode file and that that will load the `cancel.js` and `noError.js` extensions to Mathjax: AFAICT this does *NOT* work. I also looked at the code and saw nothing to suggest that this is implemented. I'll post a doc bug on the ML. What *does* work is adding the following to your init file *after* loading `ox-html`: ``` (with-eval-after-load "ox-html" (setq org-html-mathjax-template (concat org-html-mathjax-template " <script type=\"text/x-mathjax-config\"> MathJax.Hub.Register.StartupHook(\"TeX Jax Ready\",function () { MathJax.Hub.Insert(MathJax.InputJax.TeX.Definitions.macros,{ cancel: [\"Extension\",\"cancel\"], bcancel: [\"Extension\",\"cancel\"], xcancel: [\"Extension\",\"cancel\"], cancelto: [\"Extension\",\"cancel\"] }); }); </script> "))) ``` This Javascript code then gets added to the HTML file and loads the `cancel.js` extension, which lets Mathjax know about `\cancel` and related macros. See the doc string of the variable with `C-h v org-html-mathjax-template` but be aware that it's just a string: a big blob of Javascript code that initializes and configures Mathjax. All that the Org mode HTML exporter does is replace a few placeholders with values from the variable `org-html-mathjax-options` (which see) and add the whole thing to the HTML file. For more details on the Javascript code, you will have to consult the Mathjax docs. --- Tags: org-mode, org-export, latex, org-publish, mathjax ---
thread-69404
https://emacs.stackexchange.com/questions/69404
When exporting to Latex from Org, how do I stop equations from breaking my paragraphs apart
2021-11-20T01:19:06.843
# Question Title: When exporting to Latex from Org, how do I stop equations from breaking my paragraphs apart When working with mathematics in Latex, if I add a percent sign between my previous textb block and my \begin{equation} block, and another percentage sign between my \end{equation} block and my next text block, I can prevent the text block after the equation from being indented. Is there a way I can accomplish the same thing when writing my document in org-mode and exporting it to Latex? # Answer Start the second paragraph with \noindent, as in: ``` \begin{equation} x^2 \end{equation} \noindent Pellentesque dapibus suscipit ligula. Donec posuere augue in quam. Etiam vel tortor sodales tellus ultricies commodo. Suspendisse potenti. Aenean in sem ac leo mollis blandit. Donec neque quam, dignissim in, mollis nec, sagittis eu, wisi. Phasellus lacus. Etiam laoreet quam sed arcu. Phasellus at dui in ligula mollis ultricies. Integer placerat tristique nisl. Praesent augue. Fusce commodo. Vestibulum convallis, lorem a tempus semper, dui dui euismod elit, vitae placerat urna tortor vitae lacus. Nullam libero mauris, consequat quis, varius et, dictum id, arcu. Mauris mollis tincidunt felis. Aliquam feugiat tellus ut neque. Nulla facilisis, risus a rhoncus fermentum, tellus tellus lacinia purus, et dictum nunc justo sit amet elit. ``` Or use a latex block so you can put a % in it. ``` Aliquam erat volutpat. Nunc eleifend leo vitae magna. In id erat non orci commodo lobortis. Proin neque massa, cursus ut, gravida ut, lobortis eget, lacus. Sed diam. Praesent fermentum tempor tellus. Nullam tempus. Mauris ac felis vel velit tristique imperdiet. Donec at pede. Etiam vel neque nec dui dignissim bibendum. Vivamus id enim. Phasellus neque orci, porta a, aliquet quis, semper a, massa. Phasellus purus. Pellentesque tristique imperdiet tortor. Nam euismod tellus id erat. #+BEGIN_EXPORT latex \begin{equation} x^2 \end{equation} % #+END_EXPORT Pellentesque dapibus suscipit ligula. Donec posuere augue in quam. Etiam vel tortor sodales tellus ultricies commodo. Suspendisse potenti. Aenean in sem ac leo mollis blandit. Donec neque quam, dignissim in, mollis nec, sagittis eu, wisi. Phasellus lacus. Etiam laoreet quam sed arcu. Phasellus at dui in ligula mollis ultricies. Integer placerat tristique nisl. Praesent augue. Fusce commodo. Vestibulum convallis, lorem a tempus semper, dui dui euismod elit, vitae placerat urna tortor vitae lacus. Nullam libero mauris, consequat quis, varius et, dictum id, arcu. Mauris mollis tincidunt felis. Aliquam feugiat tellus ut neque. Nulla facilisis, risus a rhoncus fermentum, tellus tellus lacinia purus, et dictum nunc justo sit amet elit. ``` Or, you can add a latex line like this to get a % there. ``` Aliquam erat volutpat. Nunc eleifend leo vitae magna. In id erat non orci commodo lobortis. Proin neque massa, cursus ut, gravida ut, lobortis eget, lacus. Sed diam. Praesent fermentum tempor tellus. Nullam tempus. Mauris ac felis vel velit tristique imperdiet. Donec at pede. Etiam vel neque nec dui dignissim bibendum. Vivamus id enim. Phasellus neque orci, porta a, aliquet quis, semper a, massa. Phasellus purus. Pellentesque tristique imperdiet tortor. Nam euismod tellus id erat. \begin{equation} x^2 \end{equation} #+latex: % Pellentesque dapibus suscipit ligula. Donec posuere augue in quam. Etiam vel tortor sodales tellus ultricies commodo. Suspendisse potenti. Aenean in sem ac leo mollis blandit. Donec neque quam, dignissim in, mollis nec, sagittis eu, wisi. Phasellus lacus. Etiam laoreet quam sed arcu. Phasellus at dui in ligula mollis ultricies. Integer placerat tristique nisl. Praesent augue. Fusce commodo. Vestibulum convallis, lorem a tempus semper, dui dui euismod elit, vitae placerat urna tortor vitae lacus. Nullam libero mauris, consequat quis, varius et, dictum id, arcu. Mauris mollis tincidunt felis. Aliquam feugiat tellus ut neque. Nulla facilisis, risus a rhoncus fermentum, tellus tellus lacinia purus, et dictum nunc justo sit amet elit. ``` > 2 votes --- Tags: org-export, latex ---
thread-28204
https://emacs.stackexchange.com/questions/28204
How to set web-mode to use single-line comment style instead of multi-line for JavaScript
2016-10-28T10:49:47.533
# Question Title: How to set web-mode to use single-line comment style instead of multi-line for JavaScript When commenting C-style code like C++, JavaScript etc., I use single-line comments to be able to uncomment a previously commented region selectively, i.e ``` // This // is // a single-line style // comment ``` If I later want to uncomment lines 2 and 3, for example, I would simply select them and uncomment. With multi-line comments `/* */`, however, I would first need to uncomment the whole block, then selectively comment the parts excluding those that I wanted to uncomment in the first place. From this question, I found out that I can change the comment character to `//` by putting in my config ``` (setq-default web-mode-comment-formats (remove '("javascript" . "/*") web-mode-comment-formats)) (add-to-list 'web-mode-comment-formats '("javascript" . "//")) ``` This, however, does not change the commenting behavior of web-mode. When I select the desired region and run `web-mode-comment-or-uncomment-region`, it still exhibits multi-line behavior and uncomments the whole block instead of the region that I select. How can I uncomment just the selected region instead of the whole block? # Answer It could be that `web-mode-comment-formats` is not defined when emacs is initialized and thus removes nothing from it at that stage, in my case `web-mode` is loaded only on demand so trying to customize it at that point doesn't make sense. Try to do that customization in a `web-mode-hook` or set explicitly the values you need in that list: ``` (setq web-mode-comment-formats '(("typescript" . "//") ("javascript" . "//") ("java" . "//")) ``` > 0 votes --- Tags: indentation, web-mode, comment ---
thread-69408
https://emacs.stackexchange.com/questions/69408
What to put into 'init.el' vs 'config.el' in Org-mode?
2021-11-20T12:11:14.437
# Question Title: What to put into 'init.el' vs 'config.el' in Org-mode? I'm using Org-mode to configure Emacs in a file 'config.el', which is really unstructured meanwhile. On the other hand, lots of configurations (for exemple the configs made with the menu) are in Emacs' own 'init.el'. I would like now to put all the stuff not needed in the 'init.el' to the 'config.el' in order to get it organized with Org-mode. So what is the difference between these files, and what is the minimal content of 'init.el'? # Answer > what is the difference between these files? `init.el` is a standard Emacs init filename, and `config.el` is something you've invented. > what is the minimal content of 'init.el'? Nothing. Empty. Emacs doesn't require that the file exist at all. > 1 votes --- Tags: init-file, org-babel, config ---
thread-69401
https://emacs.stackexchange.com/questions/69401
evil mode: delete word starting with backslash leaves the last character
2021-11-19T10:47:18.070
# Question Title: evil mode: delete word starting with backslash leaves the last character I am using evil mode. In org-mode files, when I try to delete a word with `dw` and the word starts with a `\`, the last letter of the word is not deleted. For example, if my cursor is on the `b` of `\begin{section}` and I type `dw` I get `\n{section}` instead of `\{section}`. This happens *only in org-mode* (not in LaTeX or text files), but I can't figure out where in this comes from in my settings. Any idea? # Answer Found it! `(global-superword-mode 1)` is responsible for it. > 1 votes --- Tags: org-mode, evil, words ---
thread-69411
https://emacs.stackexchange.com/questions/69411
How do I mark emails as read in notmuch?
2021-11-20T17:10:54.530
# Question Title: How do I mark emails as read in notmuch? This feels like a super basic question, but it's got me stumped. I'm using `mbsync` \+ `notmuch` to collect my email locally, both from a Google mail account in one case and from an Exchange account in another. I can read my email just fine in `notmuch-mode` but... the messages are never marked as "read" -- they're still tagged as unread no matter what I do. I'm not doing anything particularly interesting in the configuration of either of those tools, that I know of, but I'll be honest I'm completely new to the idea of even reading email in Emacs; I'm dipping my toes in the water and finding that the water is deep and confusing :) So, how do I mark emails as "read" in `notmuch-mode` in a way that will propagate back to the server? # Answer > 1 votes You can customize the variable `notmuch-show-mark-read-function` to control this. The default value is `notmuch-show-seen-current-message`, which does mark the message as read. --- Tags: email, notmuch ---
thread-69413
https://emacs.stackexchange.com/questions/69413
How to specify lsp configuration messages in emacs?
2021-11-20T20:17:24.180
# Question Title: How to specify lsp configuration messages in emacs? I'm trying to configure rust analyzer to expand proc macros. According to it's documentation I have to configure my editor (i.e. emacs) to send this JSON as a LSP message: ``` { "cargo": { "loadOutDirsFromCheck": true, }, "procMacro": { "enable": true, } } ``` I couldn't find anything in Emacs's documentation on how to do it. # Answer > 1 votes Ok, so you are asking about the configuration options listed in the rust-analyzer documentation. I wasn’t able to find out much about the subject in the `lsp-mode` documentation, so instead I took a quick peek in the `lsp-rust` source code. I soon found that there is a function called `lsp-rust-analyzer--make-init-options` that returns the data structure that will be encoded as JSON and sent to the server. You can view the source inside Emacs (type `C-h f` and enter the function name; it opens a help buffer for the function which includes a link to its source code), but it is also viewable on GitHub. If you look through this giant thing, you’ll eventually see `:cargo` and `:procMacro` sections. Specifically, you’ll see this: ``` :procMacro (:enable ,(lsp-json-bool lsp-rust-analyzer-proc-macro-enable)) ``` which uses the variable `lsp-rust-analyzer-proc-macro-enable` to enable or disable support for procedural macros. Similarly: ``` :cargo (… :loadOutDirsFromCheck ,(lsp-json-bool lsp-rust-analyzer-cargo-run-build-scripts) …) ``` does the same thing with the `lsp-rust-analyzer-cargo-run-build-scripts` variable. Both of these variables refer to customizable settings. To edit them, you can just run `M-x customize-group`, and then type `lsp-rust-analyzer` at the prompt. This lists all of the settings for the `lsp-rust-analyzer` module, and gives you a nice interface for editing them. It also turns out that these variables are both documented in the `lsp-mode` documentation; I had simply failed to notice them. --- Tags: lsp-mode, config, rust ---
thread-53904
https://emacs.stackexchange.com/questions/53904
Why can't I list the contents of Desktop on macos using dired?
2019-11-21T12:20:24.687
# Question Title: Why can't I list the contents of Desktop on macos using dired? When I do `C-x C-f` on `~/Desktop/` in macos Catalina, I get the following error. ``` Listing directory failed but 'access-file' worked ``` I can list the directory for just `~`. I'm new to Emacs and know little else. I've tried installing Emacs through Homebrew and using a binary from `https://emacsformacosx.com` I've also searched for that error where some people said there's an issue with `ls` on mac, but I don't have any problem listing the contents of `~`. Also, I didn't find any clear solution to that problem (I tried copy pasting answers to my init file but that didn't solve anything). # Answer I found it. Apparently dired can't access icloud directories. My Desktop and Documents folders are sync'ed with icloud. http://emacs.1067599.n8.nabble.com/iCloud-directory-access-issue-on-macOS-Catalina-td499227.html If anyone comes here curious as to how they can access Desktop, Documents, or Downloads, the answer is in the link above, for reference, but I'll put it here in case that link expires. 1. In System Preferences -\> Security & Privacy, select the Privacy tab. 2. From the list on the left, select Full Disk Access. 3. Click the padlock in the lower left of the window to unlock this setting, if necessary. 4. Click the + button to add Emacs to the list, then add Emacs. * Note: *If* it's already checked, try unchecking, allowing it to quit and restart emacs, then check it, and allow it to quit and restart emacs again. Updating this answer since my original instructions aren't enough anymore. I had to also add ruby as others have pointed out in their answers. 5. Click the + button to add /usr/bin/ruby, but the usr folder is hidden in the UI it pops up, so press Shift+Command+G to popup a thing where you can type in /usr/bin, and then select the ruby program. > 59 votes # Answer If you find the problem persists after granting Emacs full disk access: from here on the problem remains because Emacs on MacOS gets launched indirectly, from a Ruby script. Your Emacs binary has full disk access, but Ruby does not. One way to get around this is to get the Ruby script out of the way, and replace it with a symlink to the correct binary for your platform. See https://github.com/caldwell/build-emacs/issues/84#issuecomment-545754668 for an example. > 13 votes # Answer I followed Nabi and Vinh's solutions. `dired` worked but not all functions. For example, the `sort` is not working. A quick search leads me here: https://github.com/d12frosted/homebrew-emacs-plus/issues/383#issuecomment-899157143 The problem is that macos's built-in `ls` does not support several flags `dired+` use. What worked for me is following instructions here: https://stackoverflow.com/a/65112096/4062451 Notice that you might need to change the path `insert-directory-program` to where your brew is installed > 2 votes # Answer In my case, just allow Full Disk for ruby (/usr/bin/ruby) then it works like charm! > 1 votes --- Tags: dired, osx, desktop ---
thread-69414
https://emacs.stackexchange.com/questions/69414
How to build an agenda buffer from specific files listed in org-agenda-files?
2021-11-20T21:01:05.063
# Question Title: How to build an agenda buffer from specific files listed in org-agenda-files? `A` being the set of all the .org files I use for schedules, I restrained agenda searches to `A` like this : ``` (setq org-agenda-files (quote ("../file_1.org" "../file_2.org" ... "../file_n.org" ))) ``` It is useful to be able to see all the tasks stored in these files in an agenda view. However, I would also like to be able to have an agenda view showing only the content of a specific subset of `A`. This specific subset being different according to the project I'm working on. For example, let's say I would like to switch between `org-agenda-list` for `file_1.org` and `file_2.org` and `org-agenda-list` for `file_5.org`. # Answer I think the most idiomatic way to do this is to set `org-agenda-custom-commands` with an agenda let-binding `org-agenda-files`. Something like: ``` (setq org-agenda-custom-commands '(("o" "crocefisso" agenda "" ((org-agenda-files '("../file_1.org" "../file_2.org")))))) ``` (Untested, since I don't have your setup here, but take a look at the variable's docstring and the manual and, if you are not familiar with the variable, you may want to use the customize interface to set it). > 4 votes # Answer Thanks to lawlist suggestions I managed to find a solution. But first I had to learn how to deal with functions and key binding in Emacs Lisp (I hope my code is compliant with conventions). **Note that this solution works even if `file_1.org`, `file_2.org` and `file_5.org` don't belong to `A`.** So here is the code to put in the .emacs config file: Code for file\_1.org and file\_2.org, key bound with `C-c n` ``` (defun file_1_and_2() "lauch org-agenda for file_1.org and file_2.org." (interactive) (let ((org-agenda-files '("../file_1.org" "../file_2.org"))) (org-agenda)) ) (global-set-key (kbd "C-c n") 'file_1_and_2) ``` Code for file\_5.org, key bound with `C-c s`. ``` (defun file_5() "lauch org-agenda for file_5.org." (interactive) (let ((org-agenda-files '("../file_5.org"))) (org-agenda)) ) (global-set-key (kbd "C-c s") 'file_5) ``` The only drawback, is that when I navigate in the Agenda buffer with `f` (`org-agenda-later`) and `b` (`org-agenda-earlier`), the view goes back to show searches related to `A`. If someone has an idea of how to prevent that, I'm interested. > 0 votes --- Tags: org-mode, org-agenda ---
thread-69423
https://emacs.stackexchange.com/questions/69423
Is this syntax parse possible with Emacs' regex expressions?
2021-11-22T10:43:47.957
# Question Title: Is this syntax parse possible with Emacs' regex expressions? I'm trying to write a small new mode for some input files to a specific computational physics program. I'm doing it the `define-derived-mode` way, and was specifying the syntax highlighting by setting the `font-lock-defaults` variable, when I realized I needed a regex that does "match any lone words between a line start and an equals sign, not including the equals sign." This is relatively straightforward with extended regex; I found a quite popular SO answer that gave a short solution in terms of a zero-width assertion. However, I don't see any extended regex support in the manual. Is there a way to do this with Emacs' regex? If not, is there a way to do it with rx (with which I'm an absolue novice)? Failing that, how do packages like cc-mode which need to do something similar to identify different parts of e.g. a variable declaration in their syntax highlighting do this? # Answer > 1 votes If a regexp doesn't work, you can use function that does the matching for you. If it behave as a match function, i.e. set match-data and return non-nil when it match something, you can continue to use the font-lock keyword to specify which face to apply to which part of the match. See the documentation for `font-lock-keywords` for more details. One such package that use this technique is https://github.com/Lindydancer/cmake-font-lock -- for example `cmake-font-lock-match-dollar-braces` is used to match the `${xxx}` construct. # Answer > 2 votes If you want to match `foo=` and then highlight the `foo` part, font-lock allows you to do that by grouping sub-expressions in the regexp and then highlighting only a specified sub-expression. Look for `SUBEXP` in `C-h v font-lock-keywords`. `C-h``i``g` `(elisp)Search-based Fontification` says: ``` ‘(MATCHER . SUBEXP)’ In this kind of element, MATCHER is either a regular expression or a function, as described above. The CDR, SUBEXP, specifies which subexpression of MATCHER should be highlighted (instead of the entire text that MATCHER matched). ;; Highlight the ‘bar’ in each occurrence of ‘fubar’, ;; using ‘font-lock-keyword-face’. ("fu\\(bar\\)" . 1) If you use ‘regexp-opt’ to produce the regular expression MATCHER, you can use ‘regexp-opt-depth’ (*note Regexp Functions::) to calculate the value for SUBEXP. ``` --- Tags: regular-expressions, font-lock, major-mode, syntax-highlighting, rx ---
thread-69424
https://emacs.stackexchange.com/questions/69424
How to find the matching environment command in tex mode?
2021-11-22T10:52:56.527
# Question Title: How to find the matching environment command in tex mode? A latex environment looks like this: ``` \begin{envName} body \end{envName} ``` Is there a command to jump back-and-forth between matching `\begin` and `\end` commands? (One cannot simply use a regex search because environments can be nested) # Answer `LaTeX-find-matching-begin` and `LaTeX-find-matching-end` functions do this. ``` AUCTeX offers keyboard shortcuts for moving point to the beginning and to the end of the current environment. -- Command: LaTeX-find-matching-begin ('C-M-a') Move point to the '\begin' of the current environment. -- Command: LaTeX-find-matching-end ('C-M-e') Move point to the '\end' of the current environment. ``` > 5 votes --- Tags: latex ---
thread-69421
https://emacs.stackexchange.com/questions/69421
Using after-change-functions for an ansi-term buffer
2021-11-21T14:48:32.257
# Question Title: Using after-change-functions for an ansi-term buffer I'm writing some Elisp that compiles code in watch mode using `make-term`. When the code compiles/tests pass, the compilation output is only a couple of lines. When there's an error, it can be much longer. So I would like to resize the window of the term buffer whenever the buffer content changes, to use screen space efficiently. I tried doing this by adding a function to `after-change-functions` (buffer-locally) that calls `fit-window-to-buffer`, but it never seems to get called. I'm pretty sure the code is right because it works for the `*scratch*` buffer. Is it possible to get this behaviour for term buffers? Code: ``` (defun build-watch () (interactive) (let ((compile-buffer-name-no-asterisks "compile")) (make-term compile-buffer-name-no-asterisks "compiler" nil "args") (let ((compile-buffer-name (format "*%s*" compile-buffer-name-no-asterisks))) (switch-to-buffer-other-window compile-buffer-name) (read-only-mode) (setq-local after-change-functions (cons (lambda (_start _end _length) (fit-window-to-buffer)) after-change-functions))))) ``` # Answer > 0 votes ``` -(let ((buffer-name (format "*%s*" compile-buffer-name-no-asterisks))) +(let ((compile-buffer-name (format "*%s*" compile-buffer-name-no-asterisks))) ``` Also, you should use `add-hook` with its `LOCAL` argument to add buffer-local hook functions (even with abnormal hooks like `after-change-functions`). Your current approach will cause multiple kinds of duplication. --- Tags: hooks, term, ansi-term ---
thread-69437
https://emacs.stackexchange.com/questions/69437
Point to bound variables in scope
2021-11-23T00:10:04.437
# Question Title: Point to bound variables in scope So, Dr. Racket has a very interesting feature where you can see all occurrences of a bound variable if you hover it: Is there a way to do something similar in Emacs? I'm currently editing C++ code. It doesn't need to be super-sophisticated: I'd be super-happy with just the local lexical context. --- This proved really useful to me, but it will highlight any matching words in the entire text, not just the code (let alone the enclosing lexical context.) # Answer It depends on the language. For Javascript, `js2-mode` has a complete language parser and so understand exactly which words really are variables, and which are the correct ones. `js2-refactor` has some functionality that relies on that exact information; I believe it can both highlight all occurrences of a variable and rename it, though it doesn’t draw lines over the top like that. For C++, I have heard people mention the `srefactor` package. I’ve never used it though, so I don’t know if it does exactly what you want. You might also be interested in a general guide to related Emacs packages for C/C++ development. There is also `lsp-mode`, which is all the rage at the moment. > 2 votes --- Tags: search, syntax-highlighting, c++ ---
thread-69439
https://emacs.stackexchange.com/questions/69439
Keymap that is dependent on the buffer
2021-11-23T08:45:39.353
# Question Title: Keymap that is dependent on the buffer I want to create a "toggle shell" shortcut with F1 such that it will run `shell` when I'm in any other buffer, but will call `mode-line-other-buffer` when I'm in the shell buffer. What is an efficient way to achieve this? # Answer You set `shell-command` as global key-binding for `F1` and you add a hook function to `shell-mode-hook` that sets the local key binding to `mode-line-other-buffer`. ``` (global-set-key (kbd "<f1>") #'shell) (defun my-shell-mode-hook () "My preferred settings for `shell-mode'." (local-set-key (kbd "<f1>") #'mode-line-other-buffer)) (add-hook 'shell-mode-hook #'my-shell-mode-hook) ``` You can put this stuff into your init file. > 9 votes --- Tags: key-bindings, commands, shell-mode ---
thread-69442
https://emacs.stackexchange.com/questions/69442
How to list the project by the name instead of the path in projectile?
2021-11-23T14:31:47.743
# Question Title: How to list the project by the name instead of the path in projectile? I'm new to DOOM emacs and try to get used to projectile. I found how to set the project name by using `.dir-locals.el`, which can be done by `((nil . ((projectile-project-name . "PROJECT-NAME"))))`. However, the problem is that when I want to switch project to other projects, the project list shows the path of the project instead of its name. I couldn't find any solutions about this. Are there ways to list the project by its name (I couldn't understand why projectile use the path of the project instead of its name although the name is more intuitive)? # Answer > 1 votes Projectile only uses the project name to display in the modeline of files that are part of the project. Usually the project name is taken from the final path element of the path to the project root. Moreover, the `.dir-locals.el` file is not loaded in advance; it is only loaded after you open a file in that directory or subdirectory. It only tells Projectile the name of the current project, not the names of any other projects you might happen to have. Finally, you can organize projects on your system in any way you would like. Projectile doesn’t know where they will be located, or how you are going to group them. Therefore it asks you for a path to the project when you want to open one. Alternatively, you can simply open any file directly; Projectile will check to see if the file is located within any type of project that it recognizes. See the documentation for how it recognizes a project when you open a file. --- Tags: projectile, doom ---
thread-69445
https://emacs.stackexchange.com/questions/69445
Org publish html preamble navigation bar does not work
2021-11-23T16:57:20.870
# Question Title: Org publish html preamble navigation bar does not work I tried to change html preamble by adding a new item to the nav bar, but publish is not updating the navigation bar. I found this question, but I didn't know how to add a "force flag" to org-publish function. But I'm not sure if that's the problem. My org-publish file below. I'm trying to add one more item to the list in the preamble. ``` (require 'ox-publish) (setq org-publish-project-alist '( ("org-notes" :base-directory "~/org/" :base-extension "org" :publishing-directory "~/public_html/" :recursive t :publishing-function org-html-publish-to-html :headline-levels 4 ; Just the default for this project. :auto-preamble nil :html-preamble "<div id=\"navbar\"> <ul> <li><a href=\"index.html\">Home</a></li> <li><a href=\"blog.html\">Blog</a></li> <li><a href=\"/iletisim.html\">İletişim</a></li> <li><a href=\"/hakkinda.html\">Hakkında</a></li> </ul> <hr> </div> " ) ("org-static" :base-directory "~/org/" :base-extension "css\\|js\\|png\\|jpg\\|gif\\|pdf\\|mp3\\|ogg\\|swf" :publishing-directory "~/public_html/" :recursive t :publishing-function org-publish-attachment ) ("org" :components ("org-notes" "org-static")) ;; ... add all the components here (see below)... )) ``` # Answer You can use `C-u M-x org-publish-current-project` or `C-u M-x org-publish-current-file` to force the publishing of the current project (the project associated with the current file) or just the current file. Alternatively, you can forego using timestamps for checking whether something is updated. Setting ``` (setq org-publish-use-timestamps-flag nil) ``` will *always* publish everything (which might not be a good idea if the project is large and takes a while to publish). You can also clean out the timestamps to force publishing even if `org-publish-use-timestamps-flag` is set to the default `t` value. The timestamps are saved in the directory `~/.org-timestamps` by default: check the value of `org-publish-timestamp-directory` for the actual value. You can just delete the `<project>.cache` file for your project (`org-notes` in your case). > 1 votes --- Tags: html, org-publish ---
thread-69449
https://emacs.stackexchange.com/questions/69449
How can you list all non-child frames?
2021-11-23T22:17:52.047
# Question Title: How can you list all non-child frames? There's `frame-list` but this lists child-frames, and there's `visible-frame-list` but this doesn't list iconified frames. It seems like there should be a simple function to return all non-child frames. I suspect it can be hacked together with `filtered-frame-list` but my elisp-fu is not strong enough to figure it out. # Answer You just need to filter the frames returned by `frame-list` selecting only the ones that have a null `parent-frame`: ``` (defun non-child-frame-list () (let ((frames (frame-list))) (seq-filter (lambda (frame) (null (cadr (assoc 'parent-frame (frame-parameters frame))))) frames))) ``` You can call it like this `ESC ESC : (non-child-frame-list)`. Alternatively, as you surmised, you can do it with `filtered-frame-list` with this predicate: ``` (defun non-child-frame-p (frame) (null (cadr (assoc 'parent-frame (frame-parameters frame))))) ``` Then you can do `(filtered-frame-list #'non-child-frame-p)`. > 1 votes --- Tags: frames ---
thread-69434
https://emacs.stackexchange.com/questions/69434
Using elpy in my dotemacs file
2021-11-22T18:35:45.230
# Question Title: Using elpy in my dotemacs file I am trying to use the elpy python package by putting it in my dotemacs file. But, when I fire up an emacs session and type inside the source code frame ( I don't split any frames ), I get the following messages in sequence with the first one going away very quickly so it's hard to read. First message: > Elpy is trying to create RPC virtualenv /home/markleeds/emacs.d/elpy/rpc-env Second message: > error in process sentinel: peculiar error: "exited normally with code 1 . Note that these error messages are in many threads on the internet so I'm thinking that someone may have seen it before. I'm so inexperienced with emacs usage ( I always just used it in a very basic way until recently when I started working on modifying it ) that, when I go through the threads with the identical messages, I can't even tell if a solution was found. If it is a mistake to send this here and I should instead send it to the python stackexchange list, then my apologies and I will do that. Note that, if I do, `emacs --debug-init sieve.py`, I don't get any messages at the bottom until I start typing and then I get the messages above. The link that I am trying to follow is https://realpython.com/emacs-the-best-python-editor. Thanks for your help and, if I made mistakes in explaining my problem, I'm all ears and apologize in advance. P.S: I am using ubuntu 20.04, python 2.7.18 and emacs 27.2. # Answer > 0 votes I had that problem and found this link which suggested doing `M-x elpy-rpc-reinstall-virtualenv`. That worked for me and it also seems to have worked for a few other people. Try it and see if it works for you. # Answer > 0 votes See https://emacs.stackexchange.com/a/66732/202 The key point is Emacs' python environment is independent. --- Tags: elpy ---
thread-69448
https://emacs.stackexchange.com/questions/69448
How to open emacsclient with working directory set to $PWD?
2021-11-23T20:22:58.447
# Question Title: How to open emacsclient with working directory set to $PWD? In my XTerm, I want to open new Emacs frame as well as buffer, with working directory set to $PWD in XTerm env. I tried `emacsclient -t -c --eval "(cd $PWD)"`, but it doesn't seem to work. Is it possible? # Answer > 1 votes If you want to create a buffer for a new file `./new-buffer` in the current directory, just call `emacsclient` with that filename, like ``` emacsclient -t ./new-buffer ``` The option `-t` causes `emacsclient` to open the buffer in a newly created frame on the current terminal. If you create a new non-file buffer the default directory for that buffer is the current directory of `emacsclient`. Examples: ``` emacsclient -t --eval "(eshell t)" emacsclient -t --eval "(switch-to-buffer (generate-new-buffer \"*new-buffer*\"))" ``` --- Tags: emacsclient, eval ---
thread-69456
https://emacs.stackexchange.com/questions/69456
Can I export conf source code in org-mode to aconf in LaTeX/pdf/minted?
2021-11-24T11:05:57.587
# Question Title: Can I export conf source code in org-mode to aconf in LaTeX/pdf/minted? Emacs org-mode source-code blocks (between `#+begin_src conf` and `#+end_src`) support the `conf` "language"/style with syntax highlighting, but this is not supported when exporting to LaTeX/pdf, which uses the minted LaTeX package. Instead, LaTeX/minted gives nice results when using the `aconf` style, which doesn't look nice in org-mode itself. Apart from filing a feature request, is there a quick fix/workaround where the `conf` style in org-mode is exported as `aconf` in LaTeX, or where the `aconf` style in org-mode gets the same status as the `conf` style? Or is there perhaps another solution? # Answer Try customizing `org-latex-minted-langs`. This variable maps symbols (e.g. the symbol `conf` as used in your source block) to a minted "language" (e.g. the string "aconf"). The doc string of the variable (`C-h v org-latex-minted-langs`) says: > Alist mapping languages to their minted language counterpart. The key is a symbol, the major mode symbol without the "-mode". The value is the string that should be inserted as the language parameter for the minted package. If the mode name and the listings name are the same, the language does not need an entry in this list - but it does not hurt if it is present. > > Note that minted uses all lower case for language identifiers, and that the full list of language identifiers can be obtained with: > > pygmentize -L lexers The doc string also conveniently provides a `Customize` link. Click on that and add an entry by clicking on the `INS` button at the end and entering `conf` as the major mode and `aconf` as the minted language. Click on `Apply` at the top and try it out. If it works, click on `Apply and Save` and you are done. > 1 votes --- Tags: org-mode, org-export, latex ---
thread-69461
https://emacs.stackexchange.com/questions/69461
How to move from one source block to another, in Org-mode?
2021-11-24T15:39:35.963
# Question Title: How to move from one source block to another, in Org-mode? Is there a key-binding, command, or even evil extension for Emacs, so that I can move from one source block to another? For example,`org-forward-heading-same-level`, which is bound in my system to `C-j`, etc. # Answer Yes, there is, run `M-x org-babel-next-src-block`. The default keybindings for this function are `C-c C-v C-n` and `C-c C-v n`. See also the subsection Key bindings and Useful Functions in the orgmode manual. > 5 votes --- Tags: org-mode, key-bindings, commands, motion ---
thread-69447
https://emacs.stackexchange.com/questions/69447
How to automatically build org links from an org-contacts contact?
2021-11-23T19:55:39.450
# Question Title: How to automatically build org links from an org-contacts contact? Let's say I have the following contact in my `org-contacts` org file : ``` * John Doe :PROPERTIES: :EMAIL: john.doe@gmail.com :PHONE: +44 20 7630 2400 :COMPANY: Ubuntu :NOTE: :END: ``` How could I build a macro (I guess a function activated by a key binding) that would allow me to automatically create an `org-store-link`s that would link to an orgmode file located in `~\myfolder` based on the contact name, when I point the cursor after `:NOTE:`. Here the generated link would be `[[~\myohterfolder\johndoe.org][John Doe Card]]` Or maybe a function could be inserted in the `org-capture-template` to generate the link when the contact is created. Here is my template: ``` ("c" "Networking Contacts" entry (file+headline "~/path/contacts.org" "Networking") "* %(org-contacts-template-name) :PROPERTIES: :EMAIL: %(org-contacts-template-email) :PHONE: :COMPANY: [[./otherpath/companies.org::][C]] :NOTE: :END:") ``` # Answer If `org-contacts-template-name` returns the template name ("John Doe" in your example), then you should be able to do something like this: ``` ... :NOTE: [[file:~/myotherfolder/%(munge (org-contacts-template-name)).org][%(org-contacts-template-name) Card]] ... ``` where `munge` is a function that takes the template name and returns the basename of the file ("johndoe" in your example), e.g. by converting it to lower case and deleting whitespace: ``` (defun munge (tname) (downcase (replace-regexp-in-string "[[:space:]]+" "" tname))) ``` Tested only in simulation: I don't have `org-contacts` installed. EDIT: here's a quick and dirty way to get the name interactively *once* and then use it later for the other cases: ``` (defvar org-contacts-template-name nil) (defun munge (tname) (downcase (replace-regexp-in-string "[[:space:]]+" "" tname))) (defun my-org-contacts-template-name (&optional arg) (if arg arg (setq org-contacts-template-name (read-from-minibuffer "Name: " nil)))) (setq org-capture-templates '(("c" "Networking Contacts" entry (file+headline "~/tmp/org/contacts.org" "Networking") "* %(my-org-contacts-template-name) :PROPERTIES: :PHONE: :EMAIL: %(org-contacts-template-email) :COMPANY: [[file:~/tmp/org/companies.org::][C]] :NOTE: [[file:~/tmp/org/%(munge (my-org-contacts-template-name org-contacts-template-name)).org][%(my-org-contacts-template-name org-contacts-template-name) Card]] :END:"))) ``` Basically, we define a (dynamically scoped, global) variable `org-contacts-template-name`, and we use a different function to ask the user to enter a value which is saved in that global variable. The function is called again, but now with a non-nil argument (the value of the previously-set global variable, which is just returned in that case) in the other instances of the template. This is probably quite delicate and fragile (e.g. it assumes that the capture template is processed top-to-bottom, which seems to be the case today, but there are no guarantees; there is also *no* error handling at all), but it does seem to work. Extending it to more inputs is left as an exercise. I would recommend the Introduction to Emacs Lisp: if you are going to hack Emacs Lisp, then you need to learn some :-) > 1 votes # Answer Thanks to @NickD inputs I found a satisfying solution. Here is the code: #### Naming Org file ``` #+begin_src emacs-lisp (defun org-name (tname) (downcase (replace-regexp-in-string "[[:space:]]+" "" tname))) #+end_src ``` #### Contact name input ``` #+begin_src emacs-lisp (defun con-input() (setq x (read-from-minibuffer "Card : "))) #+end_src ``` #### Company name input ``` #+begin_src emacs-lisp (defun com-input() (setq y (read-from-minibuffer "Company : "))) #+end_src ``` #### org-contacs capture ``` #+begin_src emacs-lisp ("c" "Networking Contacts" entry (file+headline "...path/contacts.org" "Networking") "* %(org-contacts-template-name) :PROPERTIES: :EMAIL: %(org-contacts-template-email) :PHONE: :NOTE: [[.../otherpath/%(org-name(con-input)).org][%(princ x) Card]] :COMPANY: [[.../anotherpath/companies.org::%(com-input)][%(princ y)]] :NOTE: :END:") #+end_src ``` > 0 votes --- Tags: org-mode, org-link, org-contacts ---
thread-69459
https://emacs.stackexchange.com/questions/69459
fixed width of column in csv mode
2021-11-24T15:12:13.343
# Question Title: fixed width of column in csv mode I plan to use `csv-mode`. In Excel, csv can be shown like the Picture 2. In emacs, `C-c C-a` yields Picture 1. Can I fix the width of the columns in `csv-mode`? Picture 1 Picture 2 # Answer I found that the following setting solve this issue. ``` (use-package csv-mode :config (setq csv-align-max-width 7) (define-key csv-mode-map (kbd "C-c C-a") 'csv-align-mode)) ``` > 1 votes --- Tags: csv ---
thread-69464
https://emacs.stackexchange.com/questions/69464
Is it possible to export an orgmode headline to orgmode format?
2021-11-24T20:19:41.207
# Question Title: Is it possible to export an orgmode headline to orgmode format? I keep notes in orgmode and a GitHub repository can display formatted orgmode. I currently copy a headline to a new orgmode file to 'export' my text for publication on GitHub. However, this differs from exporting to other formats in at least two important aspects: 1. The outermost headline is often a secondary headline in the 'export'; 2. The :(no)export: tags are not respected, and I need to trace them manually and edit the file. Hence my question: is it possible to export orgmode to orgmode? I'm hoping for a solution not involving pandoc. # Answer > 3 votes Yes, you can export to org. This is described in the org manual chapter on exporting. You will need to enable the org export backend, via `M-x customize-variable org-export-backends`. Tick the box for `org` and save your settings. --- Tags: org-mode, org-export ---
thread-69467
https://emacs.stackexchange.com/questions/69467
Leaving only one space between words within a paragraph
2021-11-24T22:20:00.667
# Question Title: Leaving only one space between words within a paragraph I have read https://www.emacswiki.org/emacs/DeletingWhitespace but couldn't find a way to select a paragraph and remove extra white spaces. For instance: > asd asdasd asdasd asdasdasd asdasda asdasdasdasd asdasdasdasdasdasd asdasd asdasd asdasdasd asdasda asdasdasdasd asdasdasdasdasdasd asdasd asdasd asdasdasd asdasda asdasdasdasd asdasdasdasdasdasd asdasd asdasd asdasdasd asdasda asdasdasdasd asdasdasdasdasdasd asdasd asdasd asdasdasd asdasda asdasdasdasd asdasdasdasdasd I'd like to be able to select this chunk and apply a function to leave just one white space between words. Thanks! # Answer > 1 votes `M-x fill-paragraph` will reformat the selected paragraph such that there is only a single space between each word. It will also 'fill' the paragraph, which means inserting line-breaks in order to keep each line shorter than `fill-column` characters long. If you don't want your lines broken like this, you could set the variable `fill-column` to a large value (i.e., 10000). --- Tags: whitespace ---
thread-14399
https://emacs.stackexchange.com/questions/14399
Highlight current line and column
2015-08-01T19:19:44.513
# Question Title: Highlight current line and column Is there a solution to highlight current line and column where the cursor is now? I tried this plugin, but then emacs motion are lagging like hell. I was able to highlight the line ``` (global-hl-line-mode 1) ``` # Answer > 0 votes Nowadays you can give `xhair.el` package a try: > This package simultaneously applies vline-mode and hl-line-mode, with tweaks, to present POINT in highlighted cross-hairs, reporting the value of POINT as a message in the echo area. --- Tags: cursor, highlighting ---
thread-17480
https://emacs.stackexchange.com/questions/17480
Move org-mode subtree to another subtree using arrows
2015-10-18T18:32:23.463
# Question Title: Move org-mode subtree to another subtree using arrows With this tree structure: ``` * A ** A.1 ** A.2 ** A.3 a3a3a3a3a3a3a3 * B * C ** C.1 *** C.1.1 *** C.1.2 *** C.1.3 ** C.2 ** C.3 ``` … I can move `C.1` (with its children) up and down with `M-↑` and `M-↓`. Easy. If I use `M-S-↑` and `M-S-↓`, only the `C.1` node is moved, without its children. Easy, too, however the Manual claims in http://orgmode.org/manual/Structure-editing.html: > `M-S-<up>` `(org-move-subtree-up)` > > Move subtree up (swap with previous subtree of same level). > > `M-S-<down>` `(org-move-subtree-down)` > > Move subtree down (swap with next subtree of same level). … so, really, it should be the other way round. Nevermind, though. Also, using `M-S-↑↓`, the `C.1` node can be moved out of its parent, `C`. When this happens, the `C.1` node *always keeps* its level (`**` in this case), no matter where it ends up. Now, what I want to achieve is to move *the whole* `C.1` subtree, the whole branch with all the children, similarly, *out* of `C`, while keeping its `**` level. This could be done with `org-refile` or killing the subtree `C-c C-x C-w` and yanking it at some new point, however, nothing beats the experience (especially when I’ve got to move hundreds of such trees after importing my notes from Wunderlist). <sub>Using GNU Emacs 25.0.50.1 and Org-mode version 8.3.2 (8.3.2-10-g00dacd-elpa).</sub> # Answer # Try This Using arrow keys to edit a nested tree structure can be confusing but is worth learning. 1. Place the cursor on `C.1` line. > **Note:** The cursor will remain on `C.1` line unless otherwise noted. ``` * A ** A.1 ** A.2 ** A.3 a3a3a3a3a3a3a3 * B * C ** C.1 *** C.1.1 *** C.1.2 *** C.1.3 ** C.2 ** C.3 ``` 2. Move `C.1` down to bottom of `C` with by typing `M-↓` repeatedly to preserve `C.2` and `C.3` branches. Outline should look like: ``` * A ** A.1 ** A.2 ** A.3 a3a3a3a3a3a3a3 * B * C ** C.2 ** C.3 ** C.1 *** C.1.1 *** C.1.2 *** C.1.3 ``` 3. Outdent entire `C.1` subtree by typing `M-S-←`. Outline should look like: ``` * A ** A.1 ** A.2 ** A.3 a3a3a3a3a3a3a3 * B * C ** C.2 ** C.3 * C.1 ** C.1.1 ** C.1.2 ** C.1.3 ``` 4. Move `C.1` subtree above `C` subtree by typing `M-↑` Outline should look like: ``` * A ** A.1 ** A.2 ** A.3 a3a3a3a3a3a3a3 * B * C.1 ** C.1.1 ** C.1.2 ** C.1.3 * C ** C.2 ** C.3 ``` 5. Indent `C.1` subtree under another subtree, e.g. `B`, by typing `M-S-→` Outline should look like: ``` * A ** A.1 ** A.2 ** A.3 a3a3a3a3a3a3a3 * B ** C.1 *** C.1.1 *** C.1.2 *** C.1.3 * C ** C.2 ** C.3 ``` I'll add some additional tips and examples to my answer soon. **Tested using** > `GNU Emacs 24.4.1 (x86_64-apple-darwin14.0.0, NS apple-appkit-1343.14)` > > `org-version: 8.3.1` > 3 votes # Answer I used `org-cut-subtree` and `org-yank` to accomplish this. `GNU Emacs 27.1` `Org mode version 9.3` > 1 votes --- Tags: org-mode ---
thread-69478
https://emacs.stackexchange.com/questions/69478
How to replace one face with another for propertized text?
2021-11-25T05:33:37.817
# Question Title: How to replace one face with another for propertized text? Text with properties can have faces assigned, how can one face be replaced with another? An example use case for this is highlighting some text or it's background. Seeing as Emacs doesn't have the ability to alpha-overlay colors over of existing text, something similar could be achieved by blending colors of existing faces. Given some propertized text extracted from a buffer (with `buffer-substring`for example), it should be possible inspect the face properties and swap faces for alternative versions (which could be generated as needed). # Answer > 1 votes This is a utility function to replace faces using an `assosiation-list`, This example function only works when faces are referenced as atoms and should be expanded for other cases for full support. ``` (defun text-property-face-replace (text face-replace-alist) "Replace faces in TEXT using FACE-REPLACE-ALIST." (let ((pos-beg 0) (pos-end (length text))) (while (< pos-beg pos-end) (let ((text-props (text-properties-at pos-beg text))) (let ((prop-iter (memq 'face text-props))) (when prop-iter (let ((value-src (car (cdr prop-iter)))) (let ((value-dst (cond ((listp value-src) nil) ;; TODO: support `plists' and other complex cases. (t (assq value-src face-replace-alist))))) (when value-dst (setcdr prop-iter (cons (cdr value-dst) (cdr (cdr prop-iter)))))))))) (setq pos-beg (next-property-change pos-beg text pos-end))))) ``` Example use: ``` (defvar text-replace-table '((font-lock-doc-face . font-lock-warning-face) (font-lock-comment-face . font-lock-warning-face) (font-lock-comment-delimiter-face . font-lock-warning-face) (font-lock-constant-face . font-lock-warning-face))) (defun text-replace-example () "Show replaced face for the current line." (interactive) (let ((line (buffer-substring (line-beginning-position) (line-end-position)))) (message "Replaced text: %s" (text-property-face-replace line text-replace-table)))) ``` --- Tags: font-lock, text-properties ---
thread-69418
https://emacs.stackexchange.com/questions/69418
Display relative dates in org-mode property drawers
2021-11-21T11:32:00.383
# Question Title: Display relative dates in org-mode property drawers In org-mode documents, I very often add drawer properties to hyperlinks. To illustrate, here is an example with various data attached to a GitHub repository link: ``` * https://github.com/caddyserver/caddy :PROPERTIES: :description: Fast, multi-platform web server with automatic HTTPS :stars: 35252 :open-issues: 96 :language: Go :created-at: 2015-01-13T19:45:03Z :updated-at: 2021-11-21T10:37:08Z :last-commit-at: 2021-11-16T20:08:22Z :fetched-at: 2021-11-21T11:43:57Z :END: ``` I would like to keep the data stored on disk this way, but have a way to (auto)toggle the display of the various dates in a relative fashion. To disambiguate what I mean by "relative", here is a more concrete example: ``` * https://github.com/caddyserver/caddy :PROPERTIES: :description: Fast, multi-platform web server with automatic HTTPS :stars: 35252 :open-issues: 96 :language: Go :created-at: 6 years and 10 months ago :updated-at: 6 hours ago :last-commit-at: 5 days ago :fetched-at: 7 hours ago :END: ``` What could be the approach to tackle this feature? Does org-mode provide a hook when a property drawer is opened? If so, should the invoked function use some kind of overlays to modify only the content of the date values in the drawer? # Answer The command `org+-dateprop` defined in the following Elisp code does what you want. It puts overlays with a `display` property on the absolute dates that shows the relative dates instead. This has the advantage that the buffer contents is not modified by the function. But, it may be a disadvantage that dates are not exported as shown but as absolute dates. You can use `org+-dateprop` to update the time stamps after you have modified the buffer. An alternative approach would be to define a new minor-mode that places the display text property by `font-lock`. If the minor mode is active the dates would be shown as relative dates as soon as they match the regexp for a proper date. But, this can also be a bit disturbing. So I stuck to the command `org+-dateprop`. Addressing your questions: 1. Question: **What could be the approach to tackle this feature?** Answer: Orgmode provides custom properties that can be hidden by `org-toggle-custom-properties-visibility`. One can use that function as an example. Instead of the `invisible` text property you can use the `display` property to show the absolute time entries as relative time entries without modifying the actual text. 2. Question: **Does org-mode provide a hook when a property drawer is opened?** Answer: This question is not so much related to the actual problem. But, no, there is no predefined hook that is called when the visibility of a drawer changes. The visibility of the drawers is changed through `org-flag-drawer`. One could add a hook variable and an advice to that function that calls `run-hooks` or one of its relatives. 3. Question: **If so, should the invoked function use some kind of overlays to modify only the content of the date values in the drawer?** Answer: You are on the right track with the overlays. But, you do not need to change the date values. You can just set the `display` property of the overlays to define what you want to show instead. ``` (require 'cl-lib) (defcustom org+-dateprop-reltime-number-of-items 3 "Number of time items shown for relative time." :type 'number :group 'org) (defun org+-next-property-drawer (&optional limit) "Search for the next property drawer. When a property drawer is found position point behind :PROPERTIES: and return the property-drawer as org-element. Otherwise position point at the end of the buffer and return nil." (let (found drawer) (while (and (setq found (re-search-forward org-drawer-regexp limit 1) found (match-string-no-properties 1)) (or (and (setq drawer (org-element-context)) (null (eq (org-element-type drawer) 'property-drawer))) (string-match found "END")))) (and found drawer))) (defun org+-time-since-string (date) "Return a string representing the time since DATE." (let* ((time-diff (nreverse (seq-subseq (decode-time (time-subtract (current-time) (encode-time date))) 0 6))) (cnt 0)) (setf (car time-diff) (- (car time-diff) 1970)) (mapconcat #'identity (cl-loop for cnt from 1 upto org+-dateprop-reltime-number-of-items for val in time-diff for time-str in '("year" "month" "day" "hour" "minute" "second") unless (= val 0) collect (format "%d %s%s" val time-str (if (> val 1) "s" "")) ) " "))) (defvar-local org+-dateprop--overlays nil "List of overlays used for custom properties.") (defun org+-dateprop-properties-re (properties) "Return regular expression corresponding to `org+-dateprop-properties'." (org-re-property (regexp-opt properties) t)) (defvar org+-dateprop--properties-re (org+-dateprop-properties-re org+-dateprop-properties) "Regular expression matching the properties listed in `org+-dateprop-properties'. You should not set this regexp diretly but through customization of `org+-dateprop-properties'.") (defun org+-dateprop (&optional absolute) "Toggle display of ABSOLUTE or relative time of properties in `org-dateprop-properties'." (interactive "P") (if org+-dateprop--overlays (progn (mapc #'delete-overlay org+-dateprop--overlays) (setq org+-dateprop--overlays nil)) (unless absolute (org-with-wide-buffer (goto-char (point-min)) (let (drawer-el) (while (setq drawer-el (org+-next-property-drawer)) (let ((drawer-end (org-element-property :contents-end drawer-el))) (while (re-search-forward org+-dateprop--properties-re drawer-end t) ;; See `org-property-re' for the regexp-groups. ;; Group 3 is PROPVAL without surrounding whitespace. (let* ((val-begin (match-beginning 3)) (val-end (match-end 3)) (time (org-parse-time-string (replace-regexp-in-string "[[:alpha:]]" " " (match-string 3)))) (time-diff-string (format "%s ago" (org+-time-since-string time))) (o (make-overlay val-begin val-end))) (overlay-put o 'display time-diff-string) (overlay-put o 'org+-dateprop t) (push o org+-dateprop--overlays)) )))))))) (define-widget 'org+-dateprop-properties-widget 'repeat "Like widget '(repeat string) but also updates `org+-dateprop-properties'." :value-to-external (lambda (widget value) (setq org+-dateprop--properties-re (org+-dateprop-properties-re value)) value) :args '(string)) (defcustom org+-dateprop-properties '("created-at" "updated-at" "last-commit-at" "fetched-at") "Names of properties with dates." :type 'org+-dateprop-properties-widget :group 'org) ``` You can put that code in your init file. > 7 votes --- Tags: org-mode, time-date ---
thread-69481
https://emacs.stackexchange.com/questions/69481
How to set shortcut for `M-" ` in emacs config file?
2021-11-25T09:55:19.610
# Question Title: How to set shortcut for `M-" ` in emacs config file? I need to assign `M-"` as a shortcut to some function. How do I do that? Doing this gives error ``` (define-key some-mode-map (kbd 'M-"') 'somefunction) ``` # Answer You need to use doble-quotes for kbd: ``` (define-key some-mode-map (kbd "M-\"") 'somefunction) ``` > 1 votes --- Tags: key-bindings ---
thread-69484
https://emacs.stackexchange.com/questions/69484
How can I apply code sample inside [] brackets in org-mode
2021-11-25T13:42:38.870
# Question Title: How can I apply code sample inside [] brackets in org-mode In the `markdown-mode` I am able to do following: \[`one`, `two`, `three`, `four`\] But in `org-mode` when I do: \[~one~, ~two~, ~three~, ~four~\] , it printed as it is instead of converting `~varaible~` into code format. How can I pretent this to keep code sample format? Related: How to apply code sample inside a line using org mode # Answer > 1 votes You need to separate the `~` from the square brackets. ``` [ ~one~, ~two~ ] ``` seems to apply the org-code face to `~one~` and `~two~`. You can also use a Zero-width space instead of the space (use `C-x 8 RET 200b` to enter it). --- Tags: org-mode ---
thread-69475
https://emacs.stackexchange.com/questions/69475
Allowed values at #+PROPERTY header line not recognized
2021-11-25T04:46:38.427
# Question Title: Allowed values at #+PROPERTY header line not recognized I'd like to set allowed property values at the top of an org-mode cheatsheet i'm working on. Only two allowed values so far for the `CATEGORY` property. I'm getting the same "Allowed values for this property have not been defined" issue experienced in the issue linked below. ``` #+PROPERTY: CATEGORY Meta Create ... * Org-mode essentials :PROPERTIES: :CATEGORY: Meta :END: ** M-RET - New bullet at the current level :PROPERTIES: :CATEGORY: Create :END: ``` I have followed org-mode Property documentation as recommended by the most similar question. I am running emacs 26.3 with org 9.1.9 on Linux Mint 20. I've tried reloading settings for the current file (C-c C-c) and restarting Emacs to no avail. Is the issue in the syntax of the top line? # Answer > 0 votes The allowed values for a property are specified by defining a specially named property: e.g. for specifying the values for a `CAT` property, you specify the allowed values as the value of the property `CAT_all`: ``` #+PROPERTY: CAT_all Meta Create ``` Don't forget to `C-c C-c` on the property line, to refresh the buffer and inform Org mode about this new property. Then you can use `C-c C-x p`, specify `CAT` as the name of the property and use `TAB` completion to select a value. See the "Property syntax" section of the manual, which you can visit in Emacs with `C-h i g (org)Property syntax`. Note: I used `CAT` for the name of your property because Org mode already has a *special* property called `CATEGORY`: `C-h i g (org)Special properties` will get you to the section that defines all of them. That section says: > The following property names are special and should not be used as keys in the properties drawer. --- Tags: org-mode ---
thread-62286
https://emacs.stackexchange.com/questions/62286
library for code execution for markdown via org-babel
2020-12-15T12:23:20.363
# Question Title: library for code execution for markdown via org-babel Are there any libraries out there that can take the markdown `code fence` block and execute it via org babel? Ie, something like ``` '''js var a = 1 var b = 2 return a + b ''' ``` **Reasoning**: I don't see not too much difference between a `#+BEGIN_SRC .... #+END_SRC` block and a `'''...'''` block. I know that it's ultimately possible to be able to convert back and forth between a markdown file and an org file (via pandoc) but I'd like to have the code execution functionality of org-babel within a markdown file. I'm wondering if anyone has extracted that functionality from org-babel and if not, maybe a guide to how to go about it. # Answer \[More of a comment than an answer, but too long anyway - if you clarify your question, I will either edit the answer or delete it altogether, depending on wht exactly you want.\] Yes, if you translate it to the form that Org babel wants: ``` #+begin_src js var a = 1 var b = 2 return a + b #+end_src #+RESULTS: : 3 ``` and you load the `ob-js` library. I suspect you want something else, but it is not clear to me what exactly that is from your question. Maybe you can clarify your question and specify what the Org mode file should contain and then what you'd like to accomplish. EDIT (in response to the added information in the question): The transformations that `pandoc` does between Org mode files and Markdown files are purely textual. You need an underlying execution engine in order to **execute** code blocks: that is provided by Org babel *and Emacs* for Org mode files, but there is nothing similar for Markdown files (even if you open them in Emacs). It is conceivable that an MD babel implementation could be made (e.g. code blocks are used in both cases for pretty-printing purposes, fontification, coloring etc.) but the details are sufficiently different to make it a non-trivial pursuit (e.g. there is a whole slew of header arguments that can be passed to an Org mode code block: there is nothing like that in any Markdown syntax that I know of), and although you might be able to extend MD syntax to cover some or all of what MD code blocks are missing, then you'd have to port Org babel to "MD babel" to provide the execution engine (and only in Emacs, remember). So, I think the answer to your question is: No, there is nothing like that currently. As for how to do it in the above context (while editing the MD file in Emacs), I think the simplest thing is to keep the Org mode syntax for code blocks as is. The MD code block would be: > \`\`\` js \<header-args\> > > code > > \`\`\` where everything after the opening triple-backtick and before the closing one is just an Org mode code block without the `#+BEGIN_SRC` and `#+END_SRC` markers. The "MD babel engine" would just replace the triple backticks with `#+BEGIN_SRC ... #+END_SRC`, write the code block to a temporary file `foo.org` and then open the file in Org mode and run the code block using Org babel, and then copy the `#+RESULTS` block and paste it into the MD file after the code block.That should not be too difficult, but the major mode used for the MD file would have to be taught how to deal with the extra stuff (e.g. the header args and the `#+RESULTS:` block) if it cared. But then the question becomes: why do all that in MD mode? Why not do the whole thing in Org mode and export the file to MD at the end and be done with it? > 3 votes # Answer I am interested in this functionality and believe we are looking for the same thing. I didn't find a ready-made one so here's a quick-and-dirty take. It only supports `sh` now, and requires `cl` and magnar's `s` <pre><code>(defun markdown-eval-current-code-block () (interactive) (save-excursion (forward-paragraph) (let ((start (progn (backward-paragraph) (point)))) (forward-paragraph) (let ((region-string (s-trim (buffer-substring start (point))))) (when (and (s-starts-with? "```" region-string) (s-ends-with? "\n```" region-string)) (let* ((split-1 (s-split-up-to "\n" (substring region-string 0 (- (length region-string) 4)) 1)) (language (substring (car split-1) 3)) (code-body (cadr split-1))) (cond ((string= language "sh") (insert (format "```\n%s\n```" (org-babel-sh-evaluate nil ;; session code-body ;; params '((:colname-names) (:rowname-names) (:result-params . ("replace" "output")) (:result-type . "output") (:exports . code) (:session . none) (:cache . no) (:noweb . no) (:hlines . no) (:tangle . no)))))) (t (progn (message "I can only process sh blocks now. Improve me please.")))))))))) </code></pre> Assuming your cursor is inside a code fence, it * searches upwards for the start of the current paragraph * downwards for the end of the current paragraph * checks if it's a code fence * detects if it understands the code fence's language marker (i.e. "sh") * passes the code body into `org-babel-sh-evaluate` and spits the result into a new fenced block to improve this: * needs better inside-code-fence detection * better language detection and code body extraction * integrate the language marker directly with the enabled org-babel-\*-evaulate dynamically loaded functions Also note the `params` association list (`colname-names` etc) is almost certainly a bad one as it was captured from playing with `org-babel-sh-evaluate`. The alist cons values (like code, none, no) should probably be strings, but for this example they don't matter. There is one association `(:results . replace output)` which is removed here, because *with* it the function errors on call, possibly due to lacking a real org-mode context. > 2 votes --- Tags: org-mode, org-babel ---
thread-62181
https://emacs.stackexchange.com/questions/62181
Configure x-export-frames to take svg screenshots (Mac/OSX)
2020-12-09T06:59:12.547
# Question Title: Configure x-export-frames to take svg screenshots (Mac/OSX) Using this reddit post as inspiration, I am trying to create a `screenshot-svg` command using the following config: ``` (defun screenshot-svg () "Save a screenshot of the current frame as an SVG image. Saves to a temp file and puts the filename in the kill ring." (interactive) (let* ((filename (make-temp-file "Emacs" nil ".svg")) (data (x-export-frames nil 'svg))) (with-temp-file filename (insert data)) (kill-new filename) (message filename))) ``` However, when I try to run the `screenshot-svg` command, I get the message `let*: Symbol’s function definition is void: x-export-frames`, and nothing seems to happen. How do I check if `x-export-frames` is available on my build? What do I need to do to get this working? Are there any other ways to get svg screenshots on emacs? **EDIT:** I am using OSX, so I am also wondering if Cairo, or something similar is available for OSX? # Answer > 1 votes As of 2021-11-25 I only have sad news here: While cairo works on macOS via `brew install cairo` just fine, I didn't find a way to make any of the Emacs builds aware of it. Tried `emacs-plus@28` and `emacs-head@28` and the `build-emacs-for-macos` script, but even with X11 support, the `x-export-frames` function isn't available. Other `x-` prefixed functions exist, but no luck with the SVG saving thus far. --- Tags: init-file, osx ---
thread-69415
https://emacs.stackexchange.com/questions/69415
How can I exclude characters from being interpreted as emphasis-markers in Org-Mode?
2021-11-20T22:12:00.087
# Question Title: How can I exclude characters from being interpreted as emphasis-markers in Org-Mode? Is it possible to exclude the tilde `~` from being interpreted as emphasis-marker in Org-Mode in general? Meaning not being escaped but being normal interpreted as simple Text? Emphasis-and-Monospace, Worg Edit: The following is now set in my `init.el` via `customize-variable`, but doesn't have any effect at all... Of course, I restarted org-mode. The target is to replace `~` with backtics for code-blocks. ``` '(org-emphasis-alist (quote (("*" bold) ("/" italic) ("_" underline) ("=" org-verbatim verbatim) ("`" org-code verbatim) ("+" (:strike-through t))))) ``` # Answer `org-emphasis-alist` wrongly suggests that you could change the emphasis markers. No, that is not the case. It rather gives you the possibility to change the faces for the emphasis markers rigidly given by the syntax specification of org-mode. Nevertheless, the code below makes some functions of Org-Mode Version 9.2.3 somewhat more general, such that it accepts modifications of the emphasis markers. The modifications are marked by comments starting with `;; Tobias:`. Note, that I used the unspecified third element of the entries of `org-emphasis-alist` to identify `verbatim` markers. ``` (require 'cl-lib) (require 'org) (defun org+-emphasis-chars () "Return a list (EMPH VERB) of strings of markers. EMPH is a string containing all marker chars for non-verbatim emphasis. VERB is a string containing all marker chars for verbatim emphasis." (let (emph verb) (cl-loop for el in org-emphasis-alist if (eq (nth 2 el) 'verbatim) do (push (car el) verb) else do (push (car el) emph)) (list (mapconcat #'identity emph "") (mapconcat #'identity verb "")))) (defvar org+-emph-chars "" "String of characters working as emphasis markers.") (defvar org+-verb-chars "" "String of characters working as verbatim markers.") ;; Modified version of `org-set-emph-re': (defun org+-set-emph-re (var val) "Set variable and compute the emphasis regular expression." (set var val) (when (and (boundp 'org-emphasis-alist) (boundp 'org-emphasis-regexp-components) org-emphasis-alist org-emphasis-regexp-components) (pcase-let* ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components) (body (if (<= nl 0) body (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl))) (template (format (concat "\\([%s]\\|^\\)" ;before markers "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)" "\\([%s]\\|$\\)") ;after markers pre border border body border post))) ;; Tobias: Added: (cl-multiple-value-setq (org+-emph-chars org+-verb-chars) (org+-emphasis-chars)) (setq org-emph-re (format template org+-emph-chars)) ;; Tobias: Replaced literal "*+/_" (setq org-verbatim-re (format template org+-verb-chars))))) ;; Tobias: Replaced literal "~=" (advice-add 'org-set-emph-re :override #'org+-set-emph-re) (org-set-emph-re 'org-emphasis-alist org-emphasis-alist) ;; Modified version of `org-do-emphasis-faces': (defun org+-do-emphasis-faces (limit) "Run through the buffer and emphasize strings." (let ((quick-re (format "\\([%s]\\|^\\)\\([%s%s]\\)" ;; Tobias: modified format string (car org-emphasis-regexp-components) org+-emph-chars ;; Tobias: added org+-verb-chars))) ;; Tobias: added (catch :exit (while (re-search-forward quick-re limit t) (let* ((marker (match-string 2)) (verbatim? (seq-contains org+-verb-chars (string-to-char marker)))) ;; Tobias: replaced (member ... '("=" "~")) (when (save-excursion (goto-char (match-beginning 0)) (and ;; Do not match table hlines. (not (and (equal marker "+") (org-match-line "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$"))) ;; Do not match headline stars. Do not consider ;; stars of a headline as closing marker for bold ;; markup either. (not (and (equal marker "*") (save-excursion (forward-char) (skip-chars-backward "*") (looking-at-p org-outline-regexp-bol)))) ;; Match full emphasis markup regexp. (looking-at (if verbatim? org-verbatim-re org-emph-re)) ;; Do not span over paragraph boundaries. (not (string-match-p org-element-paragraph-separate (match-string 2))) ;; Do not span over cells in table rows. (not (and (save-match-data (org-match-line "[ \t]*|")) (string-match-p "|" (match-string 4)))))) (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))) (font-lock-prepend-text-property (match-beginning 2) (match-end 2) 'face face) (when verbatim? (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0)) (remove-text-properties (match-beginning 2) (match-end 2) '(display t invisible t intangible t))) (add-text-properties (match-beginning 2) (match-end 2) '(font-lock-multiline t org-emphasis t)) (when org-hide-emphasis-markers (add-text-properties (match-end 4) (match-beginning 5) '(invisible org-link)) (add-text-properties (match-beginning 3) (match-end 3) '(invisible org-link))) (throw :exit t)))))))) (advice-add 'org-do-emphasis-faces :override #'org+-do-emphasis-faces) ``` > 1 votes --- Tags: org-emphasis ---
thread-69476
https://emacs.stackexchange.com/questions/69476
Key-binding shortcut for Tufte html export
2021-11-25T04:49:20.420
# Question Title: Key-binding shortcut for Tufte html export I've perused a few of the org-mode html-export key-binding shortcuts, i.e., ways to just have one key do, e.g., the entire long-winded `C-c C-e h o`. Unfortunately, there doesn't seem to be one fell swoop function like `org-html-export-as-html` to get the whole job done with what I'm using, namely, ox-tufte. I've located the (probably) germane section ``` (org-export-define-derived-backend 'tufte-html 'html :menu-entry '(?T "Export to Tufte-HTML" ((?T "To temporary buffer" (lambda (a s v b) (org-tufte-export-to-buffer a s v))) (?t "To file" (lambda (a s v b) (org-tufte-export-to-file a s v))) (?o "To file and open" (lambda (a s v b) (if a (org-tufte-export-to-file t s v) (org-open-file (org-tufte-export-to-file nil s v))))))) :translate-alist '((footnote-reference . org-tufte-footnote-reference) (src-block . org-tufte-src-block) (link . org-tufte-maybe-margin-note-link) (quote-block . org-tufte-quote-block) (verse-block . org-tufte-verse-block))) ``` but I'm not sure how to put together a custom function to accomplish the key shortcut of `C-c C-e T t` to F9. Any suggestions appreciated. Any suggested tutorial to understand what the above function is doing would also be appreciated. # Answer If you don't care about setting the `async`, `scope`, or `visible-only` options, then you can do something like this: ``` (defun my/org-tufte-export-direct-to-file () (interactive) (org-tufte-export-to-file nil nil nil)) (define-key org-mode-map (kbd "<f9>") #'my/org-tufte-export-direct-to-file) ``` i.e. call the function that the `t` key calls when you are in the export dispatcher. `C-c C-e T t` says invoke the export dispatcher (`C-c C-e`) which brings up the menu where you can set some options, but principally where you can select which exporter to use. The `T` then selects the Tufte exporter (I presume - I don't have it installed) and the `t` dispatches to `org-tufte-export-to-file` as shown by the snippet of code you posted. Another possibility is to define a keyboard macro, save it and assign it to a key. See the "Keyboard Macros" chapter in the Emacs manual (`C-h i g(emacs)Keyboard macros`). > 1 votes --- Tags: org-mode, org-export, html ---
thread-51091
https://emacs.stackexchange.com/questions/51091
Save buffer immediately after org-archive-location
2019-06-18T09:29:07.343
# Question Title: Save buffer immediately after org-archive-location # Question How do I immediately save the `.org` buffer created by `org-archive-location`? # Context and what I've tried so far Current `.emacs` settings: ``` FILE: .emacs (setq org-archive-location (concat "~/Documents/Reference/org/archive/" (format-time-string "%Y-%m") ".org::")) ``` Consider ``` FILE: main2.org * Done item ``` Calling `org-archive-location` with `C-c $` results in the following buffers ``` FILE: *Messages* Subtree archived in file: ~/Documents/Reference/org/archive/2019-06.org ``` and ``` FILE: 2019-06.org Archived entries from file /Users/janmeppe/Documents/Reference/org/main2.org * Done item :PROPERTIES: :ARCHIVE_TIME: 2019-06-18 Tue 11:26 :ARCHIVE_FILE: ~/Documents/Reference/org/main2.org :ARCHIVE_CATEGORY: main2 :END: ``` Now the problem is this, I have to manually save the buffer for it to appear in the finder, how do I automatically save this buffer after calling `org-archive-location`? I tried adding the following but it this help ``` (advice-add 'org-archive-location :after #'org-save-all-org-buffers) ``` # Answer > 5 votes `org-archive-location` is *not* a function that can be modified with `advice`. It is a variable. Perhaps the O.P. meant to say `org-archive-subtree`? Type `C-h k` (aka `M-x describe-key`) and then the keyboard shortcut to see what function is triggered .... ``` (advice-add 'org-archive-subtree :after #'org-save-all-org-buffers) ``` --- I would prefer to save only the buffer containing the archived subtree *and* the buffer from which it was archived/removed, but that would take some additional digging into the code and doing some testing ... Perhaps another forum participant would like to write up an alternate answer that uses a scalpel instead of the `org-save-all-org-buffers` (which is a sledgehammer). # Answer > 0 votes I found a workaround with the same functionality but it works on calling `save-buffer` which I call often with `:w` in evil. I'm not marking this as the correct answer because it does not answer the question (i.e. how to save immediately after `org-archive-location`) but I'd like to share it because it results in the same functionality. ``` (advice-add 'save-buffer :after #'org-save-all-org-buffers) ``` # Answer > 0 votes Since at least Org 9.4 there's a variable which controls when to save the archive file: `org-archive-subtree-save-file-p`. From the docs: ``` Conditionally save the archive file after archiving a subtree. This variable can be any of the following symbols: t saves in all cases. from-org prevents saving from an agenda-view. from-agenda saves only when the archive is initiated from an agenda-view. nil prevents saving in all cases. Note that, regardless of this value, the archive buffer is never saved when archiving into a location in the current buffer. ``` --- Tags: org-mode ---
thread-69502
https://emacs.stackexchange.com/questions/69502
How do I mark certain "elisp:" type links as safe?
2021-11-26T08:30:35.347
# Question Title: How do I mark certain "elisp:" type links as safe? I have several `[[elisp:org-todo-list][todo list]]` links in my Org documents. When I use `C-c C-o` (`org-open-at-point`), Org mode asks me whether I really want to open that link. While this is good practice in general, I *know* that `org-todo-list` will never break anything in my documents or workflow. Can I tell Org to just open any link to its todo list without asking for confirmation? # Answer > 4 votes > Can I tell org mode to just open the link without asking for confirmation? Yes. Org provides the customizable variable `org-link-elisp-skip-confirm-regexp`. Set it accordingly: ``` (setq org-link-elisp-skip-confirm-regexp "\\`org-todo-list\\'") ``` You really want to include the begin-of-string (`\`` ) and end-of-string (`\'`) matchers to catch links like `[[elisp:(remove-all-files); org-todo-list]][Evil link]]`. If you use more commands, add them to the regular expression as an alternative via `|`: ``` (setq org-link-elisp-skip-confirm-regexp "\\`\\(org-todo-list\\|org-agenda-list\\)\\'") ``` If you have many commands, you probably want to use a list for that instead: ``` (let ((safe-commands '(org-agenda-list org-clock-goto org-goto-calendar org-tags-view org-todo-list))) (setq org-link-elisp-skip-confirm-regexp (concat "\\`\\(" (mapconcat #'symbol-name safe-commands "\\|") "\\)\\'"))) ``` For more information, see `org-link-elisp-skip-confirm-regexp`'s documentation. --- Tags: org-mode ---
thread-69490
https://emacs.stackexchange.com/questions/69490
reftex does not recognize references even though default bibliography file is defined
2021-11-25T16:19:35.900
# Question Title: reftex does not recognize references even though default bibliography file is defined `reftex-citep` does not suggest any possible completions, even though the variable `reftex-default-bibliography` is set to the correct bibtex file. What else do I need to do to get reftex to detect the bibtex entries? Note: the same happens with the AuCTeX cite macro. # Answer The doc for the `reftex-default-bibliography` variable says: > List of BibTeX database files which should be used if none are specified. When ‘reftex-citation’ is called from a document which has neither a ‘\bibliography{..}’ statement nor a ‘thebibliography’ environment, RefTeX will scan these files instead. Intended for using ‘reftex-citation’ in non-LaTeX files. The files will be searched along the BIBINPUTS or TEXBIB path. Note that it is supposed to be a *list* of BibTeX database files. If you only have one, try saying ``` (setq reftex-default-bibliography '("/path/to/my/bibtex/file")) ``` EDIT: I downloaded Nelson Beebe's `ACM Computing Surveys` file from http://www.math.utah.edu/pub/tex/bib/compsurv.bib and added it to `reftex-default-bibliography` with: ``` (setq reftex-default-bibliography '("~/lib/bibtex/compsurv.bib")) ``` I put this in a file `minimal.el`. In a brand new session of emacs (started with `emacs -q -l minimal.el foo.tex`), I enabled `reftex` with `M-x reftex-mode`, typed in `Knuth` and did `M-x reftex-citep`: that had `Knuth` filled in as the regexp value, so I just pressed RET. That gave me a `*RefTex Select*` buffer with four references, I did `r SPG` to restrict it to the single reference that contained the string `SPG`, typed `a` and I got this in the `foo.tex` buffer: ``` Knuth\cite{Knuth:1974:SPG} ``` I don't know much about RefTeX, but that seems to be all correct and working. If that's not what you did and/or expected, then maybe you can edit your question and add the exact behavior you expect and the exact behavior you get. > 2 votes --- Tags: latex, auctex, reftex-mode ---
thread-69469
https://emacs.stackexchange.com/questions/69469
How to view URL of the links in org-mode
2021-11-24T23:11:55.640
# Question Title: How to view URL of the links in org-mode I am using `[[LINK][DESCRIPTION]]` format to define hyperlinks in org-mode. > Org recognizes plain URIs, possibly wrapped within angle brackets, and activate them as clickable links. The general link format, however, looks like this: > > `[[LINK][DESCRIPTION]]` When I write `[[LINK][DESCRIPTION]]` it automatically becomes `DESCRIPTION`. Would it be possible keep it as its expanded version where I can see the URL as well in the buffer? # Answer The operative variable is `org-link-descriptive` (it was called `org-descriptive-links` in earlier versions of Org mode). Its doc string (`C-h v org-link-descriptive` says: > Non-nil means Org displays descriptive links. > > E.g. \[\[https://orgmode.org\]\[Org website\]\] is be displayed as "Org Website", hiding the link itself and just displaying its description. When set to nil, Org displays the full links literally. > > You can interactively set the value of this variable by calling ‘org-toggle-link-display’ or from the "Org \> Hyperlinks" menu. That simultaneously answers the question in the question and the additional question in a comment about using a function to toggle it. The only additional thing to do is to add a keybinding: ``` (define-key org-mode-map (kbd "C-c z") #'org-toggle-link-display) ``` > 2 votes --- Tags: org-mode ---
thread-69509
https://emacs.stackexchange.com/questions/69509
Why are `defvars` in my macro ignored?
2021-11-26T15:11:38.253
# Question Title: Why are `defvars` in my macro ignored? I want to use a macro to define variables. However, evaluating the macro does not define these vars. I seem to be missing something, but I can't find it. Here's the code: ``` (defmacro delve--build-cmp (name desc sort-fn-asc sort-fn-desc slot-fn &optional map-fn) "Define two comperator functions based on NAME." (declare (indent 1)) (let* ((name-as-string (format "%s" name)) (name-asc (make-symbol (concat name-as-string "-asc"))) (name-desc (make-symbol (concat name-as-string "-desc"))) (desc-asc (concat desc ", ascending order.")) (desc-desc (concat desc ", descending order."))) `(progn (defvar ,name-asc (delve-cmp--create :comp (delve--cmp-fn ,sort-fn-asc ,slot-fn ,map-fn) :desc ,desc-asc) ,desc-asc) (defvar ,name-desc (delve-cmp--create :comp (delve--cmp-fn ,sort-fn-desc ,slot-fn ,map-fn) :desc ,desc-desc) ,desc-desc)))) ``` The function `delve-cmp--create` is a function which defines a structure object, so nothing special there. All I want is to define these two objects at the time of the evaluation of the macro. I thought about using functions, but I like it that we can use unevaluated symbol names in macros which spares us the need to quote the name. In the end, I would like to have some kind of `defun`-like syntax. So my question is: What is wrong with this code, why isn't the defvar eval'ed when I eval a call to that macro? # Answer > 3 votes The defvars *are* evaluated -- your *uninterned* symbols will have the values you've assigned. Change `make-symbol` to `intern`. --- Tags: elisp-macros, symbols, defvar, macroexpansion ---
thread-69513
https://emacs.stackexchange.com/questions/69513
How can I apply function `max` to a list of numbers?
2021-11-26T20:34:17.613
# Question Title: How can I apply function `max` to a list of numbers? I want to find the max element in a list of numbers. ``` (setq l (list 1 2 3 4 5)) ``` What is an easy way to call the `max` function on `l`? So far I have this but this seems convoluted: ``` (eval `(max ,@l)) ``` It seems like there should be an easier way. No? # Answer Function `apply` is what you're looking for: ``` (apply #'max l) ``` > 3 votes --- Tags: list, arguments, apply ---
thread-69518
https://emacs.stackexchange.com/questions/69518
How can I prevent Orgmode from opening links to `*.jot` files using GNU `less`
2021-11-27T09:53:05.647
# Question Title: How can I prevent Orgmode from opening links to `*.jot` files using GNU `less` When I open a link in Emacs Orgmode to a `*.txt` or `*.org` file, the files are opened in a new Emacs buffer. However, I have a self-created set of plain-text `*.jot` files. If I open an otherwise identical link to such a file (e.g. by renaming `file.txt` to `file.jot` and updating the link), emacs "opens" it with GNU `less`, which means nothing happens. I cannot find any mention of `jot` or `less` in my emacs `init.el` or KDE/Plasma file associations (I just assigned `*.jot` to Emacs in my System settings, even though `xdg-open file.jot` already opened it with Emacs). When I try this with `emacs -q`, I still get the same result. Is there anything special about `*.jot` files for emacs, should I add an Emacs setting to force the desired behaviour, or should I be looking elsewhere? # Answer Try this: ``` (push '("\\.jot\\'" . emacs) org-file-apps) ``` Org sometimes looks in odd system places (mailcap?) for file associations. > 1 votes --- Tags: org-mode, org-link ---
thread-69485
https://emacs.stackexchange.com/questions/69485
Org ref: (wrong-type-argument stringp nil)
2021-11-25T13:55:47.773
# Question Title: Org ref: (wrong-type-argument stringp nil) I have just installed Emacs 27.9 on a new Mac running Monterey 12.0.1 (using https://emacsformacosx.com) I then installed org-ref by putting the following lines in my .emacs: ``` (add-to-list 'load-path "~/.emacs.d/") (load "org-ref-melpa.el") ``` For me the file "org-ref-melpa.el" is set up as follows: ``` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; SETUP FOR ORG-REF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (setq user-emacs-directory "~/EMACS/org-ref/sandbox") (require 'cl) (require 'package) (setq package-archives '(("org" . "http://orgmode.org/elpa/") ("gnu" . "http://elpa.gnu.org/packages/") ("melpa" . "http://melpa.org/packages/"))) (package-initialize) (let ((packages (list 'org-plus-contrib 'org-ref))) ; refresh if needed. (unless (cl-every #'package-installed-p packages) (package-refresh-contents)) (dolist (package packages) (unless (package-installed-p package) (package-install package)))) ;; wrap lines (global-visual-line-mode 1) ;; setup org-ref (setq org-ref-bibliography-notes "~/EMACS/org-ref/notes.org" org-ref-default-bibliography '("~/EMACS/org-ref/references.bib") org-ref-pdf-directory "~/EMACS/org-ref/bibtex-pdfs/") (unless (file-exists-p org-ref-pdf-directory) (make-directory org-ref-pdf-directory t)) ;; Some org-mode customization (setq org-src-fontify-natively t org-confirm-babel-evaluate nil org-src-preserve-indentation t) (org-babel-do-load-languages 'org-babel-load-languages '((python . t))) (setq org-latex-pdf-process '("pdflatex -interaction nonstopmode -output-directory %o %f" "bibtex %b" "pdflatex -interaction nonstopmode -output-directory %o %f" "pdflatex -interaction nonstopmode -output-directory %o %f")) (setq bibtex-autokey-year-length 4 bibtex-autokey-name-year-separator "-" bibtex-autokey-year-title-separator "-" bibtex-autokey-titleword-separator "-" bibtex-autokey-titlewords 2 bibtex-autokey-titlewords-stretch 1 bibtex-autokey-titleword-length 5) (require 'dash) (setq org-latex-default-packages-alist (-remove-item '("" "hyperref" nil) org-latex-default-packages-alist)) ;; Append new packages (add-to-list 'org-latex-default-packages-alist '("" "natbib" "") t) (add-to-list 'org-latex-default-packages-alist '("linktocpage,pdfstartview=FitH,colorlinks, linkcolor=blue,anchorcolor=blue, citecolor=blue,filecolor=blue,menucolor=blue,urlcolor=blue" "hyperref" nil) t) ;; some requires for basic org-ref usage (require 'org-ref) (require 'org-ref-pdf) (require 'org-ref-url-utils) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ``` That is its the same as the version of the file found on: https://kitchingroup.cheme.cmu.edu/blog/2015/12/22/org-ref-is-on-Melpa/ with minimal changes. Now when I try to set up a bibliography file by typing for example: bibliography:newref.bib And then click on the link (as explained in the video in Kitchin's introductory video https://www.youtube.com/watch?v=2t925KRBbFc) I get the error: (wrong-type-argument stringp nil) If I use the debugger: (setq debug-on-error t), I get: ``` Debugger entered--Lisp error: (wrong-type-argument stringp nil) file-exists-p(nil) org-ref-get-bibfile-path(nil) org-ref-bibliography*-follow("newref.bib") org-link-open((link (:type "bibliography" :path "newref.bib" :format plain :raw-link "bibliography:newref.bib" :application nil :search-option nil :begin 88 :end 111 :contents-begin nil :contents-end nil :post-blank 0 :parent (paragraph (:begin 88 :end 114 :contents-begin 88 :contents-end 112 :post-blank 2 :post-affiliated 88 :parent nil)))) nil) org-open-at-point() org-open-at-mouse((mouse-2 (#<window 7 on manuscript.org> 97 (68 . 64) 140230978 nil 97 (9 . 4) nil (5 . 8) (7 . 14)))) funcall-interactively(org-open-at-mouse (mouse-2 (#<window 7 on manuscript.org> 97 (68 . 64) 140230978 nil 97 (9 . 4) nil (5 . 8) (7 . 14)))) call-interactively(org-open-at-mouse nil nil) command-execute(org-open-at-mouse) ``` I'm really very new to all things EMACS so if anyone out there can help me with this can you please give instructions that can be understood by a newb! # Answer > 0 votes Here’s the source of the `org-ref-bibliography*-follow` function. It is looking for a text property containing the filename to jump to, but apparently it isn’t finding it; you can see in the stack that it is passing `nil` to the next function along instead of a file name. Perhaps your file is not quite in the right format. The `org-ref` package should have better error handling though. I would file a bug report if I were you. # Answer > 0 votes Turns out I was using a very old version of org-ref, here is the response I got from the above GitHub page: "You are using a very out of date configuration. See https://github.com/jkitchin/org-ref#configuration for an updated setup. See https://www.youtube.com/watch?v=3u6eTSzHT6s&list=PL0sMmOaE\_gs3E0OjExoI7vlCAVygj6S4I&index=11&t=446s for a more recent video. I would start there." Installing the newer version of org-roam now works. --- Tags: org-mode, org-ref ---
thread-69524
https://emacs.stackexchange.com/questions/69524
font-lock not working with my custom face
2021-11-27T14:19:31.520
# Question Title: font-lock not working with my custom face I defined a custom face ``` (defface my-face '((t . (:background "green"))) "text") ``` that I want to use for font-lock syntax highlighting. ``` (defvar my-font-lock-keywords `( ("^\\*.*\\|;.*" . font-lock-comment-face) ("'[^']*'" . font-lock-string-face) ( ,(regexp-opt my-keywords 'symbols) . font-lock-keyword-face) ( ,(regexp-opt my-specials 'symbols) . my-face) (">[0-9A-F]+\\>\\|\\<[0-9]+\\>" . font-lock-constant-face) )) ``` The entire thing works fine if I replace `my-face` with `font-lock-doc-face` or similar, but loading my mode with this definition yields the error message ``` Error during redisplay: (jit-lock-function 1) signaled (void-variable my-face) ``` What is wrong with my face and the font-lock definition? Note that `describe-face` knows `my-face` and correctly shows its defined properties. # Answer The "face" field is evaluted by font-lock. Hence, you need to quote the name of the face: ``` ("^\\*.*\\|;.*" . 'font-lock-comment-face) ``` Note: Some standard faces like `font-lock-keyword-face` have variables with the same name as the face, whose value is the name of the face. This allows you to use those standard faces without a quote. However, this practice is deprecated. Note 2: You can utilise the fact that the field is evaluated, e.g. by mapping a regexp to different faces depending on what is matched. Note 3: Typically, strings and comments are not highlighted using font-lock keywords. Instead, they are highlighted according to the syntax table of the major mode. > 1 votes --- Tags: faces, font-lock ---
thread-63250
https://emacs.stackexchange.com/questions/63250
Fold second-level (all methods) when opening a py-file (with hs-minor-mode)
2021-02-07T21:43:46.600
# Question Title: Fold second-level (all methods) when opening a py-file (with hs-minor-mode) I use `hs-minor-mode` currently. When point is on `class Foo...` a `M-x hs-hide-level` will fold all methods of that class. This is exactly the state I need for all `*.py` files when I open them. Is it possible? When I open a python file all methods of all classes (there could be more then one!) should be folded. `hs-hide-level` was pointed out in that answer. https://emacs.stackexchange.com/a/50144/12999 # Answer Here's a quick idea: ``` (defun my-collapse () (interactive) (when (and (stringp buffer-file-name) (string-match "\\.py\\'" buffer-file-name)) (save-excursion (goto-char (point-min)) (while (re-search-forward "class" (point-max) t) (hs-hide-level 1))))) ``` This checks that the file being visited ends with ".py". It then saves where you are in the buffer before searching for the word "class". At each match, it calls the function to 'collapse' items in that block whose indent level is greater than or equal to 1. This should be all methods, assuming the class is not nested. Your point is returned to where it was prior to the search. To run it on every `.py` file, use a hook: ``` (add-hook 'find-file-hook 'my-collapse) ``` > 1 votes --- Tags: code-folding ---
thread-69529
https://emacs.stackexchange.com/questions/69529
How to automate the test step in "debugging by bisection"?
2021-11-27T17:02:06.290
# Question Title: How to automate the test step in "debugging by bisection"? Sometimes I run into a problem with Emacs that goes away if invoke Emacs with the `--no-init-flag`. In other word, I can deduce that the problem in question is caused by code *somewhere* in my .emacs file. The only way I know to pinpoint what exactly in my (very long and very old) .emacs file is causing the problem is what could be called "debugging by bisection". For those who don't know what I mean by this, I give a more detailed description of this procedure below. For the purpose of this question, however, what matters is that the method entails multiple rounds of 1. CREATE a (trial/experimental) init file for Emacs; 2. START Emacs with the init file from (1); 3. ***TEST*** whether the problem occurs or not; 4. KILL Emacs; 5. REPEAT. The speed and convenience of this procedure depends on how quickly and conveniently I can carry out the TEST step<sup>1</sup>. Very often it happens that the only way I know to carry out this TEST step is to go through a sequence of *interactive* operations (e.g. open a new buffer, enable this or that mode mode, issue this or that command, etc.) My question is this: how can I record in a file `/path/to/test/sequence` the sequence of interactive operations that make up the TEST step, so that I can replay this sequence automatically by including the expression ``` (load "/path/to/test-sequence") ``` at the right place in my init file? Also, could this recorded sequence of operation also include the one to KILL Emacs (step 4)? --- <sup><sup>1</sup> The other steps in the cycle are usually relatively simple and largely independent of the problem I'm debugging. The TEST step, in contrast, depends entirely on the problem being debugged, and can therefore vary greatly in degree of difficulty.</sup> --- <sup> **DEBUGGING MY .emacs FILE "BY BISECTION"** If somehow I already know that the problem I'm debugging is caused by code that lies *after* the first a\_i lines, but *before* the first b\_i + 1 lines of my standard .emacs file, I can start Emacs with an init file consisting of c\_i lines of my standard .emacs file, where c\_i is approximately equal to (a\_i + b\_i)/2, and check whether the problem occurs. If it does occur, I then will know that the problem is caused by code that lies *after* the first a\_i lines, but *before* the first c\_i + 1 lines of my standard .emacs file. If it doesn't occur, I then will know that the problem is caused by code that lies *after* the first c\_i lines, but *before* the first b\_i + 1 lines of my standard .emacs file. In the first case, I set a\_{i+1} = a\_i and b\_{i+1} = c\_i; in the second, I set a\_{i+1} = c\_i and b\_{i+1} = b\_i. Now I can apply the same procedure all over again. At each iteration, the difference b\_i - a\_i shrinks, therefore eventually this difference will become small enough for me to be able to identify the "top-level" S-expression that is causing the problem. Since I already know that my standard .emacs does cause the problem, I can begin the induction by setting a\_0 = 0 and b\_0 = N (where is the number of lines in my standard .emacs file), and then carrying on as described above. I.e. I start Emacs with an init file consisting of approximately the first (a\_0 + b\_0)/2 = (0 + N)/2 = N/2 lines of my standard .emacs file, and test for the occurrence of the problem. Based on the outcome of this test, I establish the values of a\_1 and b\_1, and repeat the process. Etc. </sup> # Answer If was me, I'd just use a keyboard macro. Hopefully your test procedure doesn't abort recording the macro. If so, you'll have to find some way to wrap that last command. 1. Start the macro recording with `C-x (` 2. `;; do your interactive stuff` 3. End recording the macro with `C-x )` 4. Name the macro something meaningful (eg. "mykmacro") with `C-x C-k n mykmacro RET` 5. Save your macro * visit a new file with `C-x C-f mykmacro.el` * insert your named macro into the buffer with `M-x insert-kbd-macro` * save the file `C-x C-s` * exit Emacs `C-x C-x` Now, in your shell you can run your macro non-interactively against your init file. ``` $ cat myinit.el (message "this msg is from myinit.el") $ cat mykmacro.el ;; this kbd macro inserts "foo" on two lines, and capitalizes the first (fset 'mykmacro (kmacro-lambda-form [?\C-a ?f ?o ?o return ?f ?o ?o return up up ?\C-a ?\M-x ?c ?a ?p ?i ?t ?a ?l ?i ?z ?e ?- ?w ?o ?r tab return down down ?\C-a] 0 "%d")) $ cat /tmp/foobar.txt cat: /tmp/foobar.txt: No such file or directory $ emacs --batch -l myinit.el -l mykmacro.el --eval '(find-file "/tmp/foobar.txt")' -f mykmacro -f save-buffer this msg is from myinit.el $ cat /tmp/foobar.txt Foo foo ``` Obviously the meat here is in the invocation of `emacs`. The argument break down is like this. * `--batch`: use non-interactive "batch" mode * `-l myinit.el`: `batch` implies `-q` so we must manually `load` our *init file* * `-l mykmacro.el`: `load` the file where we saved our keyboard macro * `--eval ...`: eval a lisp form (open `/tmp/foobar.txt`) * `-f mymkmacro`: call a lisp function without arguments. a shortcut for `--eval '(mykmacro)'` * `-f save-buffer`: again, but with `save-buffer` (ie. `C-x C-s`) Obviously this is a bit of a contrived example for demonstration purposes. Since you're testing your *init file* all you'd probably need is something like ``` $ emacs --batch -l your_test_init.el -l your_kbd_macro.el -f your_kbd_macro ``` Hopefully, this gets you squared away. If not, Emacs comes with a test rig for unit testing called, `ert`, that you may want to look into. > 2 votes --- Tags: debugging, keyboard-macros ---
thread-69535
https://emacs.stackexchange.com/questions/69535
Is there a "switch to buffer" hook?
2021-11-28T00:42:11.167
# Question Title: Is there a "switch to buffer" hook? I'm running emacs 26.3. I want to run a hook every time I switch to a buffer. However, I have not been able to find any kind of "buffer switch hook". If I want to always run a function when switching to a buffer, do I have to do something like wrapping `switch-to-buffer` with advice? Or is there some other way to accomplish this? # Answer > 4 votes If you're using Emacs 27.1 or later, you can use: `C-h``v` `window-selection-change-functions` Use `add-hook` with the `LOCAL` argument set a function for a specific buffer. For more details see `C-h``i``g` `(elisp)Window Hooks` --- Tags: buffers, hooks, advice ---
thread-69532
https://emacs.stackexchange.com/questions/69532
Using defadvice to add an interactive argument to a non-interactive function?
2021-11-27T22:15:14.467
# Question Title: Using defadvice to add an interactive argument to a non-interactive function? Is there a way to wrap a non-interactive function within `defadvice` so that the new function can accept an interactive argument which can alter the way that the wrapped function gets called? In other words, suppose there is a standard elisp function called `original-function` which was not written to run interactively. I'd like to do something like this ... ``` (defadvice original-function (around original-function-around activate) (interactive "P") ;; Check whether a raw argument was supplied, and if so, ;; somehow call the original function with non-standard arguments. ;; If a raw argument was not supplied, just do the following ... ad-do-it) ``` # Answer > 1 votes Note, that `defadvice` has been replaced by `advice-add` since Emacs 24.4. With `advice-add`, you could just do the following. ``` (defun original-function () "Some function without `interactive' specification and with no args." (message "Do something.")) ;; Cleaning up the mess when repeatedly advicing: (advice-mapc `(lambda (fun props) (advice-remove 'original-function fun)) 'original-function) ;; That is the actual advice: (advice-add 'original-function :around (lambda (original-fun &optional prefix) ;; We use a lambda rather than a named function ;; since the named function would not be meaningful as command. "The new function with PREFIX argument replacing ORIGINAL-FUN." (interactive "P") (if prefix (message "Do something else.") (funcall original-fun)) ) ) ``` That also works when the original function has arguments: ``` (defun original-function (arg &optional opt-arg) "Some function without `interactive' specification and with no args." (message "Do something with arg %s and opt-arg %s." arg opt-arg)) ;; Cleaning up the mess when repeatedly advicing: (advice-mapc `(lambda (fun props) (advice-remove 'original-function fun)) 'original-function) ;; That is the actual advice: (advice-add 'original-function :around (lambda (original-fun arg &optional opt-arg prefix) ;; We use a lambda rather than a named function ;; since the named function would not be meaningful as command. "The new function with PREFIX argument replacing ORIGINAL-FUN." (interactive "sArg:\nsOptional arg:\nP") (if prefix (message "Do something else with arg %s and opt-arg %s." arg opt-arg) (funcall original-fun arg opt-arg)) ) ) ``` You can also use the variable `current-prefix-arg` within the advicing function. Maybe, that is even cleaner because the argument list does not get messed up: ``` (defun original-function (arg &optional opt-arg) "Some function without `interactive' specification and with no args." (message "Do something with arg %s and opt-arg %s." arg opt-arg)) ;; Cleaning up the mess when repeatedly advicing: (advice-mapc `(lambda (fun props) (advice-remove 'original-function fun)) 'original-function) ;; That is the actual advice: (advice-add 'original-function :around (lambda (original-fun arg &optional opt-arg) ;; We use a lambda rather than a named function ;; since the named function would not be meaningful as command. "The new function with PREFIX argument replacing ORIGINAL-FUN." (interactive "sArg:\nsOptional arg:") (if current-prefix-arg (message "Do something else with arg %s and opt-arg %s." arg opt-arg) (funcall original-fun arg opt-arg)) ) ) ``` # Answer > 0 votes This should be all you need, with `foo` as an example of a non-interactive function you want to advise in the way you say. ``` (defun foo (&rest args) (message "FOO ARGS: %S" args)) (defun my-advice (orig-fn &rest orig-args) (interactive "P") (when current-prefix-arg (message "Do something interactive")) (apply orig-fn orig-args))) (advice-add 'foo :around #'my-advice) ``` The command that's the interactive advised function takes a prefix arg as its only arg. (You could of course have it take more args, if you wanted that.) --- But you also said that with a prefix arg you want to invoke the advised function with different args. For that, you just pass those args instead of `orig-args`, when you invoke the function with `apply`. You didn't specify what you want for that conditional behavior, but that's the idea. ``` (defun my-advice (orig-fn &rest orig-args) (interactive "P") (apply orig-fn (if current-prefix-arg (some-alternative-list-of-args) ; <======= orig-args))) ``` --- Tags: interactive, advice, arguments ---
thread-69530
https://emacs.stackexchange.com/questions/69530
How to bind a terminal command to a key for python code autoformatting using autopep8
2021-11-27T18:32:58.710
# Question Title: How to bind a terminal command to a key for python code autoformatting using autopep8 I'd like to autoformat my python code from the buffer that contains it with a key. I was looking at this tutorial. One can autoformat the code from the terminal with the command: ``` autopep8 --in-place --aggressive --aggressive <filename> ``` I tested it and it works. I'd like to have that bound to a key. The tutorial provides the code: ``` (defcustom python-autopep8-path (executable-find "autopep8") "autopep8 executable path." :group 'python :type 'string) (defun python-autopep8 () "Automatically formats Python code to conform to the PEP 8 style guide. $ autopep8 --in-place --aggressive --aggressive <filename>" (interactive) (when (eq major-mode 'python-mode) (shell-command (format "%s --in-place --aggressive %s" python-autopep8-path (shell-quote-argument (buffer-file-name)))) (revert-buffer t t t))) (bind-key "C-c C-a" 'python-auto-format) (eval-after-load 'python '(if python-autopep8-path (add-hook 'before-save-hook 'python-autopep8))) ``` that added to my `.emacs` file, but when I try `Ctrl C - Ctrl A` I get the error: `Wrong type argument: commandp, python-auto-format`. Reading the first answer of this question, they suggest the problem in their case might be that the snippet is for an older version of emacs. I suspect the problem here is the same as the tutorial is from 2015. I have no idea how to modify that code, so that it binds `Ctrl C - Ctrl A` to the code autoformatting. # Answer As pointed out by @Dan in the comments, the problem was that the piece of code invoked `python-auto-format`, which undefined. Instead, it should be `python-autopep8`. The functioning code looks like this: ``` (defcustom python-autopep8-path (executable-find "autopep8") "autopep8 executable path." :group 'python :type 'string) (defun python-autopep8 () "Automatically formats Python code to conform to the PEP 8 style guide. $ autopep8 --in-place --aggressive --aggressive <filename>" (interactive) (when (eq major-mode 'python-mode) (shell-command (format "%s --in-place --aggressive %s" python-autopep8-path (shell-quote-argument (buffer-file-name)))) (revert-buffer t t t))) (bind-key "C-c C-a" 'python-autopep8) ;;this is the part I changed to make it work (eval-after-load 'python '(if python-autopep8-path (add-hook 'before-save-hook 'python-autopep8))) ``` > 1 votes --- Tags: key-bindings, python, terminal-emacs, shell-command, formatting ---
thread-69541
https://emacs.stackexchange.com/questions/69541
IntelliJ style comment block cannot be recognized
2021-11-28T11:30:28.207
# Question Title: IntelliJ style comment block cannot be recognized In java-mode, I find the IntelliJ style comment block `/** ... */` cannot be recognized correctly. And I have checked that the value of `comment-start-skip` variable (inherit from c-mode) is set as `"\\(//+\\|/\\*+\\)\\s *"`, which is supposed to match `/**` in first line. Any idea? # Answer Ok, I found that starting with `/**` is a convention for javadoc comment. As opposed to the plain comment's `font-lock-comment-face`, we can do highlight customization with `font-lock-doc-face`. > 1 votes --- Tags: comment ---
thread-69534
https://emacs.stackexchange.com/questions/69534
Acceptance test for a flow that uses the transient package?
2021-11-27T23:49:50.057
# Question Title: Acceptance test for a flow that uses the transient package? I am trying to write a test around a flow that uses transient. Here is the sample code: ``` ;; -*- lexical-binding: t; coding: utf-8 -*- (require 'transient) (require 'buttercup) (require 'with-simulated-input) (defun ogt-print-a () (interactive) (insert "a")) (defun ogt-print-b () (interactive) (insert "b")) (transient-define-prefix ogt-transient () ["X" ("f" "test f" ogt-print-a) ("g" "test g" ogt-print-b)]) (describe "Transient" (it "takes keys" (with-temp-buffer (with-simulated-input "f" (ogt-transient) (expect (buffer-string) :to-match "a"))))) ``` Now, I would expect the library "with-simulated-input" to press "f" when the transient comes up and to have that put "a" in the temp buffer, as that's what the function called should do. However, it does not add anything, and the temp buffer remains empty. I could use some help, I really would like to *know for a fact* that my package works. I wondered if `with-temp-buffer` could be the culprit but changing this to a `set-buffer` call did not seem to help. # Answer > 2 votes Author of with-simulated-input here. This happens because `with-simulated-input` is expecting BODY to read input, and `ogt-transient` doesn't read input. It only sets up the appropriate key bindings to implement the transient menu and then returns, letting Emacs handle those key bindings as normal. However, when it returns, `with-simulated-input` assumes it is "done" and continues evaluating BODY. In this case, since `ogt-transient` sets up the appropriate bindings and returns without blocking on input, you don't actually need `with-simulated-input` at all. You can simply follow it by the appropriate `execute-kbd-macro` form, e.g. ``` (progn (ogt-transient) (execute-kbd-macro "f")) ``` For more details, see the issue here. --- Tags: transient-library, with-simulated-input ---
thread-69547
https://emacs.stackexchange.com/questions/69547
Error /bin/bash: line 1: nil: command not found
2021-11-28T18:44:22.517
# Question Title: Error /bin/bash: line 1: nil: command not found I have the following code to auto format python code using autopep8: ``` (defcustom python-autopep8-path (executable-find "autopep8") "autopep8 executable path." :group 'python :type 'string) (defun python-autopep8 () "Automatically formats Python code to conform to the PEP 8 style guide. $ autopep8 --in-place --aggressive --aggressive <filename>" (interactive) (when (eq major-mode 'python-mode) (shell-command (format "%s --in-place --aggressive %s" python-autopep8-path (shell-quote-argument (buffer-file-name)))) (revert-buffer t t t))) (bind-key "C-c C-a" 'python-autopep8) ``` When I am setting up emacs and use for the first time it works perfectly, but then when I close emacs with `M-x kill-emacs` and re open emacs again and try to use it, I get the error: `/bin/bash: line 1: nil: command not found`. I found this question on Stackoverflow where that person gets a similar error. They solved it apparently by setting the proper path to the variable `PATH` using `M-x setenv`. I was trying to do the same, but I am not sure what path to use and I tried different paths but kept getting the same error. I'd appreciate any help. I suspect the solution will be simple, but I just don't know it. # Answer Thanks to @phils who helped to come up with this piece of code that works: ``` (defcustom python-autopep8-path (or (executable-find "autopep8") "autopep8") "autopep8 executable path." :group 'python :type 'string) (defun python-autopep8 () "Automatically formats Python code to conform to the PEP 8 style guide. $ autopep8 --in-place --aggressive --aggressive <filename>" (interactive) (when (eq major-mode 'python-mode) (shell-command (format "%s --in-place --aggressive %s" python-autopep8-path (shell-quote-argument (buffer-file-name)))) (revert-buffer t t t))) (bind-key "C-c C-a" 'python-autopep8) ``` > 1 votes --- Tags: python, commands, exec-path, error ---
thread-69552
https://emacs.stackexchange.com/questions/69552
How to provide my own ediff-make-wide-display-function for ediff
2021-11-29T05:56:16.593
# Question Title: How to provide my own ediff-make-wide-display-function for ediff For Ediff's wide display feature I like to use my own `ediff-make-wide-display` function. Ediff has a variable for this: `ediff-make-wide-display-function`. However when I write: ``` (defun my-ediff-make-wide-display () ...) (setq ediff-make-wide-display-function #'my-ediff-make-wide-display) ``` my definition doesn't seem to get used when I toggle the display to wide view. I guess the reason is that `ediff-make-wide-display-function` is defined as a local variable (via `ediff-defvar-local`), and my `setq` call sets the variable somewhere else... So to which buffers is the definition local and how can I set it for all of these buffers? # Answer > 2 votes I think you've diagnosed the issue correctly, and you can either: 1. Use `ediff-mode-hook` to set the buffer-local value. 2. Use `setq-default` to set the default value. Offhand I think #2 seems like the best option. --- Tags: ediff, buffer-local, defvar ---
thread-69543
https://emacs.stackexchange.com/questions/69543
Hanging interface in heavy processing scripts
2021-11-28T13:05:11.113
# Question Title: Hanging interface in heavy processing scripts Emacs org-babel is an excellent notebook tool for exploratory and interactive statistics in ESS. Now, I need to run very heavy scripts in R and the entire interface of emacs hungs for the duration of the code execution. This is an important limitation of babel. * Are there ways of avoiding this? Here is a MWE: ``` #+begin_src R :results output library(umx) data(docData) var1 = paste0("varA", 1:3) var2 = paste0("varB", 1:3) tmp = umx_scale_wide_twin_data(varsToScale= c(var1, var2), sep= "_T", data= docData) mzData = subset(docData, zygosity %in% c("MZFF", "MZMM")) dzData = subset(docData, zygosity %in% c("DZFF", "DZMM")) m1 = umxDoCp(var1, var2, mzData= mzData, dzData= dzData, sep = "_T", causal= TRUE, autoRun = F) umxSummary(m1) #+end_src ``` Update: I already tried ob-async, but it is not compatible with : session, which reduces babel usefulnes. # Answer When Emacs is waiting for an orgmode cose block to run, you can regain control with 'C-g'. I'm not sure why this works, but so far I haven't had the cose block stop running when I do this. > 1 votes --- Tags: org-babel ---
thread-69539
https://emacs.stackexchange.com/questions/69539
Dedicated python shells that runs the code
2021-11-28T02:45:53.100
# Question Title: Dedicated python shells that runs the code This answer how to map `C-c !` to create a new python shell for the current buffer. The main code is this: ``` (defun my-python-start-or-switch-repl (&optional msg) "Start and/or switch to the REPL." (interactive "p") (if (python-shell-get-process) (python-shell-switch-to-shell) (progn (run-python (python-shell-calculate-command) t t) (python-shell-switch-to-shell) ) ) ) ``` As it can be seen, it uses `run-python`, so it only opens a shell that has the name of the buffer it was opened it from, e.g., if the program is `foo.py`, then the shell has the name: `*Python[foo.py]*`, but it doesn't run `foo.py`. Is there a way to have dedicated shells that by default run the program from which they being generated? # Answer You should be able to do what you need modifying your function like this: ``` defun my-python-start-or-switch-repl (&optional msg) "Start and/or switch to the REPL." (interactive "p") (if (python-shell-get-process) (progn (python-shell-send-buffer) (python-shell-switch-to-shell) ) (progn (run-python (python-shell-calculate-command) t t) (other-window 1) (python-shell-send-buffer) (python-shell-switch-to-shell) ) ) ) ``` The main change is the call to `python-shell-send-buffer` that sends the entire current buffer to the running Python process. > 1 votes --- Tags: shell, ipython ---
thread-69565
https://emacs.stackexchange.com/questions/69565
making the frame title more informative
2021-11-30T09:54:51.510
# Question Title: making the frame title more informative The frame title I can see in an emacs window on my computer running Windows 11 is "emacs@NEYMAN", where "Neyman" is the computer name. Is it possible to make the frame title more informative and reflect the contents of the file? Ideally, I would like to be able to specify the frame title in one of the first lines of the text file. The reason I am asking is that I am accustomed to never combining taskbar buttons in Windows 10, but Windows 11 has removed this option. When I hover over a combined emacs button on the taskbar, I am shown the frame titles of all open emacs files, and those titles don't give me any idea of the files' contents. There is a section (C.11 in my version) about frame titles in "GNU Emacs Manual", but I can't see how I can customize the frame title for an individual file. # Answer You can use a file-variable for this, at the start or at the end of your file (as explained in the manual). For example in a bash file, where `#` is used for comments, you can set the frame title statically, e.g. by adding the following line at the beginning of the file ``` # -*- frame-title-format: "new title" -*- ``` Or you can set it dynamically using e.g. ``` # -*- eval : (setq frame-title-format (buffer-file-name)) -*- ``` In a .c file, you can use ``` /* -*- frame-title-format: "new title" -*- */ ``` etc. > 2 votes --- Tags: frame-title-format ---
thread-69566
https://emacs.stackexchange.com/questions/69566
How to compile makefile files for newbies
2021-11-30T11:29:08.650
# Question Title: How to compile makefile files for newbies I just got cloned a piece of software and the download folder looks like this: What I am to do next to compile this piece of software? Thanks! # Answer This isn’t really an Emacs question. Emacs is a text editor, and `makefile-mode` is for editing Makefiles. A Makefile contains instructions for building software, and often for other tasks such as testing or packaging it. What you want to do is open up a shell in that directory and type “make”. It will see that there is a `Makefile`, and use it as a source of instructions. There’s a decent chance that it will fail due to missing dependencies, which you will want to install. Also, you appear to be using OSX, so there’s also a good chance that this Makefile is intended to be used with GNU Make; if that turns out to be the case then you may need to type “gmake” instead. If you want more information about make, I recommend reading the documentation. You can probably run the compile inside of Emacs if you want. Open up a file, such as the README or the Makefile, then type `M-x compile`. Emacs will then prompt you to enter a compile command; the default is to run make. Simply hit enter to accept the default and you’ll get a buffer that shows you the compile happening. > 2 votes --- Tags: compile, makefile-mode ---
thread-25037
https://emacs.stackexchange.com/questions/25037
Compile emacs with xwidget under OSX?
2016-08-03T05:45:04.993
# Question Title: Compile emacs with xwidget under OSX? **How do I compile Emacs with `xwidget` under OSX?** When I tried to run `./configure --prefix=$HOME/emacs-xwidgets --with-x-toolkit=gtk3 --with-xwidgets` I get an error `configure: error: xwidgets requested but gtk3 not used.`. But it looks like I have an gtk+3.0 - `sandric@sandric-mac ~/emacs> brew install gtk+3 Error: gtk+3-3.18.9 already installed To install this version, first `brew unlink gtk+3`` It looks like I don't have `gtk3` package in `pkg-config` \- `sandric@sandric-mac ~> pkg-config --list-all libzmq libzmq - 0MQ c++ library gio-unix-2.0 GIO unix specific APIs - unix specific headers for glib I/O library libusb-1.0 libusb-1.0 - C API for USB device access from Linux, Mac OS X, Windows and OpenBSD/NetBSD userspace gobject-introspection-no-export-1.0 gobject-introspection - GObject Introspection libecpg_compat libecpg_compat - PostgreSQL libecpg_compat library gio-2.0 GIO - glib I/O library libcdt libcdt - Container DataType library cairo-gobject cairo-gobject - gobject functions for cairo graphics library harfbuzz-icu harfbuzz - HarfBuzz text shaping library ICU integration cairo-quartz-font cairo-quartz-font - Quartz font backend for cairo graphics library libpng16 libpng - Loads and saves PNG files dbus-1 dbus - Free desktop message bus ImageMagick++ ImageMagick++ - Magick++ - C++ API for ImageMagick (ABI Q16) cairo-ps cairo-ps - PostScript surface backend for cairo graphics library gmodule-2.0 GModule - Dynamic module loader for GLib lcms lcms - LCMS Color Management Library glib-2.0 GLib - C Utility Library ImageMagick ImageMagick - ImageMagick - convert, edit, and compose images (ABI Q16) Magick++-6.Q16 Magick++ - Magick++ - C++ API for ImageMagick (ABI Q16) gimpthumb-2.0 GIMP Thumb - GIMP Thumbnail Library gdlib gd - GD graphics library libpcre2-16 libpcre2-16 - PCRE2 - Perl compatible regular expressions C library (2nd API) with 16 bit character support pango Pango - Internationalized text handling uuid OSSP uuid - Universally Unique Identifier (UUID) Library babl babl - Dynamic, any to any, pixel format conversion library MagickWand MagickWand - MagickWand - C API for ImageMagick (ABI Q16) libedit libedit - command line editor library provides generic line editing, history, and tokenization functions. libublio ublio - UBLIO caching library libicns libicns - Loads and saves Macintosh icns files libcgraph libcgraph - Graph library (file i/o, dot language parsing, graph, subgraph, node, edge, attribute, data structure manipulation) libpcrecpp libpcrecpp - PCRECPP - C++ wrapper for PCRE pangoft2 Pango FT2 and Pango Fc - Freetype 2.0 and fontconfig font support for Pango libevent_pthreads libevent_pthreads - libevent_pthreads adds pthreads-based threading support to libevent gdk-pixbuf-2.0 GdkPixbuf - Image loading and scaling gmodule-no-export-2.0 GModule - Dynamic module loader for GLib MagickCore-6.Q16 MagickCore - MagickCore - C API for ImageMagick (ABI Q16) osxfuse fuse - OSXFUSE libcroco-0.6 libcroco - a CSS2 Parsing and manipulation Library in C. libxdot libxdot - Library for parsing graphs in xdot format liblzma liblzma - General purpose data compression library gtk+-3.0 GTK+ - GTK+ Graphical UI Library libssh2 libssh2 - Library for SSH-based communication gobject-introspection-1.0 gobject-introspection - GObject Introspection Magick++ Magick++ - Magick++ - C++ API for ImageMagick (ABI Q16) gtk+-unix-print-2.0 GTK+ - GTK+ Unix print support libiodbc iODBC - iODBC Driver Manager libfontforgeexe libfontforgeexe - for embedding the FontForge UI in a program. gdk-2.0 GDK - GTK+ Drawing Kit (quartz target) gtk-mac-integration-gtk2 gtk-mac-integration-gtk2 - Mac menu bar and dock integration for GTK+ gtk-mac-integration-gtk3 gtk-mac-integration-gtk3 - Mac menu bar and dock integration for GTK+ yaml-0.1 LibYAML - Library to parse and emit YAML libssl OpenSSL - Secure Sockets Layer and cryptography libraries libpcre2-32 libpcre2-32 - PCRE2 - Perl compatible regular expressions C library (2nd API) with 32 bit character support apr-util-1 APR Utils - Companion library for APR libevent libevent - libevent is an asynchronous notification event loop library openssl OpenSSL - Secure Sockets Layer and cryptography libraries and tools libevent_openssl libevent_openssl - libevent_openssl adds openssl-based TLS support to libevent mysqlclient mysqlclient - MySQL client library cairo-pdf cairo-pdf - PDF surface backend for cairo graphics library gimpui-2.0 GIMP UI - GIMP User Interface Library apr-1 APR - The Apache Portable Runtime library gdk-quartz-2.0 GDK - GTK+ Drawing Kit (quartz target) pangocairo Pango Cairo - Cairo rendering support for Pango gmodule-export-2.0 GModule - Dynamic module loader for GLib libgvpr libgvpr - The GVPR library gimp-2.0 GIMP - GIMP Library libpq libpq - PostgreSQL libpq library ImageMagick++-6.Q16 ImageMagick++ - Magick++ - C++ API for ImageMagick (ABI Q16) Wand-6.Q16 MagickWand - MagickCore - C API for ImageMagick (ABI Q16) gsettings-desktop-schemas gsettings-desktop-schemas - Shared GSettings schemas for the desktop, including helper headers pixman-1 Pixman - The pixman library (version 1) libpcre2-8 libpcre2-8 - PCRE2 - Perl compatible regular expressions C library (2nd API) with 8 bit character support cairo-quartz-image cairo-quartz-image - Quartz Image surface backend for cairo graphics library gtk+-quartz-2.0 GTK+ - GTK+ Graphical UI Library (quartz target) libpathplan libpathplan - Library for planning polyline and bezier paths around polygon obstacles libpcre16 libpcre16 - PCRE - Perl compatible regular expressions C library with 16 bit character support libfontforge libfontforge - a font manipulation library. libtiff-4 libtiff - Tag Image File Format (TIFF) library. gobject-2.0 GObject - GLib Type, Object, Parameter and Signal Library libgvc libgvc - The GraphVizContext library gtk+-unix-print-3.0 GTK+ - GTK+ Unix print support libpng libpng - Loads and saves PNG files gthread-2.0 GThread - Thread support for GLib cairo-fc cairo-fc - Fontconfig font backend for cairo graphics library fontconfig Fontconfig - Font configuration and customization library libecpg libecpg - PostgreSQL libecpg library cairo cairo - Multi-platform 2D graphics library gdk-3.0 GDK - GTK+ Drawing Kit pygobject-2.0 PyGObject - Python bindings for GObject libcrypto OpenSSL-libcrypto - OpenSSL cryptography library libpcreposix libpcreposix - PCREPosix - Posix compatible interface to libpcre cairo-png cairo-png - PNG functions for cairo graphics library cairo-ft cairo-ft - FreeType font backend for cairo graphics library epoxy epoxy - epoxy GL dispatch Library gtk-mac-integration gtk-mac-integration-gtk2 - Mac menu bar and dock integration for GTK+ Wand MagickWand - MagickCore - C API for ImageMagick (ABI Q16) atk Atk - Accessibility Toolkit libpcre2-posix libpcre2-posix - Posix compatible interface to libpcre2-8 fish fish - fish, the friendly interactive shell libntfs-3g libntfs-3g - NTFS-3G Read/Write Driver Library libczmq libczmq - The high-level C binding for 0MQ cairo-svg cairo-svg - SVG surface backend for cairo graphics library libsodium libsodium - A portable, cross-compilable, installable, packageable fork of NaCl, with a compatible API. gdk-quartz-3.0 GDK - GTK+ Drawing Kit cairo-quartz cairo-quartz - Quartz surface backend for cairo graphics library fuse fuse - OSXFUSE harfbuzz harfbuzz - HarfBuzz text shaping library libtls LibreSSL-libtls - Secure communications using the TLS socket protocol. MagickWand-6.Q16 MagickWand - MagickWand - C API for ImageMagick (ABI Q16) libpgtypes libpgtypes - PostgreSQL libpgtypes library pycairo Pycairo - Python bindings for cairo libpcre libpcre - PCRE - Perl compatible regular expressions C library with 8 bit character support cairo-script cairo-script - script surface backend for cairo graphics library ImageMagick-6.Q16 ImageMagick - ImageMagick - convert, edit, and compose images (ABI Q16) libpcre32 libpcre32 - PCRE - Perl compatible regular expressions C library with 32 bit character support gail-3.0 Gail - GNOME Accessibility Implementation Library cairo-tee cairo-tee - tee surface backend for cairo graphics library freetype2 FreeType 2 - A free, high-quality, and portable font engine. slang slang - S-Lang programming library and interpreter MagickCore MagickCore - MagickCore - C API for ImageMagick (ABI Q16) gtk+-quartz-3.0 GTK+ - GTK+ Graphical UI Library librsvg-2.0 librsvg - library that renders svg files gtk+-2.0 GTK+ - GTK+ Graphical UI Library (quartz target) oniguruma oniguruma - Regular expression library harfbuzz-gobject harfbuzz - HarfBuzz text shaping library GObject integration pygtk-2.0 PyGTK - Python bindings for GTK+ and related libraries gail Gail - GNOME Accessibility Implementation Library` # Answer I have gtk+-3 installed by homebrew and I can see it using `pkg-config --list-all`. I have the following in my .zshrc, which may matter: ``` export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:/usr/local/Cellar/libxml2/2.9.2/lib/pkgconfig:/opt/X11/lib/pkgconfig:$PKG_CONFIG_PATH ``` To enable the gtk3 toolkit you also need to disable nextstep as building option, adding `--without-ns` to you configure. > 2 votes # Answer in addition to the --without-ns option, you also need the --without-x11 option, to force gtk+3 to use quartz. `brew install --build-from-source at-spi2-core at-spi2-atk cairo harfbuzz pango gtk+ librsvg gnome-icon-theme gtk+3 --without-ns --without-x --without-x11 --with-gtk+3` > 2 votes # Answer i also needed X11 emacs on OSX, and chased stackexchange leads like this one all day with no success (10.14). what finally worked was an approach with macports instead of homebrew: ``` sudo port install emacs +x11 ``` solution courtesy of @mariusm stackoverflow 2016 > 0 votes --- Tags: osx ---
thread-48948
https://emacs.stackexchange.com/questions/48948
Emacs Mac OSX after upgrade to 26.2 launches only in `-nw` mode
2019-04-15T19:24:41.040
# Question Title: Emacs Mac OSX after upgrade to 26.2 launches only in `-nw` mode I upgraded to Emacs 26.2 on my Mac OSX Sierra instance via "brew". After the upgrade, the `emacs` command will not open a new "GUI window", i.e. it runs as if I passed the `-nw` args or ran it from an `ssh` session. I.e. it does not seem to recognize the Mac windowing system: This behavior has changed since yesterday. **From the docs** Using Emacs with X Emacs has been tailored to work well with the X window system. If you run Emacs from under X win- dows, it will create its own X window to display in. You will probably want to start the editor as a background process so that you can continue using your original window. How can I launch Emacs without it being in terminal (`nw`) mode? # Answer > 7 votes You want to use the Homebrew cask for Emacs. That will install a "brewed" package of Emacs from https://emacsformacosx.com/. ``` brew cask install emacs ``` The "regular" Homebrew package for Emacs is built without GUI support. Via `brew edit emacs`: ``` def install args = %W[ --disable-dependency-tracking --disable-silent-rules --enable-locallisppath=#{HOMEBREW_PREFIX}/share/emacs/site-lisp --infodir=#{info}/emacs --prefix=#{prefix} --with-gnutls --without-x --with-xml2 --without-dbus --with-modules --without-ns --without-imagemagick ] ``` Note the flag `--without-ns`. This disables the GUI on macOS. # Answer > 0 votes i had the same problem, and tried the solution from @nega but it did not work for me. i am not a homebrew expert, but the command as listed didn't work and i had to use this syntax: ``` brew install --cask emacs ``` but like i said, the emacs window didn't open in X11. i had success with the macports install instead of the homebrew install: ``` sudo port install emacs +x11 ``` solution courtesy of @mariusm stackoverflow 2016 --- Tags: osx, start-up ---
thread-61196
https://emacs.stackexchange.com/questions/61196
how can I run conda in emacs shell?
2020-10-14T16:51:08.473
# Question Title: how can I run conda in emacs shell? I've been using Python command 'conda' in the terminal on my Mac. But when I run a command like 'conda activate ...' in Emacs's shell (M-x shell), it gives me this objection: > CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'. It tells me ``` To initialize your shell, run $ conda init <SHELL_NAME> Currently supported shells are: - bash - fish - tcsh - xonsh - zsh - powershell ``` But when I run `conda init bash`, it has no effect: I just get back the same result trying to run the 'conda activate ...' command again. Is there anything I can do about this? Note: I just want to run conda in the shell as I do in the terminal. I'm not really interested in other improved methods of running conda in Emacs (such as conda mode). Thank you. # Answer > 1 votes I think you need to use the emacs package conda.el The problem is that `conda activate` will change the $PATH of the shell that it is in. This will not be reflected in emacs. It allows you to see and change conda virtual environments in emacs. This includes support for eshell > Support for eshell is turned on by calling conda-env-initialize-eshell. After doing this, any new eshells you launch will be in the correct environment and have access to installed executables, etc. The mode also provides a variety of virtualenvwrapper-like commands that work identically to their bash/zsh counterparts (described in detail below). Note that in contrast to how interactive shells work, Eshell shares an environment with Emacs, so if you activate or deactivate in one, the other is affected as well. Note that this requires the variable eshell-modify-global-environment to be set to true -- running conda-env-initialize-eshell causes this to occur. # Answer > -1 votes To not get into an extended discussion in comments I am moving this to an answer. If your commands work in your regular `$SHELL` but not in emacs, the following will probably help. > https://github.com/purcell/exec-path-from-shell I highly recommend you use the excellent `exec-path-from-shell` package if you are not using it already. IMHO, this is one of those "must-have"s if you are using Emacs on `Mac OS`. # Answer > -1 votes `conda` is an executable which is added to the environment variable `PATH`. Your error notes that the command, the executable, can't be found. You need to make it discoverable. There are numerous ways this could be done. Fortunately, the conda distribution provides many scripts to set up shell environments. You can likely leverage those. On Windows, it was sufficient for me to call `conda.bat`. This is located within `../Anaconda3/condabin/`. Looking in `../Anaconda3/Scripts/`, I see `activate` which is a shell script for Unix-like environments (i.e. Mac OS). It calls `../Anaconda3/etc/profile.d/conda.sh`. This looks analogous to `conda.bat`. On Windows, this works for me: 1. `M-x shell` 2. Call `C:\path\to\Anaconda3\conda.bat activate <my-env>` within shell You might have luck with: 1. `M-x shell` 2. Call `/path/to/Anaconda3/etc/profile.d/conda.sh activate <my-env>` Of course, check `conda.sh` for the precise way arguments are handled. --- Tags: python, shell, anaconda-mode ---
thread-68377
https://emacs.stackexchange.com/questions/68377
How to use labels inserted in .dtx files?
2021-09-04T09:01:14.137
# Question Title: How to use labels inserted in .dtx files? I wonder if there is a way to have `reftex` print and use labels inserted in a `.dtx` file from the TOC menu. As every line in a `.dtx` file begins with `%`, `reftex` seems unable to display labels. For example, from the TOC menu (`C-c =`), hitting on `l` has no effect. Furthermore, as `reftex` does not see the labels, I am unable to insert references from `C-c )`. On another side, `Ref -> Global Actions -> Goto Label` works as expected. I use emacs 26.1, and AUCTeX 13.0.14 from gnu. Any help would be much appreciated. # Answer > 2 votes RefTeX sees the `\label` macros which are commented out, it just doesn't show them by default. You can access them in the `*RefTeX Select*` buffer. This is a documented feature. From the manual: > ## 3.2 Referencing Labels > > RefTeX scans the document in order to find all labels. \[...\]. > Here is a list of special commands in the selection buffer. A summary of this information is always available from the selection process by pressing `?`. > > ### Controlling what gets displayed > > \[...\] > `%` Toggle the display of labels hidden in comments in the selection buffers. Sometimes, you may have commented out parts of your document. If these parts contain label definitions, RefTeX can still display and reference these labels. For example, I loaded a test file, say arabluatex.dtx, moved point in the paragraph in `\section{Introduction}` (after line 465) and hit `C-c )`, when asked to `SELECT A REFERENCE FORMAT`, I hit `RET` followed by `SPACE` for all labels. In `*RefTeX Select*` buffer, I hit `%` and it looks like this: I can now select a label as usual. --- Tags: auctex, reftex-mode ---
thread-69521
https://emacs.stackexchange.com/questions/69521
Ivy minibuffer colums not left-justified with my setup
2021-11-27T11:21:08.677
# Question Title: Ivy minibuffer colums not left-justified with my setup I am following System Crafters series on Emacs from Scratch on YouTube. With my configuration as I have set it up, Ivy doesn't appear in nice left-justified easy-to-read columns. I am trying to figure out a setting to do this. To be clear, here is what appears in my minibuffer. A slightly shortened version of my init.el file is as follows: ``` (setq inhibit-startup-message t) (setq initial-frame-alist (append initial-frame-alist '((width . 100) (height . 45)))) (load-theme 'wombat) (scroll-bar-mode -1) ; Disable visible scrollbar (tool-bar-mode -1) ; Disable the toolbar (tooltip-mode -1) ; Disable tooltips (set-fringe-mode 10) ; Give some breathing room (menu-bar-mode -1) ; Disable the menu bar (column-number-mode) (global-display-line-numbers-mode t) ;; Disable line numbers for some modes (dolist (mode '(org-mode-hook term-mode-hook shell-mode-hook treemacs-mode-hook eshell-mode-hook)) (add-hook mode (lambda () (display-line-numbers-mode 0)))) (set-face-attribute 'default nil :family "DejaVu Sans Mono" :height 150) ;; Make ESC quit prompts (global-set-key (kbd "<escape>") 'keyboard-escape-quit) ;; Initialize package sources (require 'package) (setq package-archives '(("melpa" . "https://melpa.org/packages/") ("org" . "https://orgmode.org/elpa/") ("elpa" . "https://elpa.gnu.org/packages/"))) (package-initialize) (unless package-archive-contents (package-refresh-contents)) ;; Initialize use-package on non-Linux platforms (unless (package-installed-p 'use-package) (package-install 'use-package)) (require 'use-package) (setq use-package-always-ensure t) (use-package doom-modeline :ensure t :init (doom-modeline-mode 1) :custom ((doom-modeline-height 10))) (use-package ivy :diminish :bind (("C-s" . swiper) :map ivy-minibuffer-map ("TAB" . ivy-alt-done) ("C-l" . ivy-alt-done) ("C-j" . ivy-next-line) ("C-k" . ivy-previous-line) :map ivy-switch-buffer-map ("C-k" . ivy-previous-line) ("C-l" . ivy-done) ("C-d" . ivy-switch-buffer-kill) :map ivy-reverse-i-search-map ("C-k" . ivy-previous-line) ("C-d" . ivy-reverse-i-search-kill)) :config (ivy-mode 1)) (use-package ivy-rich :init (ivy-rich-mode 1)) (use-package counsel :bind (("M-x" . counsel-M-x) ("C-x b" . counsel-ibuffer) ("C-x C-f" . counsel-find-file) :map minibuffer-local-map ("C-r" . 'counsel-minibuffer-history))) (use-package swiper :ensure t) (use-package counsel :bind (("C-M-j" . 'counsel-switch-buffer) :map minibuffer-local-map ("C-r" . 'counsel-minibuffer-history)) :config (counsel-mode 1)) ``` # Answer By a process of elimination, I realised the problem was the font I was using, which puzzles me because I thought any monospace font would do OK. When I removed the following, the formatting in the minibuffer was fine. ``` (set-face-attribute 'default nil :family "DejaVu Sans Mono" :height 150) ``` > 1 votes --- Tags: init-file, ivy ---
thread-69588
https://emacs.stackexchange.com/questions/69588
Error enabling flyspell in emacs - aspell MacOS
2021-12-01T10:00:56.823
# Question Title: Error enabling flyspell in emacs - aspell MacOS I am having some difficulty getting flyspell/aspell to run on emacs 27.2, MacOS 12.01. I think I need to install or enable a dictionary, but no ideas on how to do this. If I type 'M-x flyspell-mode' I get the following error: ``` Starting new Ispell process /usr/local/bin/aspell with default dictionary...done Error enabling Flyspell mode: (Error: No word lists can be found for the language "en_GB".) ``` Sounds like a dictionary is missing. I have the following in my `init.el` ``` ;; Spell-check (require 'flyspell) (setq flyspell-issue-message-flag nil ispell-local-dictionary "en_GB" ispell-program-name "/usr/local/bin/aspell") (add-hook 'text-mode-hook 'flyspell-mode) (add-hook 'prog-mode-hook 'flyspell-prog-mode) ``` If I type `which aspell` in Terminal it returns `/usr/local/bin/aspell` # Answer > 2 votes You need make sure aspell command line program is installed. If it's not installed, run `brew install aspell`, see https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/aspell.rb To specify the dictionary which aspell uses, ``` (setq ispell-extra-args '("--lang=en_US")) ``` I answered lots of questions about flyspell, see https://emacs.stackexchange.com/search?q=user:202+\[flyspell\] You can also read my article, http://blog.binchen.org/posts/what-s-the-best-spell-check-set-up-in-emacs/ Or uses my package `wucuo` (https://github.com/redguardtoo/wucuo) to replace `flyspell-mode` and `flyspell-prog-mode`. Most people are confused on spell checking in Emacs, so let me clarify a few things, * In good old days, people use `ispell.el`. These days, people use `flyspell.el`. `flyspell` does use a few APIs from `ispell`, but they are basically two independent packages. Setting up other ispell variables (except `ispell-extra-args` and `ispell-program-name`) might have no effect on flyspell at all. * `flyspell` needs cli program to do the actual spell checking thing. The cli program could be `aspell` or `hunspell`. * Setting up the options passed to aspell (the cli program) is straight forward. One variable `ispell-extra-args` is enough. * Setting up the options passed to hunspell (the cli program) is more complicated. You can see my other answers for details. --- Tags: init-file, osx, flyspell ---
thread-69587
https://emacs.stackexchange.com/questions/69587
Start external process and communicate with it as soon as send messages
2021-12-01T09:53:36.340
# Question Title: Start external process and communicate with it as soon as send messages I use `gnus` configured to read mails from the `davmail` IMAP server. This one is used to read mails from `outlook` and translate them according to the IMAP protocol. When I start `gnus`, I configured emacs to autostart the `davmail` server, with following function : ``` (defun davmail/start () "Run davmail externally for gnus." (interactive) (if (buffer-live-p "*davmail*") (kill-buffer "*davmail*")) (let ((default-directory davmail-directory)) (start-process "davmail" "*davmail*" local-java-path "-jar" davmail-jar davmail-properties))) ``` The trouble is that `davmail` often asks to accept the `outlook` server certificate, which blocks `gnus`. To overcome this issue, I implemented this function : ``` (defun davmail/accept_certificate () "Accept certificate." (interactive) (if (get-process "davmail") (process-send-string "davmail" "o\n") (message "No running davmail process"))) ``` which retrieves the emacs `davmail` process and send to it the "o" (accept) string. It works but it remains a little painful. I would like to trigger this function whenever the `davmail` process asks for certificate acceptation. Usually, it is a line containing "accept certificate (o/n) ?" This way, I would not have to do it manually each time it occurs. But i am rather new to emacs/lisp and implementing this overpasses my skills. Could you give me some pieces of advices ? I am aware that it is not really an emacs related issue, I could as well ask to the `davmail` developers to implement some kind of auto accept certificate option. But it is a good opportunity for me to improve my emacs skills. Regards # Answer You can do this by switching to using `make-process` and specifying a `:filter` function that checks for the expected output. Something like this: ``` (defvar davmail-output nil) (defun davmail/start () "Run davmail externally for gnus." (interactive) (setq davmail-output nil) (let ((default-directory davmail-directory)) (make-process :name "davmail" :buffer nil :command (list local-java-path "-jar" davmail-jar davmail-properties) :filter (lambda (proc string) (setq davmail-output (concat davmail-output string)) (when (string-match "accept certificate" davmail-output) (davmail/accept-certificate)))))) ``` > 0 votes --- Tags: email, gnus, process ---
thread-69580
https://emacs.stackexchange.com/questions/69580
Trouble aliasing ctl-x-map, C-x 8 insert command?
2021-12-01T05:00:12.323
# Question Title: Trouble aliasing ctl-x-map, C-x 8 insert command? I'm reading the beginning of the Emacs manual on inserting text. It says you can run `C-x 8 [` to insert a left single curly quote. That works. In my `init.el` I have this: ``` (define-key global-map [(control t)] ctl-x-map) ``` I like that because I use a Dvorak keyboard layout, so `C-t` is easy to type. Usually that line takes commands that start with `C-x` and makes them available starting with `C-t` too. But it's failing with this `C-x 8`. If I do: `C-t 8 [`, it get a beep and nothing. In contrast I can do both `C-x b` and `C-t b` to switch to a buffer. Why does my `define-key` attempt work for most `C-x` commands but not `C-x 8`. I'm running GNU Emacs 27.2 on macOS 12. # Answer `C-x 8 [` and similar are defined in a different keymap, `iso-transl-ctl-x-8-map`. What you need is this: ``` (define-key key-translation-map "\C-t8" 'iso-transl-ctl-x-8-map) ``` See the Elisp manual, node Translation Keymaps for more info. > 2 votes --- Tags: key-bindings, keymap, prefix-keys, self-insert-command, key-translation-map ---
thread-69589
https://emacs.stackexchange.com/questions/69589
How to disable momentary highlighting of a match by xref and ggtags?
2021-12-01T11:44:50.457
# Question Title: How to disable momentary highlighting of a match by xref and ggtags? When I call `gtags-find-tag-dwim`, matches item will be highlighted for about one second. When I call `xref-pop-marker-stack`, matches item will be highlighted for about 0.2 second. like this: --------------------------- Add after Drew reply: There will be an annoying underline when `ggtags-highlight-tag` is the default value. Setting this variable to `nil` can prevent this underline, but the highlighting problem still exists, The default effect is as follows: -------------------------------------------- **NOTE:** I'm having trouble and I can't find any results using customize: customize-apropos: No customizable group, face, or option matching (ggtags) # Answer A good approach for finding such info is to look for hooks and user options. I found these answers just by looking in the relevant source files. --- For Xref: ``` (remove-hook 'xref-after-return-hook 'xref-pulse-momentarily) ``` Or `M-x customize-option xref-after-return-hook` and remove hook function `xref-pulse-momentarily`. --- For `ggtags`: Customize option `ggtags-highlight-tag` to disable that highlighting. **NOTE:** Don't just use `setq` to set the option to `nil`. Use the Customize UI. This is because the `defcustom` has a `:set` function that needs to be invoked. > 1 votes --- Tags: highlighting, xref, ggtags ---
thread-69585
https://emacs.stackexchange.com/questions/69585
org-table, fetch a specific cell from all tables in a file
2021-12-01T09:23:06.273
# Question Title: org-table, fetch a specific cell from all tables in a file ## Summary of the problem Hey guys, I am currently keeping track of the stocks I buy and sell in org mode using tables. I have N different tables in a given file, each table representing a transaction. Each file spans a time period of one month. At the end of the file, I want to have a table that summarizes the grand total. So far I have been manually writing the remote links to all the different tables manually, but this clearly does not scale well. ### How I am doing it now ``` #+NAME: 1 | Company 1 | Pcs | Cost | Brokerage| Total | Date | |-----------+------+------+----------+-----------+------------| | BUY | 100 | 9.1 | 1.365 | 911.365 | 26.11.2021 | | SELL | 100 | 9.30 | 1.395 | 928.605 | 29.11.2021 | | | | | | 17.24 | | #+NAME: 2 | Company 2 | Pcs | Cost | Brokerage| Total | Date | |-----------+------+------+----------+-----------+------------| | BUY | 100 | 9.1 | 1.365 | 911.365 | 26.11.2021 | | SELL | 100 | 9.30 | 1.395 | 928.605 | 29.11.2021 | | | | | | 17.24 | | ... Many more tables with more companies, etc.. | GRAND TOTAL | 34.48 | #+TBLFM: $2=remote(1,@4$5)+remote(2,@4$5)+...remote(N,@4$5)...+remote(56,@4$5) ``` As can be seen, I have to manually write each remote statement, which does not scale well. ### What I have discovered so far I have discovered a function named `org-table-get-remote-range`, which I believe is a step in the right direction. ### How I want it to be ``` #+NAME: 1 | Company 1 | Pcs | Cost | Brokerage| Total | Date | |-----------+------+------+----------+-----------+------------| | BUY | 100 | 9.1 | 1.365 | 911.365 | 26.11.2021 | | SELL | 100 | 9.30 | 1.395 | 928.605 | 29.11.2021 | | | | | | 17.24 | | #+NAME: 2 | Company 2 | Pcs | Cost | Brokerage| Total | Date | |-----------+------+------+----------+-----------+------------| | BUY | 100 | 9.1 | 1.365 | 911.365 | 26.11.2021 | | SELL | 100 | 9.30 | 1.395 | 928.605 | 29.11.2021 | | | | | | 17.24 | | ... Many more tables with more companies, etc.. | GRAND TOTAL | 34.48 | #+TBLFM: $2=vsum(*some function that fetches all of the cells*) ``` As can be seen, I am looking for a function that automates the process of fetching/collecting all the tables and enables me to compute the sum of them. I would appreciate any feedback/input that puts me on the right track here, I am fairly new to org-mode and emacs (around 6 months). I would love if I was able to get emacs to solve this problem for me, as I tend to live in emacs anyways. Thanks guys! # Answer > 1 votes You can use `org-element-map` on a parsed buffer to select elements or objects of a given type to operate on with a function. Here's an example for getting the names of all the named tables in the buffer as a list: ``` (org-element-map (org-element-parse-buffer) 'table (lambda (tbl) (plist-get (cadr tbl) :name))) ``` If you evaluate this in a buffer which consists of your summary section e.g., it will return `("1" "2")`. See the documentation of `org-element-map` (`C-h f org-element-map`) for more details. You will just have to give it a more complicated function to get the items that you desire. I don't have time to get a complete solution together, but I hope this will help you along. --- Tags: org-mode, org-table, remote, formula ---
thread-43626
https://emacs.stackexchange.com/questions/43626
Can emacs run inside chrome?
2018-07-15T21:26:04.677
# Question Title: Can emacs run inside chrome? Can emacs be run in chrome? Like vim does at https://rhysd.github.io/vim.wasm/ # Answer Apparently, yes. It was talked about a couple of year ago: http://endlessparentheses.com/emacs-is-available-on-chromebook-and-chrome.html https://www.reddit.com/r/emacs/comments/311kpk/emacs\_runs\_natively\_on\_chrome/ I tried it briefly then, but it was not clear how to configure it, so it was more of a curiosity. There does not seem to be any recent developments. I, too, would be interested in seeing how to run and configure emacs 26.1 in a current Chrome. > 5 votes # Answer Yes. The Chrome app NaCL Development Enviroment includes Emacs. In addition, the changes were upstreamed into Emacs' configure.ac to add NaCL as a regular port. > 1 votes --- Tags: osx ---
thread-390
https://emacs.stackexchange.com/questions/390
Display PDF images in org-mode
2014-09-28T09:24:58.857
# Question Title: Display PDF images in org-mode *Note: This question was asked here before, with no success.* Org-mode’s ability to display inline images is fantastic for writing my weekly scientific reports. I can include graphs, link them with their data, link with the conclusions, and really harness the power of org-mode. The only problem I have is that org needs the images to use conventional image formats (jpeg, png, etc), while I prefer for my graphs to be in PDF. **How can I display inline pdf images in org-mode?** My final objective is to just write a link like this in org-mode: ``` [[file:~/Work/grap.pdf]] ``` And have it displayed inline just like it would happen if it were a png. *I know I could just have a copy of each graph in jpeg or something (which is what I do right now), but it’s slightly cumbersome and it always carries the risk of the pdf graph being updated and me forgetting to update the jpeg.* # Answer **NOTE**: You need to have ImageMagick installed on your system (`convert` executable) for this solution to work. # How this solution is implemented * The function `org-include-img-from-pdf` is the workhorse that does the PDF to Image format conversion using `convert`. * If the org file contains `# ()convertfrompdf:t`, it will be assumed that the user has a pdf file that they want to convert to an image file. The user should put the above *special comment* above the image file link as shown in the below example. * The image file type is determined by the file extension in the bracket link `[[./myimage.EXT]]`. * By adding the `org-include-img-from-pdf` function to the `before-save-hook`, that function is executed every time the user saves the file (See the elisp snippet following the function definition below). # Example setup In this example setup I have the following files: * An org file like below that includes an image file. * The pdf file `myimage.pdf`. ``` # ()convertfrompdf:t [[./myimage.png]] ``` # Function to auto convert pdf to image files ``` (defun org-include-img-from-pdf (&rest _) "Convert pdf files to image files in org-mode bracket links. # ()convertfrompdf:t # This is a special comment; tells that the upcoming # link points to the to-be-converted-to file. # If you have a foo.pdf that you need to convert to foo.png, use the # foo.png file name in the link. [[./foo.png]] " (interactive) (if (executable-find "convert") (save-excursion (goto-char (point-min)) (while (re-search-forward "^[ \t]*#\\s-+()convertfrompdf\\s-*:\\s-*t" nil :noerror) ;; Keep on going to the next line till it finds a line with bracketed ;; file link. (while (progn (forward-line 1) (not (looking-at org-bracket-link-regexp)))) ;; Get the sub-group 1 match, the link, from `org-bracket-link-regexp' (let ((link (match-string-no-properties 1))) (when (stringp link) (let* ((imgfile (expand-file-name link)) (pdffile (expand-file-name (concat (file-name-sans-extension imgfile) "." "pdf"))) (cmd (concat "convert -density 96 -quality 85 " pdffile " " imgfile))) (when (and (file-readable-p pdffile) (file-newer-than-file-p pdffile imgfile)) ;; This block is executed only if pdffile is newer than ;; imgfile or if imgfile does not exist. (shell-command cmd) (message "%s" cmd))))))) (user-error "`convert' executable (part of Imagemagick) is not found"))) ``` # Hook setup to specify when to run this function ``` (defun my/org-include-img-from-pdf-before-save () "Execute `org-include-img-from-pdf' just before saving the file." (add-hook 'before-save-hook #'org-include-img-from-pdf nil :local)) (add-hook 'org-mode-hook #'my/org-include-img-from-pdf-before-save) ;; If you want to attempt to auto-convert PDF to PNG only during exports, and not during each save. ;; (with-eval-after-load 'ox ;; (add-hook 'org-export-before-processing-hook #'org-include-img-from-pdf)) ``` --- Code + MWE > 17 votes # Answer There is now a package on melpa just for this purpose: **org-inline-pdf**. It is developed at github, where you also find usage information. https://github.com/shg/org-inline-pdf.el Note that this package needs the pdf2svg tool. Also orgmode 9.4 is a minimum requirement. > 3 votes --- Tags: org-mode, pdf, images ---
thread-69604
https://emacs.stackexchange.com/questions/69604
How to prevent the mode line color from changing after the buffer is switched?
2021-12-02T09:19:52.270
# Question Title: How to prevent the mode line color from changing after the buffer is switched? like this: The mode line color of the current buffer is darker, I hope the color will not change. # Answer > 3 votes The appearance of the mode-line is governed by two faces: `mode-line` and `mode-line-inactive`. The former has a `style` of `raised`, and the foreground/background colours are different. Just `M-x customize-face RET mode-line,mode-line-inactive RET` and adjust as desired. Note that in emacs-29 there will be a `mode-line-active` face as well which inherits from `mode-line`. --- Tags: faces, mode-line ---
thread-69597
https://emacs.stackexchange.com/questions/69597
How can I disable ***all*** VC/git awareness?
2021-12-01T18:34:09.327
# Question Title: How can I disable ***all*** VC/git awareness? Even when I start Emacs without any initialization file, it is still aware of version control. (For example, if I visit a `git`-controlled file, the modeline will say something like "Git:some-branch".) Is there a convenient way to disable ***all*** VC/git awareness? The goal is to make Emacs' behavior entirely independent of whether a file is under version control or not. # Answer > 3 votes `vc` is the package that handles version control for Emacs. You can disable it by customizing `vc-handled-backends` to nil: ``` vc-handled-backends is a variable defined in `vc-hooks.el'. Its value is (Git) Original value was (RCS CVS SVN SCCS SRC Bzr Git Hg Mtn) List of version control backends for which VC will be used. Entries in this list will be tried in order to determine whether a file is under that sort of version control. Removing an entry from the list prevents VC from being activated when visiting a file managed by that backend. An empty list disables VC altogether. ``` --- Tags: git, version-control ---
thread-69608
https://emacs.stackexchange.com/questions/69608
Function argument does not seem to be visible inside of function
2021-12-02T12:51:19.373
# Question Title: Function argument does not seem to be visible inside of function I use this code (found here) to highlight a single line in black: ``` (defun find-overlays-specifying (prop pos) (let ((overlays (overlays-at pos)) found) (while overlays (let ((overlay (car overlays))) (if (overlay-get overlay prop) (setq found (cons overlay found)))) (setq overlays (cdr overlays))) found)) (defun highlight-or-dehighlight-line () (if (find-overlays-specifying 'line-highlight-overlay-marker (line-beginning-position)) (remove-overlays (line-beginning-position) (+ 1 (line-end-position))) (let ((overlay-highlight (make-overlay (line-beginning-position) (+ 1 (line-end-position))))) (overlay-put overlay-highlight 'face '(:background "black")) (overlay-put overlay-highlight 'line-highlight-overlay-marker t)))) (global-set-key [f9] (lambda () (interactive) (highlight-or-dehighlight-line))) ``` Now I want to make it more generic because I want to be able to use a few different colors. So I added a parameter `color` to function `highlight-or-dehighlight-line`, replaced `"black"` with `color`, and passed `"black"` to `highlight-or-dehighlight-line`: ``` (defun find-overlays-specifying (prop pos) (let ((overlays (overlays-at pos)) found) (while overlays (let ((overlay (car overlays))) (if (overlay-get overlay prop) (setq found (cons overlay found)))) (setq overlays (cdr overlays))) found)) (defun highlight-or-dehighlight-line (color) (if (find-overlays-specifying 'line-highlight-overlay-marker (line-beginning-position)) (remove-overlays (line-beginning-position) (+ 1 (line-end-position))) (let ((overlay-highlight (make-overlay (line-beginning-position) (+ 1 (line-end-position))))) (overlay-put overlay-highlight 'face '(:background color)) (overlay-put overlay-highlight 'line-highlight-overlay-marker t)))) (global-set-key [f9] (lambda () (interactive) (highlight-or-dehighlight-line "black"))) ``` However, this does not seem to do anything and I cannot find my mistake. What's wrong with this code? # Answer The mistake is here: `'(:background color)`. This is quoted, so it is simply treated literally. The result is a list containing two elements, the keyword `:background` and the symbol `color`. One solution is to use a backquote, or quasi–quote, so that you can interpolate values into the list: ``` `(:background ,color) ``` Another solution is to call a function instead, since the arguments to the function will be evaluated: ``` (list :background color) ``` The first is more idiomatic, but both will get you a list containing the keyword `:background` followed by the value assigned to the variable named `color`, rather than the literal symbol `color`. See chapter 10.4 Backquote in the Emacs Lisp manual. You can open the Info viewer inside of Emacs to read this manual with `C-h i`. > 2 votes --- Tags: quote, backquote ---
thread-69607
https://emacs.stackexchange.com/questions/69607
How to disable momentary highlighting of a match by ggtags?
2021-12-02T10:51:57.163
# Question Title: How to disable momentary highlighting of a match by ggtags? When I call gtags-find-tag-dwim, matches item will be highlighted for about one second. Like this: Please note that `ggtags-highlight-tag` has absolutely nothing to do with this highlight, I believe this is caused by another mysterious problem. # Answer > 1 votes `ggtags-find-tag-dwim` relies on `compilation-mode` to jump to the determined location. The variable that controls how (and if) `compilation-mode` highlights locations is `next-error-highlight`. Setting it to `nil` will disable the highlighting. --- Tags: highlighting, ggtags ---
thread-26845
https://emacs.stackexchange.com/questions/26845
Org Mode Babel - Interactive code block evaluation in Python
2016-09-05T09:44:51.590
# Question Title: Org Mode Babel - Interactive code block evaluation in Python Similarly to this question I would like to evaluate (in org mode) Python source code blocks containing "input" instructions but I can't find a way to have an interactive evaluation (with user input) during evaluation or to give it some input known in advance (stored in a file for instance). My constraint is to use explicitly the `input` instruction since all this should be included in a textbook for students. Example of code : ``` #+BEGIN_SRC python :results output a= input("Value") print(a) #+END_SRC ``` Is it possible to have such an interactive evaluation or to simulate it (by giving to the source code a fake input) ? # Answer Here is an alternative approach that uses a non-exported, tangled file to replace the input function. ``` #+BEGIN_SRC python :session :exports none :tangle example1.py def input(x): if x == 'Value of a': return 3 elif x == 'Value of b': return 4 #+END_SRC #+RESULTS: ``` > **Tip:** Press `C-c``C-v``t` or use the `M-x``org-babel-tangle` command to create, i.e. tangle, the `example1.py` file. --- ``` #+BEGIN_SRC python :results output :preamble from example1 import * a = input('Value of a') b = input('Value of b') print(a + b) #+END_SRC #+RESULTS: : 7 ``` > **Note:** The `example1.py` file that was created from the previous python `SRC` block will be imported into the current block using the builtin :preamble header and the value `from example1 import *`. > 9 votes # Answer # Evaluate `python` code blocks using literate programming in org-mode. ## Use `:var` header to assign variables and test your code. > Note: If desired use `elisp` `(read-string "Prompt: ")` and `(read-number "Prompt: ")` to prompt for user input inside emacs. --- ### Example 1 - *print(a)* * Assign `hello world` to `a`. --- ``` #+name: ex1-code #+header: :var a="hello world" #+begin_src python :results verbatim replace output :exports results print(a) #+end_src #+begin_src python :eval never :exports code :noweb yes a = input('Value of a') <<ex1-code>> #+end_src #+results: ex1-code : hello world ``` --- ### Example 2 - `print(a + b)` * Assign `1` to `a`. * Assign `2` to `b`. --- ``` #+name: ex2-code #+header: :var a=1 #+header: :var b=2 #+begin_src python :results replace output :exports results print(a + b) #+end_src #+begin_src python :eval never :exports code :noweb yes a = input('Value of a') b = input('Value of b') <<ex2-code>> #+end_src #+results: ex2-code : 3 ``` --- ### Example 3 - `print(a,b,c)` * When prompted for `Value of a` enter `Thanks` * When prompted for `Value of b` enter `4`. * When prompted for `Value of c` enter `your question`. --- ``` #+NAME: ex3-code #+header: :var a=(read-string "Value of a ") #+header: :var b=(read-number "Value of b ") #+header: :var c=(read-string "Value of c ") #+begin_src python :results replace output :exports results print a,b,c #+end_src #+begin_src python :eval never :exports code :noweb yes a = input('Value of a') b = input('Value of b') c = input('Value of c') <<ex3-code>> #+end_src #+results: ex3-code : Thanks 4 your question ``` --- > When you export your org file, the output should look similar to the example below --- Example 1 - `print(a)` * Assign `hello world` to `a`. ``` a = input('Value of a') print(a) hello world ``` Example 2 - `print(a + b)` * Assign `1` to `a`. * Assign `2` to `b`. ``` a = input('Value of a') b = input('Value of b') print(a + b) 3 ``` Example 3 - `print(a,b,c)` * When prompted for `Value of a` enter `Thanks` * When prompted for `Value of b` enter `4`. * When prompted for `Value of c` enter `your question`. ``` a = input('Value of a') b = input('Value of b') c = input('Value of c') print a,b,c Thanks 4 your question ``` --- --- > This code was tested with > GNU Emacs 24.5.1 (x86\_64-unknown-cygwin, GTK+ Version 3.14.13) > Org-Mode Version: 8.3.2 > and github. > 8 votes # Answer I don't think it is possible to get truly interactive Python input with org-babel. You could use a preamble to redefine the input function so it returns what you want to simulate the use of input, e.g. here we make it look like the user typed in "3". ``` #+BEGIN_SRC python :results output :preamble def input(x): return 3 a = input("value ") print(a) #+END_SRC #+RESULTS: : 3 ``` Depending on what students see that is exported, they might not see that you have done this. > 6 votes # Answer As a complement of John Kitchin's solution, I propose to use a generator to provide the successive values that will "feed" the `input(...)` functions and to return a `str`object systematically. ``` #+BEGIN_SRC python :session :exports none :tangle example2.py :results none def generate(lst): for element in lst: yield str(element) generator = generate(["Thanks",4,"your help"]) def input(x): return generator.__next__() #+END_SRC #+BEGIN_SRC python :results output :preamble from example2 import * :exports both a = input('Value of a') b = input('Value of b') c = input('Value of c') print(a,b,c) #+END_SRC ``` > 2 votes # Answer Another way is to use tkinter and to input the value in an external window: ``` #+name: tkinput #+begin_src python :results output :exports none from tkinter.simpledialog import askstring from tkinter import Tk def input(message): root = Tk() root.withdraw() entered = askstring("", message) root.destroy() return entered #+end_src #+name: test-tkinput #+begin_src python :results output :exports code :noweb strip-export <<tkinput>> x = input("Test1") y = input("Test2") print(x,y) #+end_src ``` > 0 votes --- Tags: org-mode, org-babel ---
thread-69603
https://emacs.stackexchange.com/questions/69603
Change font for org LaTeX-preview
2021-12-02T06:51:20.573
# Question Title: Change font for org LaTeX-preview I successfully use org LaTeX-preview to have my formulas displayed as images in my org-mode documents. There is one problem I am facing, though: I need the LaTeX math font to be upright instead of slanted. This is easily solved in an ordinary LaTeX-document by adding `\usepackage[math-style=upright]{unicode-math}`. For some reason, I have trouble getting it to work with LaTeX preview. This is my package specification for preview images: ``` (setq org-latex-packages-alist '( ("" "amssymb" t) ("" "turnstile" t) ; for Turnstiles ("" "centernot" t) ; for striked through Turnstiles ("" "mathpartir" t) ; for inference patterns ("math-style=upright" "unicode-math" t) ; for upright Math font )) ``` If I understand how `org-latex-packages-to-string` works, the above specification should produce the desired result. I even manually added "\usepackage\[math-style=upright\]{unicode-math}" to `org-format-latex-header`: ``` (setq org-format-latex-header "\\documentclass{article} \\usepackage[usenames]{color} \[PACKAGES] \[DEFAULT-PACKAGES] \\usepackage[math-style=upright]{unicode-math} % added package \\pagestyle{empty} % do not remove % The settings below are copied from fullpage.sty \\setlength{\\textwidth}{\\paperwidth} \\addtolength{\\textwidth}{-3cm} \\setlength{\\oddsidemargin}{1.5cm} \\addtolength{\\oddsidemargin}{-2.54cm} \\setlength{\\evensidemargin}{\\oddsidemargin} \\setlength{\\textheight}{\\paperheight} \\addtolength{\\textheight}{-\\headheight} \\addtolength{\\textheight}{-\\headsep} \\addtolength{\\textheight}{-\\footskip} \\addtolength{\\textheight}{-3cm} \\setlength{\\topmargin}{1.5cm} \\addtolength{\\topmargin}{-2.54cm}" ) ``` This did not work either. Do you have an idea what I can do to have the LaTeX-fragments displayed upright instead of slanted? **Edit:** The value of `org-preview-latex-process-alist` is ``` ((dvipng :programs ("latex" "dvipng") :description "dvi > png" :message "you need to install the programs: latex and dvipng." :image-input-type "dvi" :image-output-type "png" :image-size-adjust (1.0 . 1.0) :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f") :image-converter ("dvipng -D %D -T tight -bg Transparent -o %O %f")) (dvisvgm :programs ("latex" "dvisvgm") :description "dvi > svg" :message "you need to install the programs: latex and dvisvgm." :image-input-type "dvi" :image-output-type "svg" :image-size-adjust (1.7 . 1.5) :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f") :image-converter ("dvisvgm %f -n -b min -c %S -o %O")) (imagemagick :programs ("latex" "convert") :description "pdf > png" :message "you need to install the programs: latex and imagemagick." :image-input-type "pdf" :image-output-type "png" :image-size-adjust (1.0 . 1.0) :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f") :image-converter ("convert -density %D -trim -antialias %f -quality 100 %O"))) ``` Also, I have `(setq org-latex-create-formula-image-program 'dvipng)` in my .init file. This is why the value of `org-preview-latex-default-process` is `dvipng`. # Answer Thanks to d125q's comments, I solved the issue. It was twofold: First and foremost, unicode-math is a package which only works with XeTeX or LuaTeX, but org by default compiles with LaTeX. This is why you need the preview images to be generated by XeTeX or LuaTeX. This is my configuration: ``` (setq org-preview-latex-process-alist '((dvipng :programs ("lualatex" "dvipng") :description "dvi > png" :message "you need to install the programs: latex and dvipng." :image-input-type "dvi" :image-output-type "png" :image-size-adjust (1.0 . 1.0) :latex-compiler ("lualatex -output-format dvi -interaction nonstopmode -output-directory %o %f") :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f")) (dvisvgm :programs ("latex" "dvisvgm") :description "dvi > svg" :message "you need to install the programs: latex and dvisvgm." :use-xcolor t :image-input-type "xdv" :image-output-type "svg" :image-size-adjust (3 . 1.5) :latex-compiler ("xelatex -no-pdf -interaction nonstopmode -output-directory %o %f") :image-converter ("dvisvgm %f -n -b min -c %S -o %O")) (imagemagick :programs ("latex" "convert") :description "pdf > png" :message "you need to install the programs: latex and imagemagick." :use-xcolor t :image-input-type "pdf" :image-output-type "png" :image-size-adjust (1.0 . 1.0) :latex-compiler ("xelatex -no-pdf -interaction nonstopmode -output-directory %o %f") :image-converter ("convert -density %D -trim -antialias %f -quality 100 %O")))) ``` I copied it off from here and am open for any suggestions (the images are generated more slowly than before). Secondly, LuaTeX requires org-latex-preview to generate .dvi images (instead of .png or .pdf files). You can configure this by adding `(setq org-preview-latex-default-process 'dvisvgm)` to your .init file. But caution: You need the dvisvgm dependency, which ships with `latex-extra-utils`, as well as an emacs build capable of dealing with svg files. This usually is the case, but especially if you build it from source like me, you need to double-check to (1) have `librsvg2-dev` installed and (2) use `--with-rsvg` in `./configure`. If those two points are solved, org-latex-preview should compile the images with LuaTeX and thus be able to use the `unicode-math` package when generating the preview image if you add it to `org-latex-packages-alist`, for example by adding `(add-to-list 'org-latex-packages-alist '("math-style=upright" "unicode-math" t))` to your .init file. > 0 votes --- Tags: org-mode, latex, preview-latex, latex-header ---
thread-17319
https://emacs.stackexchange.com/questions/17319
JSON major mode complaining about valid JSON file
2015-10-12T16:27:17.193
# Question Title: JSON major mode complaining about valid JSON file I am editing a dead simple JSON file: ``` { "foo": "bar" } ``` Here's what I see: Doing a `C-h m` I see the following minor modes running alongside JSON mode: ``` Enabled minor modes: Auto-Composition Auto-Compression Auto-Encryption Column-Number File-Name-Shadow Font-Lock Global-Font-Lock Global-Hl-Line Global-Linum Js2 Line-Number Linum Mouse-Wheel Openwith Tool-Bar Tooltip Transient-Mark ``` The following problem is reported when the cursor is on `:` character: ``` missing ; before statement ``` The entire `"bar"` string value is also highlight red. Is the problem related to `js-lint` running alongside JSON? # Answer > 3 votes I have the same problem. Turns out I'm using js2-mode as minor-mode for js-mode ``` (add-hook 'js-mode-hook 'js2-minor-mode) ``` Everything is ok after remove above code from my .emacs.el Another option is to add js2-minor-mode only if it's not json-mode ``` (add-hook 'js-mode-hook '(lambda () (unless (eq major-mode 'json-mode) (js2-minor-mode)))) ``` --- Tags: json ---
thread-69600
https://emacs.stackexchange.com/questions/69600
How can I enable electric indentation for all modes except some?
2021-12-01T21:01:44.933
# Question Title: How can I enable electric indentation for all modes except some? I am trying to enable electric-indent-mode for all modes except fundamental-mode, where it is just annoying. In my init file, I have the following: ``` (electric-indent-mode +1) (add-hook 'after-change-major-mode-hook (lambda () (if (eq major-mode 'fundamental-mode) (electric-indent-mode -1)))) ``` This, however always disables electric-indent-mode because the value of major-mode is always 'fundamental-mode when the hook is invoked. Seems that the value of that variable is changed AFTER the hook is called? Makes no sense to me. Anyone have a suggestion on how to achieve this? There is no fundamental-mode-hook unfortunately. # Answer `electric-indent-mode` is a global mode, so if your function *ever* gets invoked, it will disable it everywhere. You then also have the problem that if the global mode is enabled, new buffers which are never given a new major mode at all will have that behaviour, because the hook you're using never runs. `electric-indent-local-mode` is the equivalent buffer-local minor mode, so I think you should *disable* the global mode, and instead *enable* the local mode everywhere you want it, which you can do using much the same technique you've shown in your question. ``` (electric-indent-mode 0) (add-hook 'after-change-major-mode-hook #'my-electric-indent-local-mode-maybe) (defun my-electric-indent-local-mode-maybe () "Enable `electric-indent-local-mode' if appropriate." (unless (eq major-mode 'fundamental-mode) (electric-indent-local-mode 1))) ``` I'll add that the local mode turns out to be a hack of the global mode, such that as far as `describe-mode` is concerned it's the global mode which is active or inactive on a per-buffer basis. This is pretty confusing when testing :) --- You could alternatively do this: ``` (defun my-electric-indent-rules (_char) "Used with `electric-indent-functions'." (when (eq major-mode 'fundamental-mode) (setq electric-indent-inhibit t) ;; Prevent future attempts. 'no-indent)) ;; Deny the current attempt. (add-hook 'electric-indent-functions #'my-electric-indent-rules) ``` I don't recommend it for your case though, because it's having to process things every time it might need to indent something, as opposed to configuring the behaviour once per buffer. (Thanks to Andrew Swann for pointing out that we could make this latter approach more efficient in the `fundamental-mode` case by also setting `electric-indent-inhibit`.) > 2 votes # Answer Instead of toggling the `electric-indent-mode` directly you can set the variable `electric-indent-inhibit`: ``` (electric-indent-mode t) (add-hook 'after-change-major-mode-hook (lambda () (if (eq major-mode 'fundamental-mode) (setq electric-indent-inhibit t)))) ``` This variable is buffer local. > 1 votes --- Tags: init-file, hooks, major-mode, electric-indent ---
thread-5465
https://emacs.stackexchange.com/questions/5465
How to migrate Markdown files to Emacs org mode format
2014-12-17T01:52:27.940
# Question Title: How to migrate Markdown files to Emacs org mode format I've got hundreds of personal notes stored as files in Markdown format, after several years using the VoodooPad personal wiki software for OS X. There's plenty of information available for exporting from org mode to Markdown, but is there an easy way to convert Markdown to org mode format? --- **Update** Thanks to user2619203's answer and this answer to a question on batch processing of files with Pandoc I was able to convert four hundred Markdown files into org mode format in just a few minutes. The solution was to export the VoodooPad document to a folder as text (**File** \> **Export Document** \> **Export as Text...**). Then call `pandoc` via the `find` command to convert them all in one go: ``` $ find . -name \*.txt -type f -exec pandoc -f markdown -t org -o {}.org {} \; ``` The converted .org files I've looked at are formatted beautifully -- even the codeblocks and format styling. Thank-you, user2619203. To simply convert one file from Markdown to Org the following command can be used: `pandoc -f markdown -t org -o newfile.org original-file.markdown` Here is a link to the Pandoc documentation # Answer > 55 votes Pandoc can convert between multiple document formats. To convert a bunch of Markdown files to org-mode: ``` for f in `ls *.md`; do pandoc -f markdown -t org -o ${f}.org ${f}; done ``` # Answer > 6 votes Here is an emacs function that will convert the current buffer's content to orgmode format using pandoc: ``` (defun markdown-convert-buffer-to-org () "Convert the current buffer's content from markdown to orgmode format and save it with the current buffer's file name but with .org extension." (interactive) (shell-command-on-region (point-min) (point-max) (format "pandoc -f markdown -t org -o %s" (concat (file-name-sans-extension (buffer-file-name)) ".org")))) ``` # Answer > 5 votes Try this new cool package: org-pandoc-import. # Answer > 0 votes A modification of the answer provided by the author that has the benefit of renaming `.md` files to `.org`, instead of to `.md.org`: ``` fd . -I --extension=md --type=f --exec bash -c 'pandoc -f markdown -t org -o "${1%.md}".org "$1"' - '{}' \; ``` Edit: this works by passing `'pandoc ...'` to bash as a command string through `bash -c`, which gives more flexibility than `--exec pandoc ...` in terms of string processing in this case. --- Tags: org-mode, markdown ---
thread-69582
https://emacs.stackexchange.com/questions/69582
same files.el.gz, different auto-mode-alist
2021-12-01T08:16:31.480
# Question Title: same files.el.gz, different auto-mode-alist Two Debian systems with different history of apt-based and local software installations. On one system, `cmake-mode` works, on the other not, though file `/usr/local/share/emacs/site-lisp/cmake-mode.el` is present on both systems. On one system, variable `auto-mode-alist` contains rules for CMake, on the other system not. Via `C-h v auto-mode-alist` we are told that `"auto-mode-alist is a variable defined in ‘files.el’"`, with the link pointing to `/usr/share/emacs/27.1/lisp/files.el.gz`. So the difference comes from that file? No, that file is identical on both systems, and does *not* contain any rule for CMake. Questions thus: By what mechanism are additional rules written to variable `auto-mode-alist`? What could have gone wrong on the system that does not support `cmake-mode`? # Answer > 1 votes I don't know how Debian does things, but... `auto-mode-alist` is a variable, and (as with any variable) any and all elisp code may modify that value. files.el merely defines its default value. What happens after that is up to the rest of the system. For this particular variable, it's entirely expected for elisp libraries which add support for some file type to add to `auto-mode-alist`. As it's simply a list there are lots of ways to manipulate it, but it's commonly done with `add-to-list`. > file `/usr/local/share/emacs/site-lisp/cmake-mode.el` is present on both systems. The file being present on the filesystem doesn't necessarily mean that Emacs has loaded it. Does `M-x` `load-library` `RET` `cmake-mode` `RET` make a difference? I don't know how Debian manages elisp packages, but the first thing I would look for is a `site-start.el` and/or `default.el` file in the `site-lisp` directory, as I'd expect whatever it does to be controlled from those. --- Tags: auto-mode-alist ---