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-61444
|
https://emacs.stackexchange.com/questions/61444
|
Prevent screen splitting by julia-repl
|
2020-10-27T17:32:38.013
|
# Question
Title: Prevent screen splitting by julia-repl
I want to prevent `julia-repl` from splitting my screen, which seems like a common request given the numbers of questions I have found relating to this. Drawing on advice found here and here, I came up with the following code for my `init.el`:
```
(setq display-buffer-alist
'((".*" (display-buffer-reuse-window display-buffer-same-window))))
(setq display-buffer-reuse-frames t)
(setq pop-up-windows nil)
```
And yet when I open Emacs (`emacs`) and start `julia-repl` (`M+x julia-repl`), it **still** splits the window. My understanding is that the regex in the first command should catch *all* buffers and prevent splitting.
I also tried,
```
(add-to-list 'display-buffer-alist
'(".*". (display-buffer-reuse-window .
((reusable-frames . t)))))
```
from here, too, without any success. What am I doing wrong here? Is this a quirk of `julia-repl` since the standard solutions don't work?
# Answer
> 1 votes
I assume you're referring to this piece of code: https://github.com/tpapp/julia-repl/blob/d073acb6339e99edf77833f82277afd9a076f16a/julia-repl.el#L449-L454
It doesn't use `display-buffer` internally, so customizations to `display-buffer-alist` have no effect. Ask the developer to replace `switch-to-buffer-other-window` with `pop-to-buffer` or better, hand in a pull request. In the meantime redefine the command in your init file as follows:
```
(with-eval-after-load 'julia-repl
(defun julia-repl ()
"..."
(interactive)
(pop-to-buffer (julia-repl-inferior-buffer))))
```
---
Tags: window-splitting
---
|
thread-60973
|
https://emacs.stackexchange.com/questions/60973
|
Is it possible to archive org-mode agenda entries from a given date range?
|
2020-10-03T14:05:01.297
|
# Question
Title: Is it possible to archive org-mode agenda entries from a given date range?
My emacs org-mode agenda files are steadily growing, and many of my projects span several to many years. In addition, I need to last access the entries after about a year. Hence rather than (or in addition to) archiving my agenda entries per project, I would like to archive all my agenda entries from a given date range, for example (half) a calendar year. Is this possible somehow? Since I need to do this once or twice a year, it isn't too bad if I need more than a few keystrokes for this action (which I could stick in a macro anyway). Even if the solution would only work for a given month or calendar year, rather than any random date range, it would help me.
My work agenda file has a structure like below. I would like that structure to be kept in the archive file, in case I ever need to figure out how much time I spent on a given project or on all my teaching years later.
```
* Research
** Project 1
*** Task 1 (with timestamp below)
<2023-07-19 Wed 11:40>
*** Task 2
<2023-07-19 Wed 11:41>
*** Etc
** Project 2
*** More tasks with timestamps
** Project N
* Teaching
** Class 1
*** Even more tasks with timestamps
** Class 2
*** More tasks with timestamps
```
# Answer
I created a command-line tool written in Python called `org-agenda-archive` that (crudely) does what I wanted and published it on GitHub.
> 0 votes
---
Tags: org-mode, org-agenda
---
|
thread-56185
|
https://emacs.stackexchange.com/questions/56185
|
Reference a window with a designated name
|
2020-03-17T07:24:39.650
|
# Question
Title: Reference a window with a designated name
I list the current windows with
```
#+begin_src emacs-lisp :tangle yes
(window-list)
#+end_src
#+RESULTS:
| #<window 14 on 28.Windows.org> | #<window 3 on .emacs.d> |
```
Then I tried to operate one of them with
```
(split-window '#<window 14 on 28.Windows.org>)
```
but get the error:
```
Symbol’s value as variable is void: on
```
Tried alternatively
```
(split-window #<window 14 on 28.Windows.org>)
(split-window <window 14 on 28.Windows.org>)
```
Report the same error,
How could I reference a window by a designated name?
# Answer
What Org emits here is a printed representation of an otherwise opaque window object. While you can serialize a window to a string, you cannot go back from the string to the window. You can recognize such data types by their printed representation looking like `#<...>`, see https://www.gnu.org/software/emacs/manual/html\_node/elisp/Printed-Representation.html for further details.
This doesn't mean that you can't do meaningful things with windows though. For example the following works just fine:
```
#+begin_src emacs-lisp :tangle yes
(split-window (selected-window))
#+end_src
#+RESULTS:
: #<window 38>
```
> 4 votes
# Answer
If you use Icicles then you can use command `icicle-select-window` to switch to windows by name, using completion.
> **`icicle-select-window`** is an interactive compiled Lisp function in `icicles-cmd1.el`.
>
> `(icicle-select-window)`
>
> Select window by its name.
>
> With no prefix arg, candidate windows are those of the selected frame.
>
> With a prefix arg:
>
> * Non-negative means windows of all visible frames are candidates.
> * Negative means windows of all frames are candidates (i.e., including iconified and invisible frames).
>
> A window name is the name of its displayed buffer, but suffixed as needed by `[`*`NUMBER`*`]`, to make the name unique. For example, if you have two windows showing buffer *Help*, one of the windows will be called `*Help*[2]` for use with this command.
> 2 votes
# Answer
Build on the icicle answer you can do that without including this big library with that function:
```
(defun MY/select-window-by-name (name)
"Selects the window with buffer NAME"
(select-window
(car (seq-filter
(lambda (window)
(equal name (buffer-name (window-buffer window))))
(window-list-1 nil 0 t)))))
```
> 2 votes
---
Tags: window, frames
---
|
thread-57498
|
https://emacs.stackexchange.com/questions/57498
|
How to hide TODO state and Priority in org-agenda-custom-command?
|
2020-03-31T17:40:20.200
|
# Question
Title: How to hide TODO state and Priority in org-agenda-custom-command?
I do not want TODO states ("TODO, DONE") and priorities ("\[#A\]") for tasks to be displayed in one of my custom agenda views. I have not been able to find any settings that would accomplish this. Is there any way this can be achieved?
Ideally, I would like to be able to toggle the visibility of TODO states and priorities separately.
# Answer
You could postprocess `org-agenda-format-item` and add your own trimming function. Here is an example that removes my(!) todo keywords and strips the priority down to just one letter:
```
(defun myTrim (s)
; remove todo keyword and trimp priorities to just one letter
(replace-regexp-in-string
"[]#[]" ""
(replace-regexp-in-string "\\(TD\\|NX\\|WT\\|DN\\) " "" s)))
```
Adjust this to your needs. Then you can turn the stripping off and on by adding or removing the advice:
```
(advice-add 'org-agenda-format-item :filter-return #'myTrim)
(advice-remove 'org-agenda-format-item #'myTrim)
```
I am pretty sure this will break *something*. I lost the fontification of the priority, but you wanted to remove the priority entirely, so this won't hurt you. Sorting by priority is probably also endangered.
> 0 votes
# Answer
TODO states may be modified in agenda views by setting the org-agenda-todo-keyword-format variable. To hide the TODO state entirely, use the following line in a org agenda custom command:
```
(org-agenda-todo-keyword-format "")
```
Documentation: org-agenda-todo-keyword-format is a variable defined in ‘org-agenda.el’. Format for the TODO keyword in agenda lines. Set this to something like "%-12s" if you want all TODO keywords to occupy a fixed space in the agenda display.
I have not found a way to hide priorities yet.
> 2 votes
---
Tags: org-mode, org-agenda
---
|
thread-61403
|
https://emacs.stackexchange.com/questions/61403
|
Emacs transparent after fresh install
|
2020-10-23T21:25:58.303
|
# Question
Title: Emacs transparent after fresh install
Complete emacs beginner here. Just installed emacs in my Manjaro (awesomewm edition) machine using pacman.
The emacs window is almost completely transparent, I can't read anything. If started from a terminal, it raises these errors:
```
(emacs:4193): Gtk-CRITICAL **: 23:20:57.211: _gtk_css_image_get_concrete_size: assertion 'default_width > 0' failed
(emacs:4193): Gtk-CRITICAL **: 23:20:57.211: _gtk_css_image_get_surface: assertion 'surface_width > 0' failed
(emacs:4193): Gtk-CRITICAL **: 23:20:57.211: _gtk_css_image_get_concrete_size: assertion 'default_width > 0' failed
(emacs:4193): Gtk-CRITICAL **: 23:20:57.211: _gtk_css_image_get_surface: assertion 'surface_width > 0' failed
(emacs:4193): Gtk-CRITICAL **: 23:20:57.211: _gtk_css_image_get_concrete_size: assertion 'default_width > 0' failed
(emacs:4193): Gtk-CRITICAL **: 23:20:57.211: _gtk_css_image_get_surface: assertion 'surface_width > 0' failed
```
Any clues on what's wrong?
Screenshot:
Note: also tried installing emacs with another package manager (guix) as a foreign package manager. Still got the same problem.
# Answer
> 1 votes
Welcome Soap!
This seems unrelated to Emacs. I guess it could be related to your window manager (AwesomeWM), some kind of X11 compositor like Compton or the configuration files associated with those.
Try to add the following to your `init.el`.
`(add-to-list 'default-frame-alist '(alpha 100))`
---
Tags: debugging, start-up, gtk3
---
|
thread-47389
|
https://emacs.stackexchange.com/questions/47389
|
How to programmatically export org buffer to html ( mimic the org mode sequence `C-c C-e h o` )?
|
2019-01-24T19:10:08.443
|
# Question
Title: How to programmatically export org buffer to html ( mimic the org mode sequence `C-c C-e h o` )?
**In brief:**
I would like to **programmatically** mimic the org mode sequence `C-c C-e h o` to export a buffer to HTML and open the web browser.
**My scenario:**
* I have a written a shell-command (in my code snippet below, this command is remplaced by the simple `"more"` command) that processes the current buffer file (the `(buffer-file-name)` part).
* the shell command (here "more") generates an org mode compatible output and stores it in `new_buffer`.
* **my problem:** I want to export this `new_buffer` into an html file and open the browser (like the manual `C-c C-e h o` sequence).
* then I kill the temporary new\_buffer
-\> I do not know how to do that. For the moment I use `org-html-export-as-html`, however this function simply exports the created `new_buffer` into a new `*Org HTML Export*` buffer.
What I have done so far (with my brittle emacs-lisp knowledge):
```
(defun generate_html()
(interactive)
(let ((new_buffer (generate-new-buffer (concat (buffer-file-name) ".org"))))
(shell-command (concat "more " (buffer-file-name)) new_buffer)
(org-html-export-as-html ) ;; <-- what to do here to mimic C-c C-e h o ?
(kill-buffer new_buffer)))
```
# Answer
> 2 votes
My org-mode version is 9.4, Emacs version is 25.1.50.1.
I'd do
```
(org-open-file (org-html-export-to-html))
```
to programmatically export the org buffer to html and open it in a browser.
I looked for the definition function `org-html-export-to-html` and looked around in the same file, stopping where the shortcut menu is defined:
```
(?o "As HTML file and open"
(lambda (a s v b)
(if a (org-html-export-to-html t s v b)
(org-open-file (org-html-export-to-html nil s v b)))))
```
With `trace-function` of `org-html-export-to-html` I saw that its arguments were all nil, and as the whole arglist is optional, it may be omitted.
# Answer
> 1 votes
Looks like you'll need to define your own command to do it. If you look in `ox-html.el` and search for "`:menu-entry`" (on my machine \[Org 9.0.9\], it's on line 105), you'll see that `C-c C-e h H` and `C-c C-e h h` point to commands in `ox-html.el`, but `C-c C-e h o` is implemented via a lambda function that you'll have to reproduce. No idea why it was done differently than the other options.
# Answer
> 1 votes
The solution to my alternative issue (I used pandoc, more below) may apply to your's as well.
I was looking for a CGI-based approach to render org files in the browser, thus implicitly publishing them on the fly. This would allow me to work with the org files without having to actively publish them.
In the past, I took a lot of notes using ReStructured Text and later AsciiDoc. I had implemented a solution for each of the formats, but ended up with this handy Perl-based script that would do the conversion on the fly. AsciiDoc, MarkDown and ReStructured Text are covered, but org gave me a headache as I simply could not render the result of `org-html-export-as-html`.
When invoking
```
emacs <source.org> --batch --kill -l ~/.emacs -f org-html-export-to-html
```
on the terminal, a file `source.html` is generated, but when I put the command in my CGI:
```
emacs <source.org> --batch --kill -l ~/.emacs -f org-html-export-to-html && cat source.html
```
it did not come up. This wasn't anyway what I wanted, as an HTML file would have been generated.
I did not find a way of making Emacs redirect the result of `org-html-export-as-html` to stdout in batch mode. All in all, the whole thing seemed too complicated, until I looked for an alternative way of converting org to html: https://pandoc.org/.
Now I have a single sgml.pl that will convert all these formats on the fly to HTML and thus can be used as a CGI for viewing them on the browser.
This is circumventing Emacs and should therefore perhaps not belong to this forum. I apologise.
Let me know if you're interested in the code.
Best,
Denis
Ok, since I have been asked (I hope this helps):
The below CGI works for both Apache2 and Nginx.
Just to recap,
In Apache2, a handler is defined:
```
<IfModule mod_actions.c>`
Action convert-sgml /cgi/sgml.pl`
AddHandler convert-sgml .adoc .md .org .rst .txt`
...
</IfModule>
```
In Nginx:
```
location ~ \.(adoc|md|org|rst|txt)$ {`
fastcgi_param PATH_TRANSLATED $document_root$document_uri;`
rewrite ^(.+\.)(adoc|md|org|rst|txt)$ /cgi-bin/sgml.pl?$document_root$document_uri last;`
...
}
```
The actual CGI code (pandoc does not convert *into* AsciiDoc, hence using asciidoctor):
```
#! /usr/bin/perl
# Obtain the server software from the signature (Apache/nginx),
# in order to determine which environment variable will have
# the name of the file to be converted.
$ENV{'SERVER_SOFTWARE'}=~/^([A-Za-z]+)/;
my $serverName=$&;
my %httpd=(
'Apache','PATH_TRANSLATED'
,'nginx','QUERY_STRING'
);
my $input=$ENV{$httpd{$serverName}};
my $ext=$input;
# Determine the file type (asciidoc/markdown/org/restructured text)
# and choose the corresponding converter
my %sgml=(
'asciidoc','\.(adoc|txt)'
,'markdown','\.md'
,'org','\.org'
,'rst','\.rst'
);
my %processor=(
'asciidoc',"/opt/local/bin/asciidoctor -a last-update-label! -o - '%s'"
,'markdown',"/usr/local/bin/pandoc '%s'"
,'org',"/usr/local/bin/pandoc '%s'"
,'rst',"/usr/local/bin/pandoc '%s'"
);
my $cmd;
foreach my $key (keys %sgml) {
if ($input =~ /$sgml{$key}/) {
$cmd=sprintf("$processor{$key}",$input);
last;
}
}
use CGI ':all';
use utf8;
use open ':encoding(utf8)';
binmode(STDOUT, ":utf8");
print header;
#print "<pre>\ninput=".$input."\noutput=".$output."\next=".$ext."\ncmd=".$cmd."\n</pre>\n";
system("$cmd");
```
# Answer
> 0 votes
I came to this solution, that do what I wanted:
* calls a shell command I have written in C++ `code_to_org` that transforms some source code into an org mode compatible document
* exports it to a html file and starts the web-browser to visualize it.
.
```
(defun my-code-to-html()
(interactive)
(save-buffer)
(setq current_buffer (current-buffer))
(setq current_filename (buffer-file-name))
(with-temp-buffer
(shell-command (concat "code_to_org " current_filename) (current-buffer))
(org-open-file (org-export-to-file 'html (concat current_filename ".html")))
)
)
```
---
Tags: org-mode, org-export, html
---
|
thread-59177
|
https://emacs.stackexchange.com/questions/59177
|
How to tell persp-mode to ignore some buffers by major-mode
|
2020-06-20T19:04:38.537
|
# Question
Title: How to tell persp-mode to ignore some buffers by major-mode
I'm new to persp-mode and don't fully understand its API, noticed that the Magit buffers are restored and set to fundamental-mode when restarting Emacs, and the list of these buffers grows as I work on different projects, I would like to have these buffers added automatically by persp-mode to the `nil` perspective.
Here is my current configuration for persp-mode:
```
;; parte de esta configuracion fue extraida de
;; https://pastebin.com/raw/Q1hK8cwi
;; fuente: https://www.reddit.com/r/emacs/comments/d66s8r/how_to_get_the_most_from_perspectiveel/f0r42ch/
(use-package persp-mode
:after (ivy)
:custom
(ivy-sort-functions-alist
(append ivy-sort-functions-alist
'((persp-kill-buffer . nil)
(persp-remove-buffer . nil)
(persp-add-buffer . nil)
(persp-switch . nil)
(persp-window-switch . nil)
(persp-frame-switch . nil))))
(wg-morph-on nil)
(persp-autokill-buffer-on-remove 'kill-weak)
(persp-keymap-prefix nil)
:bind (:map global-map ("C-x x" . hydra-persp/body))
:hook
(after-init . (lambda () (persp-mode 1)))
:init
(add-hook 'ivy-ignore-buffers #'(lambda (b)
(when persp-mode
(let ((persp (get-current-persp)))
(if persp
(not (persp-contain-buffer-p b persp))
nil)))))
(defmacro hfj-make-tab (name &rest body)
"Select an existing tab, or create one and configure it."
`(cond
((persp-with-name-exists-p ,name)
(persp-switch ,name))
(t
(persp-switch ,name)
,@body)))
(defun hfj-make-tab-f (name setup-actions)
"Select an existing tab, or create one and configure it."
(cond
((persp-with-name-exists-p name)
(persp-switch name))
(t
(persp-switch name)
(funcall setup-actions))))
(defun define-layout-inner (name f)
"Add layout config to hfj-predefined-layouts"
(setq hfj-predefined-layouts
(delete-if (lambda (a) (string-equal (car a) name))
hfj-predefined-layouts))
(push (list* name (cons name f)) hfj-predefined-layouts)
(setq hfj-predefined-layouts
(sort hfj-predefined-layouts
(lambda (a b) (string< (car a) (car b))))))
(defmacro hfj-define-layout (name &rest body)
"Add layout config to hfj-predefined-layouts"
`(define-layout-inner ,name (lambda () ,@body)))
(defun hfj-pick-layout ()
"Switch to a new or existing layout."
(interactive)
(let* ((names (persp-names))
(name (completing-read "Cambiar a maqueta: " names))
(exists (persp-with-name-exists-p name)))
(persp-switch name)
(unless exists
(switch-to-buffer "*scratch*"))))
(defvar hfj-predefined-layouts '())
(defun hfj-pick-predefined-layout ()
"Create a predefined layout to be selectable from list."
(interactive)
(when (null hfj-predefined-layouts)
(error "No hay maquetas configuradas."))
(let ((layout-name-and-actions (ivy-read :prompt "Seleccionar maqueta predefinida: " :collection hfj-predefined-layouts :require-match t)))
(when layout-name-and-actions
(hfj-make-tab-f (car layout-name-and-actions) (cdr layout-name-and-actions)))))
(defun hfj-persp-kill-current ()
(interactive)
(let ((persp (get-current-persp)))
(cond ((null persp) (error "No se puede matar la maqueta por defecto"))
(t (persp-kill (persp-name persp))))))
(defun hfj-persp-switch-to-n (n)
(let ((names (persp-names-current-frame-fast-ordered))
(count 1))
(dolist (name names)
(when (= count n)
(persp-switch name))
(cl-incf count))))
(defun hfj-persp-switch-to-1 () (interactive) (hfj-persp-switch-to-n 1))
(defun hfj-persp-switch-to-2 () (interactive) (hfj-persp-switch-to-n 2))
(defun hfj-persp-switch-to-3 () (interactive) (hfj-persp-switch-to-n 3))
(defun hfj-persp-switch-to-4 () (interactive) (hfj-persp-switch-to-n 4))
(defun hfj-persp-switch-to-5 () (interactive) (hfj-persp-switch-to-n 5))
(defun hfj-persp-switch-to-6 () (interactive) (hfj-persp-switch-to-n 6))
(defun hfj-persp-switch-to-7 () (interactive) (hfj-persp-switch-to-n 7))
(defun hfj-persp-switch-to-8 () (interactive) (hfj-persp-switch-to-n 8))
(defun hfj-persp-switch-to-9 () (interactive) (hfj-persp-switch-to-n 9))
(defun hfj-persp-switch-to-10 () (interactive) (hfj-persp-switch-to-n 10))
(defun hydra-perse-names ()
(let ((names (persp-names-current-frame-fast-ordered))
(current-name (safe-persp-name (get-current-persp)))
(parts '())
(count 1))
(dolist (name names (s-join " | " (nreverse parts)))
(cond ((eq name current-name)
(push (format "[%d:%s]" count name) parts))
(t
(push (format "%d:%s" count name) parts)))
(cl-incf count))))
:hydra (hydra-persp (:hint nil)
"
Maquetas %s(hydra-perse-names)
^Navegación^ ^Selección^ ^Acciones^ ^Buffers^
^-^---------------^-^---------------^-^--------------^-^------------
_n_: sig. _l_: escoger _d_: borrar _a_: agregar buffer
_p_: prev. _L_: predefinido _r_: renombrar
"
("q" nil)
("a" persp-add-buffer :exit t)
("d" hfj-persp-kill-current)
("l" hfj-pick-layout :exit t)
("L" hfj-pick-predefined-layout :exit t)
("r" persp-rename :exit t)
("n" persp-next)
("p" persp-prev)
("1" hfj-persp-switch-to-1 :exit t)
("2" hfj-persp-switch-to-2 :exit t)
("3" hfj-persp-switch-to-3 :exit t)
("4" hfj-persp-switch-to-4 :exit t)
("5" hfj-persp-switch-to-5 :exit t)
("6" hfj-persp-switch-to-6 :exit t)
("7" hfj-persp-switch-to-7 :exit t)
("8" hfj-persp-switch-to-8 :exit t)
("9" hfj-persp-switch-to-9 :exit t)
("0" hfj-persp-switch-to-10 :exit t)))
(use-package persp-mode-projectile-bridge
:straight (persp-mode-projectile-bridge :type git :host github :repo "Bad-ptr/persp-mode-projectile-bridge.el")
:init
:hook ((persp-mode-projectile-bridge-mode . (lambda () (if persp-mode-projectile-bridge-mode
(persp-mode-projectile-bridge-find-perspectives-for-all-buffers)
(persp-mode-projectile-bridge-kill-perspectives))))
(after-init . (lambda () (persp-mode-projectile-bridge-mode 1)))))
```
# Answer
> 1 votes
Check out this commimt from the repo `seagle0128/.emacs.d`.
It adds a filter function into the list `persp-filter-save-buffers-functions` to do filtering **magit** buffers. So, we can use the below example to config the **persp-mode**.
```
(add-to-list 'persp-filter-save-buffers-functions
(lambda (b)
"Ignore temporary buffers."
(let ((bname (file-name-nondirectory (buffer-name b))))
(or (string-prefix-p "magit" bname)
(string-equal "*ansi-term*" bname)
(string-prefix-p "*" bname)
;; and more
))))
```
---
Tags: persp-mode
---
|
thread-61454
|
https://emacs.stackexchange.com/questions/61454
|
gdb over ssh via tramp fails (but gdb-gud works?)
|
2020-10-28T15:05:58.197
|
# Question
Title: gdb over ssh via tramp fails (but gdb-gud works?)
I am running into an issue where the `gdb` command fails over tramp. The remote host is a simple linux box I am accessing via ssh. Even when I run emacs without my init file it still happens.
* Emacs 27.1
* Tramp 2.4.3.27.1
* gdb (on remote host) 8.0
* Mac OS Catalina 10.15.7 (local host OS)
I am running `M-x gdb` on a remote buffer, which results in the prompt: `Run gdb (like this): gdb -i=mi`. (Note that I am just trying to run gdb as a bare executable.) After hitting enter, I get an error in the minibuffer: wrong-type-argument "consp nil" and the resulting gud buffer is only partially loaded. Using debug-on-error I have the following stack trace:
```
Debugger entered--Lisp error: (wrong-type-argument "consp nil")
signal(wrong-type-argument ("consp nil"))
tramp-signal-hook-function(wrong-type-argument (consp nil))
signal(wrong-type-argument (consp nil))
tramp-sh-handle-make-process(:name "gdb-inferior" :buffer #<buffer limbo<4>> :command nil :noquery nil :file-handler t)
apply(tramp-sh-handle-make-process (:name "gdb-inferior" :buffer #<buffer limbo<4>> :command nil :noquery nil :file-handler t))
tramp-sh-file-name-handler(make-process :name "gdb-inferior" :buffer #<buffer limbo<4>> :command nil :noquery nil :file-handler t)
apply(tramp-sh-file-name-handler make-process (:name "gdb-inferior" :buffer #<buffer limbo<4>> :command nil :noquery nil :file-handler t))
tramp-file-name-handler(make-process :name "gdb-inferior" :buffer #<buffer limbo<4>> :command nil :noquery nil :file-handler t)
tramp-handle-start-file-process("gdb-inferior" #<buffer limbo<4>> nil)
apply(tramp-handle-start-file-process ("gdb-inferior" #<buffer limbo<4>> nil))
tramp-sh-file-name-handler(start-file-process "gdb-inferior" #<buffer limbo<4>> nil)
apply(tramp-sh-file-name-handler start-file-process ("gdb-inferior" #<buffer limbo<4>> nil))
tramp-file-name-handler(start-file-process "gdb-inferior" #<buffer limbo<4>> nil)
apply(tramp-file-name-handler start-file-process "gdb-inferior" #<buffer limbo<4>> nil nil)
#f(compiled-function (name buffer program &rest program-args) "<doc snipped>" #<bytecode 0x40ddd66b>)("gdb-inferior" #<buffer limbo<4>> nil)
apply(#f(compiled-function (name buffer program &rest program-args) "<doc snipped>" #<bytecode 0x40ddd66b>) "gdb-inferior" #<buffer limbo<4>> nil nil)
start-file-process--with-editor-process-filter(#f(compiled-function (name buffer program &rest program-args) "<doc snipped>" #<bytecode 0x40ddd66b>) "gdb-inferior" #<buffer limbo<4>> nil)
apply(start-file-process--with-editor-process-filter #f(compiled-function (name buffer program &rest program-args) "<doc snipped>" #<bytecode 0x40ddd66b>) ("gdb-inferior" #<buffer limbo<4>> nil))
start-file-process("gdb-inferior" #<buffer limbo<4>> nil)
apply(start-file-process "gdb-inferior" #<buffer limbo<4>> nil nil)
comint-exec-1("gdb-inferior" #<buffer limbo<4>> nil nil)
comint-exec(#<buffer limbo<4>> "gdb-inferior" nil nil nil)
make-comint-in-buffer("gdb-inferior" #<buffer limbo<4>> nil)
gdb-inferior-io-mode()
gdb-get-buffer-create(gdb-inferior-io)
gdb-init-1()
gdb-update()
gdb("gdb -i=mi")
funcall-interactively(gdb "gdb -i=mi")
call-interactively(gdb record nil)
command-execute(gdb record)
counsel-M-x-action("gdb")
```
I am not sure what is going on. I have verified that running `gdb` on a file locally works, and Emacs is responsive as a front end and properly opens source files and makes break points visible.
Additionally, if I run `gud-gdb` instead of `gdb` (with `Run gudb-gdb (like this): gdb`) I am able to successfully start gdb and use over tramp, but I can only use it from the CLI and not use any of the emacs integration. So I know I can both use Emacs as a gdb front end and access a remote gdb session over tramp, but something breaks putting both of those pieces together.
Can anyone help with this issue? I would really like to be able to use Emacs as a front end to remote gdb. Also let me know if there is any more information I can provide. Thanks in advance!
---
Note that I snipped the documentation of `start-file-process-xxx` in several places to clean up the trace. The text where `<doc snipped>` appears in the trace is here:
> Start a program in a subprocess. Return the process object for it. Similar to `start-process`, but may invoke a file name handler based on `default-directory`. See Info node `(elisp)Magic File Names`. This handler ought to run PROGRAM, perhaps on the local host, perhaps on a remote host that corresponds to `default-directory`. In the latter case, the local part of `default-directory`, the one produced from it by `file-local-name`, becomes the working directory of the process on the remote host. PROGRAM and PROGRAM-ARGS might be file names. They are not objects of file name handler invocation, so they need to be obtained by calling `file-local-name`, in case they are remote file names. File name handlers might not support pty association, if PROGRAM is nil.
# Answer
This is bug#44151, see https://debbugs.gnu.org/44151. I've fixed this in Tramp 2.4.4.3, which will be released later today on GNU ELPA. Note that this bug describes a further problem, which seems to be in gdb-mi.el. This I couldn't fix.
> 2 votes
---
Tags: debugging, tramp, gdb, remote, gud
---
|
thread-51721
|
https://emacs.stackexchange.com/questions/51721
|
Failed to download 'gnu' archive
|
2019-07-19T01:14:49.450
|
# Question
Title: Failed to download 'gnu' archive
I tried to install emacs and in an attempt to install MELPA, tried:
(this is my `init.el` file)
```
(package-initialize)
(add-to-list 'package-archives '("gnu" . "http://elpa.gnu.org/packages/"))
(add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/"))
(require 'package)
(let* ((no-ssl (and (memq system-type '(windows-nt ms-dos))
(not (gnutls-available-p))))
(proto (if no-ssl "http" "https")))
(add-to-list 'package-archives
(cons "melpa" (concat proto "://melpa.org/packages/")) t))
(package-initialize)
```
When I tried running the following commands `M-x package-initialize` then `M-x package-refresh-contents`, it said that it Failed to download 'gnu' archive. Is there anyway of getting around this?
I'm using MacOS and using emacs version 26.2.
# Answer
> 20 votes
Add the following before package-initialize:
```
(setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")
```
This is apparently a bug in Emacs 26.2 for MacOS. I found this solution in this reddit thread.
# Answer
> 4 votes
First of all run emacs with `--debug-init` from your terminal and check if it complains about being unable to verify the elpa archive due to an invalid key. If that is the case, **copy the public key displayed to you**.
I ran into this problem because the GPG keys used by the ELPA package manager to verify authenticity of packages downloaded from the GNU ELPA archive have a limited validity in time (for example, the first key was valid until **Sep 2019** only).
If your keys are already too old, causing signature verification errors when installing packages you can do the following:
`gpg --homedir ~/.emacs.d/elpa/gnupg --receive-keys C433554766D3DDC64221BFAA066DAFCB81E42C40`
**You should replace the key with the value you copied from the debug log**
I found this package to hopefully avoid this problem when the certificates change the next time.
# Answer
> 1 votes
Another potential problem is that `gnutls-cli`, which Emacs may be trying to use to initiate the TLS connection, just may not be installed. Unfortunately, if this is the case, the error message produced by Emacs gives no indication of this. If this is indeed the problem, then on a Debian-like system you need to install `gnutls-bin`, whereas on a RedHat-like system the package is called `gnutls-utils`.
---
Tags: init-file, package, osx, package-repositories
---
|
thread-61470
|
https://emacs.stackexchange.com/questions/61470
|
Evaluate a variable when inserting text into a buffer
|
2020-10-29T15:24:20.707
|
# Question
Title: Evaluate a variable when inserting text into a buffer
When I open a fresh file for coding, I like to insert a header like this:
```
#####################################################################
# Purpose:
# Author: me (me@someplace.com)
# Date:
#####################################################################
```
I keep this text in a file called `header` in `~/.emacs.d/` and I insert it like so:
```
;; Insert header to file
(defun header()
"Insert header into file"
(interactive)
(insert-file "~/.emacs.d/header"))
```
which I call with `M+x header`. Very cool! I also have a function for adding the date:
```
;; Insert today's date
(defun today ()
"Insert today's date"
(interactive)
(insert (format-time-string "%Y-%m-%d")))
```
which I invoke with `M+x today` after inserting my header text in order to populate the `Date:` field.
**Q:** Is there a way that I can merge these functions such that the date is *automatically* inserted after `Date:` when I insert my header text? For example, can I add `(format-time-string "%Y-%m-%d")` after `Date:` in my `header` file and evaluate it somehow when it is inserted?
# Answer
Inside of GNU Emacs only your imagination is the limit :)
I think you're looking for something along the following lines, though some adjustments might be needed.
```
(defun header()
"Insert header into file"
(interactive)
(insert-file "~/.emacs.d/header")
(re-search-backward "Date:")
(insert (format-time-string "%Y-%m-%d")))
```
> 2 votes
---
Tags: insert, template
---
|
thread-61469
|
https://emacs.stackexchange.com/questions/61469
|
What is the difference between `M-f` and `C-right`?
|
2020-10-29T14:54:07.907
|
# Question
Title: What is the difference between `M-f` and `C-right`?
The documentation states the following:
*(forward-word &optional ARG) is bound to M-f*
*(right-word &optional N) is bound to C-right*
Could there be any difference between the two? It just doesn't seem right to me that a software as elegant as Emacs has two functions that do essentially the same thing... Thanks in advance!
# Answer
> 3 votes
`right-word` may move the cursor left when there is bidirectional text like the documentation points out and so did @NickD (in the comments). Try it with the quoted sample text and you'll observe that the cursor moves left during the Urdu fragment since Urdu is read from left to right.
> Mir says, "!ہے نام مجلسوں میں میرا میر بے دماغ", sarcastically in Urdu.
But either way, it is correct to say that the cursor moves forward (left to right in Urdu and right to left in English). You may look at the documentation like this `C-h k C-<right>`. I'll copy it here as well.
```
right-word is an interactive compiled Lisp function.
It is bound to <C-right>.
(right-word &optional N)
Move point N words to the right (to the left if N is negative).
Depending on the bidirectional context, this may move either forward
or backward in the buffer. This is in contrast with M-f
and M-b, which see.
Value is normally t.
If an edge of the buffer or a field boundary is reached, point is left there
and the function returns nil. Field boundaries are not noticed
if ‘inhibit-field-text-motion’ is non-nil.
[back]
```
Did some more research and it looks like, `right-word` just conditionally calls `forward-word` or `backward-word`. I found the source code:
```
(defun right-word (&optional n)
(interactive "^p")
(if (eq (current-bidi-paragraph-direction) 'left-to-right)
(forward-word n)
(backward-word n)))
```
`forward-word` however has a somewhat difficult implementation to read:
```
DEFUN ("forward-word", Fforward_word, Sforward_word, 0, 1, "^p",
doc: /* ... */)
(Lisp_Object arg)
{
Lisp_Object tmp;
ptrdiff_t orig_val, val;
if (NILP (arg))
XSETFASTINT (arg, 1);
else
CHECK_FIXNUM (arg);
val = orig_val = scan_words (PT, XFIXNUM (arg));
if (! orig_val)
val = XFIXNUM (arg) > 0 ? ZV : BEGV;
/* Avoid jumping out of an input field. */
tmp = Fconstrain_to_field (make_fixnum (val), make_fixnum (PT),
Qnil, Qnil, Qnil);
val = XFIXNAT (tmp);
SET_PT (val);
return val == orig_val ? Qt : Qnil;
}
```
So I am not sure what is up but I think `right-word` is the implementation that is \`ought to be smart about bidirectional text, which is counter-intuitive in my opinion.
---
Tags: motion, bidirectional-support
---
|
thread-29447
|
https://emacs.stackexchange.com/questions/29447
|
how to style block quotes in org-mode LaTeX export?
|
2016-12-20T21:44:08.390
|
# Question
Title: how to style block quotes in org-mode LaTeX export?
I am trying to change the style of block quote formatting in org-mode export to PDF via LaTeX.
Using this answer, I defined a new LaTeX environment called `fancyquotes`. I am successfully able to create block quotes with this styling by creating a special block:
```
#+BEGIN_fancyquotes
In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move. ---Douglas Adams
#+END_fancyquotes
```
This successfully creates the desired TeX output:
```
\begin{fancyquotes}
In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move. ---Douglas Adams
\end{fancyquotes}
```
However, for compatibility with org-mode export to HTML, I would prefer to use not a special block, but rather standard quote blocks:
```
#+BEGIN_QUOTE
In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move. ---Douglas Adams
#+END_QUOTE
```
The problem is that, by default, the above gets exported using the `quote` label:
```
\begin{quote}
In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move. ---Douglas Adams
\end{quote}
```
How do I direct org-mode to automatically export standard quote blocks to my newly defined new LaTeX environment and apply the labels `\begin{fancyquotes}` and `\end{fancyquotes}`? In other words, how do I redefine org-mode quote blocks in LaTeX export, changing it from the default label `quote` to the label `fancyquotes`?
Bonus question: For the fancyquotes LaTeX environment I defined, how do I specify the `shadequoteauthor` in my org-mode source?)
# Answer
> 6 votes
Interesting question. I put together this start based on this part of the manual. How you set this up will depend on how you want to use it. Based on my experiments, it seems easier to define a new exporter, like the manual suggests, than it is to redefine the latex one.
```
(defun my-org-latex-quote-block (quote-block contents info)
"Transcode a QUOTE-BLOCK element from Org to LaTeX.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(org-latex--wrap-label
quote-block
(format "\\begin{fancyquotes}\n%s\\end{fancyquotes}" contents) info))
(org-export-define-derived-backend 'my-latex 'latex
:translate-alist '((quote-block . my-org-latex-quote-block)))
```
You can then test the export with
```
(org-export-to-buffer 'my-latex "*Org MY-LATEX Export Results*")
```
This only does a dump to a buffer, but illustrates the basic idea.
**Update:**
I initially thought just redefining `org-latex-quote-block` should work, but it wasn't for me. I know why now. I have org set up to use async by default, which runs a separate emacs process with the default versions of the org functions. Turning off async makes this work too. To use this with async you would have to redefine the function in your `org-export-async-init-file`.
```
(defun org-latex-quote-block (quote-block contents info)
"Transcode a QUOTE-BLOCK element from Org to LaTeX.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(org-latex--wrap-label
quote-block
(format "\\begin{fancyquotes}\n%s\\end{fancyquotes}" contents) info))
```
# Answer
> 2 votes
@justbur's answer works but he forgot to add `info` at the end.
```
(defun org-latex-quote-block (quote-block contents info)
"Transcode a QUOTE-BLOCK element from Org to LaTeX.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(org-latex--wrap-label
quote-block
(format "\\begin{fancyquotes}\n%s\\end{fancyquotes}" contents) info))
```
---
Tags: org-mode, org-export, latex, quote
---
|
thread-61482
|
https://emacs.stackexchange.com/questions/61482
|
Elisp - Changing directory in shell buffer
|
2020-10-30T16:28:20.880
|
# Question
Title: Elisp - Changing directory in shell buffer
I want to open an instance of a terminal emulator (in my case `term`) and go to a specific directory, all with a single Elisp function. My idea was to send a specific string programmatically to the shell, telling it to change to a specific directory. But I don't know how I should do it, and I've not been able to find an alternative (like sending the `cd` command as the shell is opened).
How can I achieve this?
# Answer
One method would be to let-bind the `default-directory` when opening `term`:
```
(let ((default-directory "/path/to/desired/directory/"))
(term "/bin/sh"))
```
> 2 votes
---
Tags: shell, term
---
|
thread-61488
|
https://emacs.stackexchange.com/questions/61488
|
How to change coloring in counsel
|
2020-10-31T00:05:30.143
|
# Question
Title: How to change coloring in counsel
I am using `counsel-buffer-or-recentf` in order to toggle in files under buffer and recentf. The selected line is not clear, which has blue background highlighting.
=\> Is it possible to change the coloring of the highlight? or can I remove the highlights?
# Answer
Check out ivy-faces.el for most of the faces of interest. The face you are asking specifically is called `ivy-current-match`. You wanna call `describe-face` and choose `customize this face` for customization.
> 1 votes
---
Tags: counsel
---
|
thread-52994
|
https://emacs.stackexchange.com/questions/52994
|
Org-mode agenda: Show list of tasks done in the past, and not those clocked
|
2019-10-06T11:39:37.370
|
# Question
Title: Org-mode agenda: Show list of tasks done in the past, and not those clocked
Similar to this thread and this one, I want to show an agenda view with all items marked as "DONE" in the last two weeks, but without the lines `Clocked: (1:00) DONE Some task` (because for that I only care about the totals and use a `clock-report` dynamic block). I would also like to restrict to second-level items only.
I tried this code and succeeded in restricting to second-level headings only:
```
(add-to-list 'org-agenda-custom-commands
'("W" "Weekly review"
agenda ""
((org-agenda-span 'week)
(org-agenda-start-on-weekday 1)
(org-agenda-start-with-log-mode nil)
(org-agenda-skip-function
'(org-agenda-skip-entry-if 'notregexp "^\\*\\* DONE "))
)))
```
If I set `org-agenda-start-with-log-mode` to `t`, then `Clocked: ...` lines show, e.g.:
```
Monday 30 September 2019 W40
gtd: 10:49-10:59 Clocked: (0:10) DONE some task
gtd: 10:50...... Closed: DONE Some other task
```
If I set it to `nil`, then `Closed: ...` lines do not show.
Also, if I set `org-agenda-span` to 14, to include the past 14 days, it shows 14 days starting from today.
How can I include only `Closed: ...` lines, and list tasks in the past?
# Answer
> 7 votes
To include only `Closed: ...` use:
```
(org-agenda-start-with-log-mode '(closed))
```
To show the past 14 days offset the start day:
```
(org-agenda-start-day "-14d")
```
This results in:
```
(with-eval-after-load 'org-agenda
(add-to-list 'org-agenda-custom-commands
'("W" "Weekly review"
agenda ""
((org-agenda-start-day "-14d")
(org-agenda-span 14)
(org-agenda-start-on-weekday 1)
(org-agenda-start-with-log-mode '(closed))
(org-agenda-skip-function
'(org-agenda-skip-entry-if 'notregexp "^\\*\\* DONE "))))))
```
The statement is wrapped inside `with-eval-after-load` to make sure that this doesn't throw an error if org-agenda is not yet loaded.
You might also want to include archived items with:
```
(org-agenda-archives-mode t)
```
---
*Note: Use `C-h v` to describe a variable like `org-agenda-start-with-log-mode` to see the possibilities or `M-x custmoize-variable` to customize it (this shows all possibilities in the customize interface).*
# Answer
> 1 votes
I used Hubsian's suggested solution, however, found that the `org-agenda-custom-commands` variable appears to only be created after the agenda is opened for the first time in an emacs session. This causes an error when loading emacs after closing and reopening:
`Symbol's value as variable is void: org-agenda-custom-commands`
So instead, I've modified it to create the variable (and keep the "Agenda and all TODOs item that is created with you first open the agenda dispatcher with `C-c a`):
```
(setq org-agenda-custom-commands
'(("W" "Weekly review"
agenda ""
((org-agenda-start-day "-14d")
(org-agenda-span 14)
(org-agenda-start-on-weekday 1)
(org-agenda-start-with-log-mode '(closed))
(org-agenda-archives-mode t)
(org-agenda-skip-function '(org-agenda-skip-entry-if 'notregexp "^\\*\\* DONE "))))
("n" "Agenda and all TODOs"
agenda ""
((alltodo "")))
))
```
`setq org-agenda-custom-commands` creates the variable `org-agenda-custom-commands` instead of appending to the existing variable by changing `add-to-list` to `setq` and removing the `'` before the variable name.
Additionally, we need to wrap the Weekly review item that's being created in an additional set of parenthesis to make it a list since we're creating a new list variable and not appending new entry to an existing one. This is why there are now two `(` at the start of the `'(("W" "Weekly review"` line and an additional at the end the last line.
Note: more information on the options available when creating custom commands can be found by running `C-h v RET org-agenda-custom-commands`.
*Edit: formatting, better explanation and added: "Agenda and all TODOs".*
---
Tags: org-mode, org-agenda
---
|
thread-61496
|
https://emacs.stackexchange.com/questions/61496
|
Overlay category set properties
|
2020-10-31T10:05:25.960
|
# Question
Title: Overlay category set properties
From the Elisp manual:
> If an overlay has a category property, we call it the category of the overlay. It should be a symbol. The properties of the symbol serve as defaults for the properties of the overlay.
How can I set the properties of the overlay category?
# Answer
> 2 votes
Use `put` to set a property of a symbol. Use `get` to retrieve one property and `symbol-plist` to retrieve them all. The properties of a symbol are an attribute of it, parallel to its value as a variable (`symbol-value`) and its function definition (`symbol-function`).
For example, the following snippet causes `overlay` to be shown in the default face, but in bold italic when the mouse cursor is over it, because the `mouse-face` property of the category applies but the `face` property of the category is overridden by the same property on the overlay itself.
```
(put 'my-category 'face 'bold)
(put 'my-category 'mouse-face 'bold-italic)
(let ((overlay (make-overlay (point) (1+ (point)))))
(overlay-put overlay 'category 'my-category)
(overlay-put overlay 'face 'default)
...)
```
---
Tags: overlays
---
|
thread-61504
|
https://emacs.stackexchange.com/questions/61504
|
Is it possible to make 'tput bel' behave like it does in iTerm with a macOS Dock badge?
|
2020-10-31T21:08:59.117
|
# Question
Title: Is it possible to make 'tput bel' behave like it does in iTerm with a macOS Dock badge?
Running `sleep 1s && tput bel` inside iTerm and quickly tabbing out into another application displays this very nice notification badge in the Dock:
I tried running `(shell-command "sleep 1s && tput bel")` or calling something like `echo -e "\a"`, but there is no audible beep or that nice Dock badge. It just displays `^G`.
I am interested in using this badge for new emails, linking it into mu4e-alert as a subtle way to notify me because I don't want to use the full-size notifications provided by something like `terminal-notifier -message "New email..."`.
Does anyone know of other ways how I could get this badge to appear? I especially like the integration into macOS that the badge goes away on its own when the application is launched into its foreground.
---
I also tried the built-in `(beep)` and it beeps, but does not display the Dock badge when Emacs is not in focus:
```
(sleep-for 2)
(beep)
```
# Answer
It's certainly possible, but you should understand that this has nothing to do with BEL characters or beeps. Any OSX application can call the system API that adds the badge to the dock icon any time it wants. Your email program does it when you receive an email, and iTerm does it when it sees a BEL character. But you're not running Emacs inside of iTerm, so the BEL character has no special effect. What you need to do is consult the developer documentation for OSX, find out what APIs have to be called, extend Emacs to include Lisp functions that call those APIs, and finally write Lisp that triggers Emacs to make those calls in appropriate situations.
It's actually possible that some of this work has already been done, but as a rule Emacs tends not to support many platform-unique features. Features that exist across platforms but are simply implemented in a different way are commonly supported by Emacs, but not features that exist only on one platform. This is particularly true of features that exist only on OSX, as OSX is non-Free. Don't let that stop you from extending Emacs to better suit you though.
> 2 votes
---
Tags: osx, notifications
---
|
thread-54492
|
https://emacs.stackexchange.com/questions/54492
|
Org mode agenda fails to show consistency graph
|
2019-12-22T09:12:40.830
|
# Question
Title: Org mode agenda fails to show consistency graph
I set up the Org mode consistency graph of habits following the manual. Each habit is, e.g.:
```
** TODO some habit
SCHEDULED: <2019-12-22 Sun 07:20 ++1d>
:PROPERTIES:
:STYLE: habit
:LAST_REPEAT: [2019-12-21 Sat 09:14]
:END:
:LOGBOOK:
- State "DONE" from "TODO" [2019-12-21 Sat 09:14]
...
:END:
```
and my init file has:
```
;; track habits
(add-to-list 'org-modules 'habits)
(setq org-habit-graph-column 65)
(setq org-habit-show-habits-only-for-today nil)
```
The consistency graph showed in agenda view for the week yesterday and I cannot replicate it now, either in view for the week or the day. I tried adding the code from How to show org-habit graph alone?
```
(set 'org-habit-show-all-today t)
```
Pressing `K` in either day or week view shows that the buffer is read-only in the mini-buffer.
How can I set up the consistency graph or debug what's wrong?
# Answer
You are probably using DEADLINE instead of SCHEDULED. I had the same problem and I solved it by using SCHEDULED.
> 0 votes
---
Tags: org-mode
---
|
thread-12889
|
https://emacs.stackexchange.com/questions/12889
|
Syncing changes on a tangled file back to the original org file
|
2015-06-04T05:48:26.530
|
# Question
Title: Syncing changes on a tangled file back to the original org file
I am using org-mode with fountain mode to write a screenplay.
Org for organization and fountain for screenplay formatting.
This is the code I use for this purpose :
Settings for working with (fountain) source blocks in org.
```
;; prevent org from messing with indentation of the source text.
(setq org-src-preserve-indentation t)
(setq org-edit-src-content-indentation 0)
;; open the buffer for editing fountain in another window.
(setq org-src-window-setup (quote reorganize-frame))
;; prevent a message in the edit buffer from being shown.
(setq org-edit-src-persistent-message nil)
;; save edits in the fountain buffer to the org buffer after x sec
(setq org-edit-src-auto-save-idle-delay 1)
```
For example :
Act 1
\** SQ 1
\*** Scene 1
Bunch of text related to the scene and what the characters are doing and everything that I need to know but will never end up in the screenplay.
BEGIN\_SRC fountain
screenplay text
END\_SRC
Now I C-c ' and it opens the above in a new buffer and I can take it up from there.
---
The problem with my current set up is that it doesn't let me see the screenplay text in its entirety.
I have around 50+ such blocks and I'd like to achieve the following :
I want org to export all fountain blocks to a specific file, say fountain-screenplay. That way I have a single file with the screenplay only.
Have all edits synced with the org file. If I edit anything in fountain-screenplay, the source block in org should update the change and vice-versa.
---
To do this, I inserted the following properties in my org file :
```
:PROPERTIES:
:file: "~/files/fountain-screenplay.fountain"
:cache: yes
:comments: yes
:tangle: yes
:results: silent
:END:
```
When I C-c C-c it returns with an error saying that No org-babel execute function found.
And when I C-c C-v t it says 0 blocks tangled.
Is my approach incorrect or am I missing something?
Edit : I changed the properties to :
```
#+properties :file .fountain :cache yes and so on
```
and when I C-c C-v t it tangles the source blocks to a filename.fountain. Now the sync part remains to be solved.
# Answer
One widely known option that implements two-way round-trip linkage between different document formats (org and fountain, for example) within the same file is the **lentic server** feature developed by Phillip Lord. It can be installed as the **lentic** package through MELPA repository.
There is a screencast showing org-mode and lisp integration in the same file with two different editable views at the same time, linked. Changing in one makes changes in the other. Some initial setup may be required to accommodate the formats you need.
This is a richer integration, more suitable for editing, than say one-way output of tangle and detangle through org-babel.
> 8 votes
# Answer
Slightly late to the party, but I had the same wish to sync tangled blocks with their external files.
For this I can recommend org-tanglesync
This package looks for a `:tangle <filename>` property in the header of an org file and compares the block content to it. A diff is performed in the background, and then the user is prompted to pull or reject the external changes.
I find that this is more intuitive than `org-babel-detangle` because it does not require the external file to have extra org-babel magic for it to work, i.e. it is the source file that tracks the external exported blocks and not the other way around.
> 2 votes
# Answer
For this specific use case (fountain and org), fountain mode now has outlining built in. Just use `#` instead of `*`.
> 0 votes
---
Tags: org-mode, org-babel
---
|
thread-61517
|
https://emacs.stackexchange.com/questions/61517
|
Issue while trying to use chemacs
|
2020-11-01T19:15:05.800
|
# Question
Title: Issue while trying to use chemacs
I am currently trying to use chemacs on my computer, following the instructions given on github, but I do not seem to be able to make it work properly.
My goal would be to be able to use both Emacs 24.5.1 and spacemacs using Emacs 26.3, and chemacs seemed to be the only solution for doing this in a sensible way. I am using Ubuntu 16.04, and both versions of emacs were installed today.
So I did what the instruction on github were saying: I first cloned the repository into my home file. Here is the result I got:
```
(base) giovanni@giovanni-UX510UXK:~$ git clone https://github.com/plexus/chemacs.git
Cloning into 'chemacs'...
remote: Enumerating objects: 11, done.
remote: Counting objects: 100% (11/11), done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 116 (delta 3), reused 7 (delta 2), pack-reused 105
Receiving objects: 100% (116/116), 41.23 KiB | 39.00 KiB/s, done.
Resolving deltas: 100% (37/37), done.
Checking connectivity... done.
(base) giovanni@giovanni-UX510UXK:~$ cd chemacs
(base) giovanni@giovanni-UX510UXK:~/chemacs$ ./install.sh
OK Creating symlink ~/.emacs -> /home/giovanni/chemacs/./.emacs
```
Now, when I try to run emacs 24.5.1, I get the following message
```
Warning (initialization): An error occurred while loading `/home/giovanni/.emacs':
Symbol's function definition is void: alist-get
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.
```
The message is the same even if I use the command `emacs --with-profile default`. This makes me suspect that emacs 24.5.1 is too old for chemacs (although I did not find this mentioned in anything that I found online). Now, I should probably say that emacs seems to work, but I do not know exactly what this error means and how I should try to solve the issue. When I tried to run emacs with the `-debug-init` option, this is the message I got:
```
Debugger entered--Lisp error: (void-function alist-get)
(alist-get key (chemacs-get-emacs-profile chemacs-current-emacs-profile) default)
chemacs-emacs-profile-key(user-emacs-directory)
(file-name-as-directory (chemacs-emacs-profile-key (quote user-emacs-directory)))
(let* ((emacs-directory (file-name-as-directory (chemacs-emacs-profile-key (quote user-emacs-directory)))) (init-file (expand-file-name "init.el" emacs-directory)) (custom-file- (chemacs-emacs-profile-key (quote custom-file) init-file)) (server-name- (chemacs-emacs-profile-key (quote server-name)))) (setq user-emacs-directory emacs-directory) (if server-name- (progn (setq server-name server-name-))) (mapcar (function (lambda (env) (setenv (car env) (cdr env)))) (chemacs-emacs-profile-key (quote env))) (if (chemacs-emacs-profile-key (quote straight-p)) (progn (chemacs-load-straight))) (load init-file) (if (not custom-file) (progn (setq custom-file custom-file-) (if (equal custom-file init-file) nil (load custom-file)))))
chemacs-load-profile("default")
(if args (let ((s (split-string (car args) "="))) (cond ((equal (car args) "--with-profile") (add-to-list (quote command-switch-alist) (quote ("--with-profile" lambda (_) (pop command-line-args-left)))) (chemacs-load-profile (cadr args))) ((equal (car s) "--with-profile") (add-to-list (quote command-switch-alist) (cons (car args) (quote (lambda ...)))) (chemacs-load-profile (mapconcat (quote identity) (cdr s) "="))) (t (chemacs-check-command-line-args (cdr args))))) (chemacs-load-profile (chemacs-detect-default-profile)))
chemacs-check-command-line-args(nil)
(cond ((equal (car args) "--with-profile") (add-to-list (quote command-switch-alist) (quote ("--with-profile" lambda (_) (pop command-line-args-left)))) (chemacs-load-profile (cadr args))) ((equal (car s) "--with-profile") (add-to-list (quote command-switch-alist) (cons (car args) (quote (lambda (_))))) (chemacs-load-profile (mapconcat (quote identity) (cdr s) "="))) (t (chemacs-check-command-line-args (cdr args))))
(let ((s (split-string (car args) "="))) (cond ((equal (car args) "--with-profile") (add-to-list (quote command-switch-alist) (quote ("--with-profile" lambda (_) (pop command-line-args-left)))) (chemacs-load-profile (cadr args))) ((equal (car s) "--with-profile") (add-to-list (quote command-switch-alist) (cons (car args) (quote (lambda (_))))) (chemacs-load-profile (mapconcat (quote identity) (cdr s) "="))) (t (chemacs-check-command-line-args (cdr args)))))
(if args (let ((s (split-string (car args) "="))) (cond ((equal (car args) "--with-profile") (add-to-list (quote command-switch-alist) (quote ("--with-profile" lambda (_) (pop command-line-args-left)))) (chemacs-load-profile (cadr args))) ((equal (car s) "--with-profile") (add-to-list (quote command-switch-alist) (cons (car args) (quote (lambda ...)))) (chemacs-load-profile (mapconcat (quote identity) (cdr s) "="))) (t (chemacs-check-command-line-args (cdr args))))) (chemacs-load-profile (chemacs-detect-default-profile)))
chemacs-check-command-line-args(("emacs"))
eval-buffer(#<buffer *load*> nil "/home/giovanni/.emacs" nil t) ; Reading at buffer position 7047
load-with-code-conversion("/home/giovanni/.emacs" "/home/giovanni/.emacs" t t)
load("~/.emacs" t t)
#[0 "\205\262
```
Again, I don't exactly know what is going on here. Any hint is really appreciated.
Finally, I would like to apologize for such a long post containing questions that may well be very trivial. In my defense, I can say that I am fairly new to all of this (also, I might have messed up with the tags; apologies for that as well).
# Answer
`alist-get` was added in Emacs-25, so indeed the code of chemacs seems to require a version more recent than Emacs-24.5. You'll likely get better information by asking directly the chemacs maintainers. Maybe they do want to support older Emacs versions and it's a simple error (it's easy to replace uses of `alist-get` with something else).
> 1 votes
---
Tags: spacemacs, init-file
---
|
thread-61511
|
https://emacs.stackexchange.com/questions/61511
|
Replace element in a list / add in case of absence, with custom test/key functions
|
2020-11-01T10:46:48.883
|
# Question
Title: Replace element in a list / add in case of absence, with custom test/key functions
`add-to-list` doesn't refresh item, it only checks for existence of item by `equal` or custom comparison function:
```
(add-to-list
'tramp-methods
'("gssh" (tramp-login-program "gcloud compute ssh"))
nil (lambda (a b) (equal (car a) (car b))))
```
What way can I replace definition in a list, that handles presence/absence of item and support custom comparison function?
`tramp-methods` is an association list. Is there something to set key/value with replacing existing entry?
**UPDATE** I found `cl-pushnew` & `cl-adjoin` but they don't replace, only adds if not there...
**UPDATE 2** Found exactly same question: https://stackoverflow.com/questions/10063195/replace-item-in-association-list-in-elisp
There is no build-in library function that handles replacement of existing items with custom key/test function & that handles missing item case...
The close solution:
```
(setq tramp-methods (cons
'("gssh" (tramp-login-program "compute ssh 2"))
(cl-remove "gssh" tramp-methods :key 'car :test 'equal)))
```
I wonder if there is some `cl-` equivalent...
**UPDATE 3** `cl-union` is the most closed so far, but it has undefined behavior when elements are equal...
# Answer
You can use `alist-get` with `setf` (elisp) Generalized Variables, e.g.,
```
;; Add
(let ((al (list (cons 'a 1) (cons 'b 2))))
(setf (alist-get 'c al) 3)
al)
;; => ((c . 3) (a . 1) (b . 2))
;; Replace/update
(let ((al (list (cons 'a 1) (cons 'b 2))))
(setf (alist-get 'b al) "2")
al)
;; => ((a . 1) (b . "2"))
```
```
(add-to-list
'tramp-methods
'("gssh" (tramp-login-program "gcloud compute ssh"))
nil (lambda (a b) (equal (car a) (car b))))
(setf (alist-get "gssh" tramp-methods nil nil #'equal)
'(tramp-login-program "GCLOUD COMPUTE SSH"))
(car tramp-methods)
;; => ("gssh" tramp-login-program "GCLOUD COMPUTE SSH")
```
`alist-get` was added in Emacs 25.1, its optional argument `TESTFN` was added in Emacs 26.1.
> 2 votes
# Answer
I ended with function like:
```
(defun my-assoc-push (key value alist-name)
(when (not (symbolp alist-name)) (error "alist-name is not a symbol."))
(set alist-name
(cons (cons key value)
(cl-remove key (symbol-value alist-name) :key #'car :test #'equal))))
(my-assoc-push "gssh" '((tramp-login-program "compute ssh 3")) 'tramp-methods)
```
to replace/add if new key to an association list.
> 1 votes
# Answer
> `tramp-methods` is an association list.
Which means that you don't have to *replace* an existing value at all.
When a value is looked up in an alist, only the *first* match for the key is returned.
Therefore merely pushing a new `(KEY . VALUE)` onto the front of the list has the desired effect, regardless of whether or not there are other uses of that same KEY in the list already.
> 1 votes
---
Tags: list, association-lists
---
|
thread-61528
|
https://emacs.stackexchange.com/questions/61528
|
What is the difference between Workflow states vs Types in org-mode?
|
2020-11-02T12:15:33.590
|
# Question
Title: What is the difference between Workflow states vs Types in org-mode?
In org-mode, what is the difference between TODO workflow states and TODO types? They looks and seems the same.
Here's a simple workflow states:
```
(setq org-todo-keywords
'((sequence "TODO" "FEEDBACK" "VERIFY" "|" "DONE" "DELEGATED")))
```
And here's a TODO type:
```
(setq org-todo-keywords '((type "Fred" "Sara" "Lucy" "|" "DONE")))
```
But for me, they both look and function the same.
# Answer
> 2 votes
The doc says:
> The second possibility is to use TODO keywords to indicate different *types* of action items. For example, you might want to indicate that items are for “work” or “home”. Or, when you work with several people on a single project, you might want to assign action items directly to persons, by using their names as TODO keywords. This type of functionality is actually much better served by using tags (see \*note Tags::), so the TODO implementation is kept just for backward compatibility.
So you probably should not use `type` at all.
---
Tags: org-mode, todo, keywords
---
|
thread-7377
|
https://emacs.stackexchange.com/questions/7377
|
Named string substitution?
|
2015-01-14T19:30:38.877
|
# Question
Title: Named string substitution?
I often have to make several substitution of the same string:
```
(format "%s %s %s" "a" "a" "a") ;; gives: "a a a"
```
(it's just a dummy example, in this case it's better to glue "a" with a whitespace, but in general I deal with more complicated situations)
Is there a way to make a named substitution? For example in python one would write:
```
"{0} {0} {0}".format("a") # or:
"{name} {name} {name}".format(name="a")
```
# Answer
> 18 votes
Re-writing this answer gives another solution:
```
(format-spec "%a %a %a %b %b %b" (format-spec-make ?a "a" ?b "b"))
```
**Edit**: Another `format-spec` solution:
As Malabarba gives another solution in comments:
```
(format-spec "%a %a %a %b %b %b" '((?a . "a") (?b . "b")))
```
**Edit 2**: Evaluation before substitution:
Here are examples with evaluation before substitution:
```
(let ((a 1)
(b 2))
(format-spec "a = %a; b = %b" (format-spec-make ?a a ?b b)))
;; ⇒ "a = 1; b = 2"
(let ((a 1)
(b 2))
(format-spec "a = %a; b = %b" `((?a . ,a) (?b . ,b))))
;; ⇒ "a = 1; b = 2"
```
# Answer
> 16 votes
Magnar Sveen's string manipulation library s.el provides a variety of ways to do this. For example:
```
(require 's)
(s-format "${name} ${name} ${name}" 'aget '(("name" . "test")))
;; ==> "test test test"
```
Note that `s-format` can take any replacer function, but provides special handling for `aget`, `elt`, and `gethash`. So you could use a list of tokens and reference them by index, like so:
```
(s-format "$0 $0 $0 $1 $1 $1" 'elt '("a" "b"))
;; ==> "a a a b b b"
```
You can also replace using in-scope variables, like this:
```
(let ((name "test"))
(s-lex-format "${name} ${name} ${name}"))
;; ==> "test test test"
```
# Answer
> 4 votes
Not a general-purpose, but will solve your case:
```
(apply 'format "%s %s %s" (make-list 3 'a))
```
Using provided example:
```
(apply 'format (concat " * - :raw-html:`<img width=\"100%%\" "
"src=\"http://xxx.xxx/images/languages/"
"staff/%s.jpg\" alt=\"%s.jpg\"/>` - .. _%s:")
(make-list 3 'some-image))
```
gives:
```
" * - :raw-html:`<img width=\"100%\" src=\"http://xxx.xxx/images/languages/staff/some-image.jpg\" alt=\"some-image.jpg\"/>` - .. _some-image:"
```
# Answer
> 3 votes
s.el's s-lex-format is really what you want, but if you want to actually be able to put code inside the substitution blocks and not just variable names, I wrote this as a proof of concept.
```
(defmacro fmt (str)
"Elisp string interpolation for any expression."
(let ((exprs nil))
(with-temp-buffer
(insert str)
(goto-char 1)
(while (re-search-forward "#{" nil t 1)
(let ((here (point))
(emptyp (eql (char-after) ?})))
(unless emptyp (push (read (buffer-substring (point) (progn (forward-sexp 1) (point)))) exprs))
(delete-region (- here 2) (progn (search-forward "}") (point)))
(unless emptyp (insert "%s"))
(ignore-errors (forward-char 1))))
(append (list 'format (buffer-string)) (reverse exprs)))))
;; demo with variable and code substitution
(fmt "My name is #{user-full-name}, I am running Emacs #{(if (display-graphic-p) \"with a GUI\" \"in a terminal\")}.")
;; results in
"My name is Jordon Biondo, I am running Emacs with a GUI."
```
You can even embed an `fmt` call inside another `fmt` if you're crazy
```
(fmt "#{(fmt\"#{(fmt\\\"#{user-full-name}\\\")}\")}")
;; =>
"Jordon Biondo"
```
The code just expands to a `format` call so all the substitutions are done in order and evaluated at run time.
```
(cl-prettyexpand '(fmt "Hello, I'm running Emacs #{emacs-version} on a #{system-type} machine with #{(length (window-list))} open windows."))
;; expands to
(format "Hello, I'm running Emacs %s on a %s machine with %s open windows."
emacs-version
system-type
(length (window-list)))
```
Improvements could be made with what format type is used instead of always using %s, but that would have to be done at runtime and would add overhead but could be done by surrounding all the format args in a function call that nicely formats things nicely based on type but really the only scenario where you would want that is probably floats and you could even do a (format "%f" float) in the substitution is you were desperate.
If I work on it more, I'm more likely to update this gist instead of this answer. https://gist.github.com/jordonbiondo/c4e22b4289be130bc59b
# Answer
> 3 votes
Since search engines lead me to this page...
Reading `format` documentation, I find the following:
```
A %-sequence other than %% may contain optional field number, flag,
width, and precision specifiers, as follows:
%<field><flags><width><precision>character
where field is [0-9]+ followed by a literal dollar "$", flags is
[+ #0-]+, width is [0-9]+, and precision is a literal period "."
followed by `[0-9]+`.
If a %-sequence is numbered with a field with positive value N, the
Nth argument is substituted instead of the next one. A format can
contain either numbered or unnumbered %-sequences but not both, except
that %% can be mixed with numbered %-sequences.
```
Which means the following will work (well.. it works for me, on Emacs 27.1)
```
(format "%1$s %1$s %1$s" "a") ;; gives: "a a a"
```
---
Tags: format
---
|
thread-61515
|
https://emacs.stackexchange.com/questions/61515
|
How to swap words `true` and `false` in buffer text?
|
2020-11-01T17:38:22.273
|
# Question
Title: How to swap words `true` and `false` in buffer text?
I found myself switching the text `true` to `false`, and vice versa, while coding very often. It's quite tedious to mark the entire thing and replace it with opposite. It would be great to have a function that replaces word under the cursor to `true` if it was `false` and vice versa.
Is there any existing solution to solve that? If not how this can be implemented.
# Answer
Oh, I just wrote this a few days ago. It does nothing more than the package "parrot" recommended in another answer, though. Here's the code:
```
(require 'dash)
(defvar my-flip-symbol-alist
'(("true" . "false")
("false" . "true"))
"symbols to be quick flipped when editing")
(defun my/flip-symbol ()
"\"I don't want to type here, just do it for me.\""
(interactive)
(-let* (((beg . end) (bounds-of-thing-at-point 'symbol))
(sym (buffer-substring-no-properties beg end)))
(when (member sym (cl-loop for cell in my-flip-symbol-alist
collect (car cell)))
(delete-region beg end)
(insert (alist-get sym my-flip-symbol-alist "" nil 'equal)))))
;; TODO here, bind keys to the function with your favorite key binding function
```
> 5 votes
# Answer
Have a look there :(info "(emacs)Regex replacement") exchange ‘x’ and ‘y’ this way:.... so,
```
M-x replace-regexp <RET> \(true\)\|false <RET>
\,(if \1 "false" "true") <RET>
```
should do the trick
*edit:*
Probably this command is much better for your demand
```
(defun swap-true-false ()
(interactive)
(save-excursion
(when (thing-at-point-looking-at "\\b\\(true\\)\\|false\\b")
(replace-match (if (match-string 1) "false" "true")))
))
```
You can bind a key to this command according to your taste, for instance
```
(bind-key (kbd "C-c s") #'swap-true-false)
```
> 4 votes
# Answer
How about parrot.el? You can define you own `parrot-rotate-dict`.
> 2 votes
# Answer
It might be better to change approach, and use global constant variables (if your language supports them) to turn the feature on/off.
> 0 votes
---
Tags: text-editing
---
|
thread-60953
|
https://emacs.stackexchange.com/questions/60953
|
How to get the merged face attributes at point?
|
2020-10-02T15:08:05.800
|
# Question
Title: How to get the merged face attributes at point?
The appearance of a given character is determined by faces from various sources and `face-remapping-alist`. How to determine the properties Emacs ultimately uses after taking all sources into account? What I'm looking for is an attribute list that could be used for the `default` face, i.e. one specifiying all attributes.
`background-color-at-point` and `foreground-color-at-point` come close for the respective attributes. But they don't take into account `face-remapping-alist`.
# Answer
Your question isn't clear to me. But I guess you're asking how to tell what faces actually have a visual effect on a given character.
Not sure this answers the question at all, but:
1. Node Displaying Faces of the Elisp manual says how various faces affect the display of a character they act on.
2. `C-u C-x =` tells you what faces are used on the character after the cursor, from both text properties and overlays. That uses function `describe-char`, which you can use programmatically.
Hopefully someone else will have a better answer for you.
> 0 votes
# Answer
The library face-explorer contains, among else, functions that untangle all face sources. For example `face-explorer-face-attributes-at` returns the attributes used at a position in the buffer. It take `face-remapping-alist` into account.
This package was originally designed to be used be packages that convert text with face information to other formats. Concretely, it's used in the e2ansi package which emits ANSI sequences, to make it possible to display highlighted text in a terminal window.
The package also contains other tools. For example `face-explorer-describe-face` describes a face, including all underlying definitions. (Think of this as a `describe-char` on steroids.)
Or, why not play around with `face-explorer-simulate-display-mode`, a minor mode that simulates how a face (or a theme) would look using, say, a grayscale monitor, or an 8 color terminal.
> 0 votes
---
Tags: faces
---
|
thread-61530
|
https://emacs.stackexchange.com/questions/61530
|
RevTEX 4.1 latex class with Org-Mode
|
2020-11-02T14:14:54.890
|
# Question
Title: RevTEX 4.1 latex class with Org-Mode
I'm trying to get this latex class to work with org, anyone had any luck?
```
(add-to-list 'org-latex-classes
'("revtex"
"\\documentclass[preprint,a4paper, amsfonts, amssymb, amsmath, showkeys, nofootinbib, fleqn]{revtex4-1}
\\usepackage{amsthm}
\\newtheorem{theorem}{Theorem}
\\newtheorem{definition}{Definition}
\\newtheorem{proposition}{Proposition}
\\newtheorem{remark}{Remark}
\\newtheorem{lemma}{Lemma}
\\newtheorem{corollary}{Corollary}
\\bibliographystyle{apsrev4-1}
[EXTRA]
"
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")
("\\paragraph{%s}" . "\\paragraph*{%s}")
("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
```
the org exporter puts the title and author commands in the preamble, while the revtex class requires them to be put in the document section, is there a way to tweak org-exporter to work with it?
# Answer
A long time ago, I had worked on a hack to deal with this peculiarity of `revtex` and reconstructed it for this answer (with some differences to accommodate things that have changed in Org mode, in particular the handling of titles).
The main problem as you note is that `revtex` wants the title, author and date in the body, not in the preamble where just about every *other* package wants it. That in itself is not too difficult to accomplish:
```
#+LATEX: \title{Foo}
```
will put it in the body and similarly for the others. Unfortunately, it will add it *after* the `\maketitle` and `\tableofcontents` constructs in the body, which is too late: we want it before the `\maketitle`.
The LaTeX backend (uniquely among all the backends) defines a variable `org-latex-title-command` whose default value is the string `\maketitle`. Immediately after it outputs the `\begin{document}`, it will output the value of `org-latex-title-command`. In fact, the string can be a template with placeholders like `%t` which will get substituted with the value of the `#+TITLE` keyword. Do `C-h v org-latex-title-command` to see all the placeholders that it can deal with.
So if we could redefine `org-latex-title-command` to the string `\title{%t} \maketitle`, we'd be all set: the LaTeX exporter would insert the `\title{...}` part *and* the `\maketitle` part in the body of the document, as required by `revtex`.
The way to do that is to use the `#+BIND:` keyword mechanism which allows you to define local variables in the temp buffer where the LaTeX output is constructed. The format is
```
#+BIND: variable value
```
This mechanism is considered to be something of a safety risk, so you need to explicitly allow it in your Org mode configuration:
```
(setq org-export-allow-bind-keywords t)
```
Of course, in this case, *you* are the one setting the local variable, so you can judge whether it is unsafe, but in general, you might pick up a malicious Org mode file, so Org mode tries to be conservative in this area.
So the Org mode file would look like this at this point:
```
#+LATEX_CLASS: revtex
#+TITLE: This is the title
#+DATE: November 2, 2020
#+BIND: org-latex-title-command "\\title{%t} \\date{%D} \\maketitle"
* h1
Lorem ipsum etc.
```
Exporting to LaTeX should work and should do what you expect. Note that backslashes are doubled in the string: that's required by elisp.
There is one more wrinkle having to do with `\author` constructs. You would expect that you could add `\author{%a}` to the `#+BIND:` line and add a keyword line like this: `#+AUTHOR: A.U. Thor`, and everything would work, but it does not: the `#+TITLE:` keyword makes the exporter produce a `title{...}` construct *in the preamble*; the `#+AUTHOR:` keyword behaves similarly. But while `revtex` seems unfazed by the existence of the `\title{...}`, it barfs on seeing `\author{...}` in the preamble. So to deal with that wrinkle, we explicitly turn off the effect of the `#AUTHOR:` keyword by turning off the `author` option in the file:
```
#+LATEX_CLASS: revtex
#+OPTIONS: author:nil
#+AUTHOR: A.U. Thor
#+TITLE: This is the title
#+DATE: November 2, 2020
#+BIND: org-latex-title-command "\\title{%t} \\author{%a} \\date{%D} \\maketitle"
* h1
Lorem ipsum etc.
```
A small extract of the resulting LaTeX file looks like this:
```
...
\date{November 2, 2020}
\title{This is the title}
...
\begin{document}
\title{This is the title} \author{A.U. Thor} \date{(November 2, 2020)} \maketitle
\tableofcontents
\section{h1}
\label{sec:org63adbe3}
Lorem ipsum etc.
...
```
There are `\title{}` and `\date{}` constructs in the preamble but they do not matter: Org mode has already substituted their value to the places that *do* matter: the `\title{}` and `\date{}` constructs in the body, just before the `\maketitle`. Note also that even though there is no `\author{}` in the preamble (which was accomplished through the `#+OPTIONS:` setting), the one in the body also has the correct value, substituted in from the value of `#+AUTHOR:` in the Org mode file. And the proof of the pudding is that `revtex` likes the result.
> 4 votes
---
Tags: org-mode, org-export
---
|
thread-7617
|
https://emacs.stackexchange.com/questions/7617
|
How to programmatically execute a command in eshell?
|
2015-01-21T18:47:59.473
|
# Question
Title: How to programmatically execute a command in eshell?
I want to execute simple commands in `eshell` without explicitly typing them into the prompt, using something like `with-current-buffer` How can I do this?
# Answer
My initial hunch was looking for an official command that does this already, so I've found `eshell-command`. However that outputs to a separate buffer, so it's not an option.
Here's an example with `ls` and an `*eshell*` buffer:
```
(with-current-buffer "*eshell*"
(eshell-return-to-prompt)
(insert "ls")
(eshell-send-input))
```
> 16 votes
# Answer
The following proposed solution is intended to permit users to send input programmatically underneath the `eshell` hood, rather than inserting the command into the `eshell` buffer following command prompt. @lawlist has submitted a feature request for the Emacs development team to consider: http://debbugs.gnu.org/cgi/bugreport.cgi?bug=25270
**SAMPLE USAGE**: `(eshell-send-input nil nil nil "ls -la /")`
```
(require 'eshell)
(defun eshell-send-input (&optional use-region queue-p no-newline input-string-a)
"Send the input received to Eshell for parsing and processing.
After `eshell-last-output-end', sends all text from that marker to
point as input. Before that marker, calls `eshell-get-old-input' to
retrieve old input, copies it to the end of the buffer, and sends it.
- If USE-REGION is non-nil, the current region (between point and mark)
will be used as input.
- If QUEUE-P is non-nil, input will be queued until the next prompt,
rather than sent to the currently active process. If no process, the
input is processed immediately.
- If NO-NEWLINE is non-nil, the input is sent without an implied final
newline."
(interactive "P")
;; Note that the input string does not include its terminal newline.
(let ((proc-running-p
(and (eshell-interactive-process)
(not queue-p)))
(inhibit-point-motion-hooks t)
after-change-functions)
(unless (and proc-running-p
(not (eq (process-status (eshell-interactive-process)) 'run)))
(if (or proc-running-p
(>= (point) eshell-last-output-end))
(goto-char (point-max))
;; This is for a situation when point is before `point-max'.
(let ((copy (or input-string-a (eshell-get-old-input use-region))))
(goto-char eshell-last-output-end)
(insert-and-inherit copy)))
(unless (or no-newline
(and eshell-send-direct-to-subprocesses
proc-running-p))
(insert-before-markers-and-inherit ?\n))
(if proc-running-p
(progn
(eshell-update-markers eshell-last-output-end)
(if (or eshell-send-direct-to-subprocesses
(= eshell-last-input-start eshell-last-input-end))
(unless no-newline
(process-send-string (eshell-interactive-process) "\n"))
(process-send-region (eshell-interactive-process)
eshell-last-input-start
eshell-last-input-end)))
(if (and (null input-string-a) (= eshell-last-output-end (point)))
;; This next line is for a situation when nothing is there --
;; i.e., just make a new command prompt.
(run-hooks 'eshell-post-command-hook)
(let (input)
(eshell-condition-case err
(progn
(setq input (or input-string-a
(buffer-substring-no-properties
eshell-last-output-end (1- (point)))))
(run-hook-with-args 'eshell-expand-input-functions
eshell-last-output-end (1- (point)))
(let ((cmd (eshell-parse-command-input
eshell-last-output-end (1- (point)) nil input-string-a)))
(when cmd
(eshell-update-markers eshell-last-output-end)
(setq input (buffer-substring-no-properties
eshell-last-input-start
(1- eshell-last-input-end)))
(run-hooks 'eshell-input-filter-functions)
(and (catch 'eshell-terminal
(ignore
(if (eshell-invoke-directly cmd)
(eval cmd)
(eshell-eval-command cmd input))))
(eshell-life-is-too-much)))))
(quit
(eshell-reset t)
(run-hooks 'eshell-post-command-hook)
(signal 'quit nil))
(error
(eshell-reset t)
(eshell-interactive-print
(concat (error-message-string err) "\n"))
(run-hooks 'eshell-post-command-hook)
(insert-and-inherit input)))))))))
(defun eshell-parse-command-input (beg end &optional args input-string-b)
"Parse the command input from BEG to END.
The difference is that `eshell-parse-command' expects a complete
command string (and will error if it doesn't get one), whereas this
function will inform the caller whether more input is required.
- If nil is returned, more input is necessary (probably because a
multi-line input string wasn't terminated properly). Otherwise, it
will return the parsed command."
(let (delim command)
(if (setq delim (catch 'eshell-incomplete
(ignore
(setq command
(eshell-parse-command
(cons beg end) args t input-string-b)))))
(ignore
(message "Expecting completion of delimiter %c ..."
(if (listp delim)
(car delim)
delim)))
command)))
(defun eshell-parse-command (command &optional args toplevel input-string-c)
"Parse the COMMAND, adding ARGS if given.
COMMAND can either be a string, or a cons cell demarcating a buffer
region. TOPLEVEL, if non-nil, means that the outermost command (the
user's input command) is being parsed, and that pre and post command
hooks should be run before and after the command."
(let* (
eshell--sep-terms
(terms
(if input-string-c
(eshell-parse-arguments--temp-buffer input-string-c)
(append
(if (consp command)
(eshell-parse-arguments (car command) (cdr command))
(let ((here (point))
(inhibit-point-motion-hooks t))
(with-silent-modifications
;; FIXME: Why not use a temporary buffer and avoid this
;; "insert&delete" business? --Stef
(insert command)
(prog1
(eshell-parse-arguments here (point))
(delete-region here (point))))))
args)))
(commands
(mapcar
(function
(lambda (cmd)
(setq cmd (if (or (not (car eshell--sep-terms))
(string= (car eshell--sep-terms) ";"))
(eshell-parse-pipeline cmd)
`(eshell-do-subjob
(list ,(eshell-parse-pipeline cmd)))))
(setq eshell--sep-terms (cdr eshell--sep-terms))
(if eshell-in-pipeline-p
cmd
`(eshell-trap-errors ,cmd))))
(eshell-separate-commands terms "[&;]" nil 'eshell--sep-terms))) )
(let ((cmd commands))
(while cmd
(if (cdr cmd)
(setcar cmd `(eshell-commands ,(car cmd))))
(setq cmd (cdr cmd))))
(if toplevel
`(eshell-commands (progn
(run-hooks 'eshell-pre-command-hook)
(catch 'top-level (progn ,@commands))
(run-hooks 'eshell-post-command-hook)))
(macroexp-progn commands))))
(defun eshell-parse-arguments--temp-buffer (input-string-d)
"Parse all of the arguments at point from BEG to END.
Returns the list of arguments in their raw form.
Point is left at the end of the arguments."
(with-temp-buffer
(insert input-string-d)
(let ((inhibit-point-motion-hooks t)
(args (list t))
delim)
(with-silent-modifications
(remove-text-properties (point-min) (point-max)
'(arg-begin nil arg-end nil))
(goto-char (point-min))
(if (setq
delim
(catch 'eshell-incomplete
(while (not (eobp))
(let* ((here (point))
(arg (eshell-parse-argument)))
(if (= (point) here)
(error "Failed to parse argument '%s'"
(buffer-substring here (point-max))))
(and arg (nconc args (list arg)))))))
(throw 'eshell-incomplete (if (listp delim)
delim
(list delim (point) (cdr args)))))
(cdr args)))))
```
> 3 votes
# Answer
I wrote this function for it,
```
(defun run-this-in-eshell (cmd)
"Runs the command 'cmd' in eshell."
(with-current-buffer "*eshell*"
(eshell-kill-input)
(end-of-buffer)
(insert cmd)
(eshell-send-input)
(end-of-buffer)
(yank)
))
```
It will first kill the input already present, run `cmd` and then yank the input that was present back.
> 0 votes
# Answer
`Package-install RET eshell-toggle`, then use this piece of code as a function or whatever.
```
(progn
(eshell-toggle)
(eshell-return-to-prompt)
(insert *command*)
(eshell-send-input))
```
> 0 votes
---
Tags: elisp, eshell
---
|
thread-61481
|
https://emacs.stackexchange.com/questions/61481
|
Print shell-command output to STDOUT?
|
2020-10-30T13:54:43.647
|
# Question
Title: Print shell-command output to STDOUT?
Is there an equivalent of C's `system(char*)` or Python's `os.system(string)` for `emacs --script`?
I want to use Emacs for shell-scripting purposes. However, I cannot find a function that allows running an executable in a subprocess and connectings its STDOUT/STDERR directly to the terminal.
`make-process`, `call-process`, `start-process`, `shell-command`, `async-shell-command` all require a lot of additional code to forward the process output from either an intermediate Emacs buffer or by using filter functions.
I am looking for a solution that replicates the simplicity of `int status = system("ls -l");`. Ideally, it should be a builtin feature of Emacs to avoid having to set up `EMACSLOADPATH`.
# Answer
The command `shell-command-to-string` will capture STOUT from a program to a string. You can then do what you like with that string in your script. Simply passing it to `message` will print it out to STDOUT:
```
emacs --batch --eval '(message (shell-command-to-string "ls -lh"))'
```
> total 384K
> drwxr-xr-x 2 smithty domain users 4.0K Oct 28 09:16 bin
> drwxr-xr-x 9 smithty domain users 4.0K Nov 2 09:27 blogdown
> drwxr-xr-x 2 smithty domain users 4.0K Oct 1 13:18 Desktop
> drwxr-xr-x 2 smithty domain users 4.0K Nov 2 15:46 dl
> drwxr-xr-x 2 smithty domain users 4.0K Oct 14 21:27 Documents
> drwxr-xr-x 4 smithty domain users 4.0K Nov 1 17:14 hacking
> -1 votes
---
Tags: shell-command, script
---
|
thread-61534
|
https://emacs.stackexchange.com/questions/61534
|
Why is the matplotlib plot produced by executing `org-babel-execute-src-block` contain errors?
|
2020-11-02T19:55:19.667
|
# Question
Title: Why is the matplotlib plot produced by executing `org-babel-execute-src-block` contain errors?
# The context
Consider the following Emacs configuration
```
$ cat ~/.emacs.d/init.el
(org-babel-do-load-languages 'org-babel-load-languages
'((python . t)))
$
```
and the following Org mode file
```
$ cat ~/Experiments/main.org
#+begin_src python :tangle main.py :results file :file 1.png
from matplotlib import pyplot
x = [1, 2, 3]
y = [1, 4, 9]
pyplot.plot(x, y)
pyplot.savefig('1.png')
#+end_src
$
```
If I tangle the Python code block (i.e. execute `org-babel-tangle`), execute the Python script (i.e. execute `python main.py` in a shell) and obtain the hash of the resulting image I get
```
$ pwd
/home/myusername/Experiments
$ python main.py
$ sha512sum 1.png && du -h 1.png
084ffd63ec53665c21fc3eaba5f5ec3622d4d27a97f89cb67e3b436ca8093467272bbc239fd0e60dde27f5207ee33392f5b83b9eca1427efe7523450d92a6a8c 1.png
20K 1.png
```
I can open `1.png` with `firefox` and `mpv` without any problems.
If I execute the code block in Emacs by pressing `C-c C-c` (i.e. execute `org-babel-execute-src-block`) while the cursor is in the `#+BEGIN_SRC` block, I get the following
```
$ sha512sum 1.png && du -h 1.png
e39d05b72f25767869d44391919434896bb055772d7969f74472032b03bc18418911f3b0e6dd47ff8f3b2323728225286c3cb36914d28dc7db40bdd786159c0a 1.png
4.0K 1.png
```
Note that the size of `1.png` is significantly lower than the size shown above.
# Additional context
In addition to that, if I try to open the image with `mpv`, I get the following error
```
$ mpv 1.png
(+) Video --vid=1 (png 1.000fps)
[ffmpeg/video] png: Invalid PNG signature 0x00000000.
Error while decoding frame!
(Paused) V: 00:00:01 / 00:00:01 (100%)
[ffmpeg/video] png: Invalid PNG signature 0x00000000.
Error while decoding frame!
(Paused) V: 00:00:01 / 00:00:01 (100%)
```
An error is also shown when I try to open the image in `firefox` (see image below)
The error is not present in both `firefox` and `mpv` when producing the image `1.png` by executing the script in a shell.
# The question
* Why is the file `1.png` obtained after executing `org-babel-execute-src-block` different than the one produced by tangling the `#+BEGIN_SRC` block and executing `python main.py` in a shell?
* Why does the resulting file `1.png` contain errors?
# Answer
> 3 votes
Change `:results file` to `:results file graphics`.
# Answer
> 1 votes
Here's an explanation to go with @darcamo's answer:
When you say `:results file :file 1.png`, babel creates a file `1.png` containing the result of running the block (in the default case of `:results value`) or the standard output (in the `:results output` case) and puts a link to that file as the result of the evaluation of the block.
In your case, the source block returns the value that `pyplot.savefig(...)` returns, which happens to be `None`. The block also writes the image into `1.png` (that's what `savefig()` does after all), but then babel saves the result and overwrites the image with the word `None`. So you end up with a "corrupt" PNG file: check it with `ls -l` and `cat`: it's 4 bytes long containing the characters `None`.
---
OTOH, when you say `:results file link :file 1.png` (or `:results file graphics :file 1.png` \- they do the same thing), babel just puts a link to a (non-existent) file called `1.png` as the result of the evaluation but *does not create the file*. It just runs the block which, as a side effect, produces the file `1.png` \- a real PNG file in this case, since babel does not overwrite it. Note that there is a conspiracy involved: babel creates a link to `1.png` but has no idea what file (if any) the block is going to produce: *you* have to make sure that the file produced by the block has the same name - if the names are different, then the link is not going to work.
---
Tags: org-mode, org-babel, python
---
|
thread-10294
|
https://emacs.stackexchange.com/questions/10294
|
Relative dates in org template
|
2015-03-25T14:30:48.877
|
# Question
Title: Relative dates in org template
I organize a technical user group and as part of that I use org-mode to schedule the same task tree every month so I remember to do everything for our meetings (food, speakers, projector, etc.) This, to me, sounds like a perfect use case for a capture template. What I'd like to do is specify an event name and date and have the rest of the tasks automatically calculated based on that. Here's the template I have so far (simplified a bit to show what I want to do):
```
("m" "Meetup" (file+headline "~/org/STLPython.org" "events")
"** %^{Event}\n%^{Date}t\n*** Send a reminder to the group\nSCHEDULED: <%<%^{Date}t -5d>>"))
```
Ideally, I'd get this output, after specifying "Event" and "Date" once each:
```
** Documenting with Sphinx: Beyond Quickstart
<2015-05-05 Tue>
*** Send a reminder to the group
SCHEDULED: <2015-05-30 Thu>
```
Instead, I get this output, and I have to specify "Date" twice:
```
** Documenting with Sphinx: Beyond Quickstart
<2015-05-05 Tue>
*** Send a reminder to the group
Scheduled: <<2015-05-05 Tue> -5d>
```
So I guess I have two questions:
1. how can I "reuse" an already captured variable?
2. how can I modify the date? I saw an answer using `%(...)` and now can't find it again, and at any rate it didn't seem to accept arguments.
# Answer
> 3 votes
Instead of using the built in templates you can build your own via a function and pass this as the final argument to the capture template. Then you can use arbitrary elisp to manipulate data. Here is an example in your case, that uses `org-completing-read-no-i` for string prompts and `org-read-date` for date input. I have updated it to show how to set a schedule on a date 5 days earlier (calculated as 3600 secs times 24 times 5):
```
(defun my-event-template ()
"Capture template for events"
(let* ((event (org-completing-read-no-i "Event: " nil))
(date-input (org-read-date nil t nil "Date: "))
(date (format-time-string
(car org-time-stamp-formats)
date-input))
(date+shift (concat (substring date 0 -1) " -5d" (substring date -1)))
(date-schedule (format-time-string (car org-time-stamp-formats)
(time-subtract date-input
(seconds-to-time (* 3600 24 5))))))
(format "** %s\n %s\n*** Send a reminder to the group\n DEADLINE: %s SCHEDULED: %s"
event date date+shift date-schedule)))
(custom-set-variables
'(org-capture-templates
(quote
(("m" "Meetup" entry (file+headline "~/org/STLPython.org" "events")
(function my-event-template))))))
```
Typical output from this is
```
** My event
<2015-03-29 Sun>
*** Send a reminder to the group
DEADLINE: <2015-03-29 Sun -5d> SCHEDULED: <2015-03-24 Tue>
```
The object `(car org-time-stamp-formats)` is the standard format for an active timestamp.
# Answer
> 2 votes
Here is my solution to a similar situation. I create a headline for a candidate, which contains a property with today's date, and add a child headline with a deadline two days in the future from today.
Here is the portion of the capture template for the child headline:
```
*** %\\1 :waitreply:sentrequest:
DEADLINE: %(org-insert-time-stamp (org-read-date nil t \"+2\"))
```
It took me longer than I care to admit to figure this out, but I'm happy with the solution. org-read-date with these parameters produces an internal time value, which org-insert-time-stamp converts into a timestamp.
---
Tags: org-mode
---
|
thread-61523
|
https://emacs.stackexchange.com/questions/61523
|
Force one window when opening multiple files
|
2020-11-02T01:39:07.503
|
# Question
Title: Force one window when opening multiple files
Any time I open multiple files I'd like emacs to only show me one buffer. I do not want any split windows. This would save me a keystroke every time.
I learned I could do away with the buffer list from this post with `(setq-default inhibit-startup-buffer-menu t)`. But, now another buffer just replaces what would have been the buffer list. Any way to force only one window when opening multiple files?
# Answer
> 1 votes
I don't quite understand your last comment, but try the following in your init file:
```
(setq inhibit-splash-screen t)
(setq command-line-functions (list #'handle-files))
(defun handle-files ()
(let* ((files (cons argi command-line-args-left))
(lastfile (car (last files)))
(files (butlast files)))
(while files
(find-file-noselect (car files))
(setq files (cdr files)))
(if lastfile
(find-file lastfile))
(setq command-line-args-left nil)
t))
```
The assumption is that all the options are already processed and you just have a list of files at the end of your command line. Each function in the list `command-line-functions` is called with no args (do `C-h i g (elisp)command-line-arguments` to read the relevant section of the Elisp manual in emacs or see the online Elisp manual for details). There is only one function in this case and it consumes all of the left-over arguments: it does a `find-file-noselect` on all of them except the last one, on which it does a `find-file`.
Doing `emacs -Q -l /path/to/init/file.el a b c d` does what you want (I think).
EDIT: per the OP's comment, I fixed up the code so that it works with 0, 1 and 2 file arguments. By induction, it has to work for any number of arguments :-)
---
Tags: buffers, window, window-splitting
---
|
thread-61547
|
https://emacs.stackexchange.com/questions/61547
|
Emacs can't connect to GNU archive
|
2020-11-03T03:08:10.237
|
# Question
Title: Emacs can't connect to GNU archive
I'm having a very basic problem with getting my emacs to talk to the GNU package repository.
The contents of my .emacs are
```
(require 'package)
(package-initialize)
(package-refresh-contents)
```
When I start up emacs, I see
```
Contacting host: elpa.gnu.org:443
Package refresh done
Failed to download ‘gnu’ archive.
```
When I do `M-x toggle-debug-on-error` and then `M-x package-refresh-contents`, I get the following stacktrace:
```
Debugger entered--Lisp error: (file-error "https://elpa.gnu.org/packages/archive-contents" "Bad Request")
signal(file-error ("https://elpa.gnu.org/packages/archive-contents" "Bad Request"))
package--download-one-archive(("gnu" . "https://elpa.gnu.org/packages/") "archive-contents" nil)
package--download-and-read-archives(nil)
package-refresh-contents()
funcall-interactively(package-refresh-contents)
call-interactively(package-refresh-contents record nil)
command-execute(package-refresh-contents record)
execute-extended-command(nil "package-refresh-contents" "package-refre")
funcall-interactively(execute-extended-command nil "package-refresh-contents" "package-refre")
call-interactively(execute-extended-command nil nil)
command-execute(execute-extended-command)
```
I originally was trying to connect to Melpa, but I saw I have this issue even working with just the GNU archive. I'm on Emacs 26.2, macOS 10.14.6.
Any ideas?
# Answer
> 2 votes
I believe that Emacs 26.3 fixes this.
You should upgrade (26.2 to 26.3 is a very minor update; nothing should break); but if you genuinely cannot do that for some reason, then this might do the trick for you:
```
(setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")
```
You could also consider installing 27.1, which is the latest release.
---
Tags: init-file, http
---
|
thread-61535
|
https://emacs.stackexchange.com/questions/61535
|
Org mode macro for including content of another org mode file
|
2020-11-02T20:04:10.453
|
# Question
Title: Org mode macro for including content of another org mode file
I'm trying to wrap my head around why the following macro does not work:
```
#+MACRO: INCLUDE_ORG #+INCLUDE: "$1::$2" :minlevel 3 :only-contents t
```
This is how I'm using it:
```
{{{INCLUDE_ORG(./somefile.org,Some long heading with spacesj)}}}
```
I was experimenting with putting quotes here and there without any progress. Using regular include without macro works just fine.
Could you please help me understand what causes the issue?
# Answer
> 3 votes
It does not work because macro expansion happens *after* include processing: by the time the macro is expanded and you have `#+INCLUDE:` in the output, it is too late.
The code is in the function `org-export-as` in file `ox.el`, ll.2948-2953:
```
...
(org-export-with-buffer-copy
;; Run first hook with current back-end's name as argument.
(run-hook-with-args 'org-export-before-processing-hook
(org-export-backend-name backend))
(org-export-expand-include-keyword)
(org-export--delete-comment-trees)
(org-macro-initialize-templates)
(org-macro-replace-all (append org-macro-templates
org-export-global-macros)
parsed-keywords)
...
```
# Answer
> 0 votes
Fixed that behavior by applying following fix to `org-export-as` function in ox.el.
```
(org-export-expand-include-keyword)
(org-export--delete-comment-trees)
(org-macro-initialize-templates)
(org-macro-replace-all (append org-macro-templates
org-export-global-macros)
parsed-keywords)
;; Duplicate include, initialize, replace before refresh
(org-export-expand-include-keyword)
(org-export--delete-comment-trees)
(org-macro-initialize-templates)
(org-macro-replace-all (append org-macro-templates
org-export-global-macros)
parsed-keywords)
```
---
Tags: org-mode, org-export
---
|
thread-61552
|
https://emacs.stackexchange.com/questions/61552
|
How can I actually evaluate a #+CALL statement?
|
2020-11-03T09:26:10.763
|
# Question
Title: How can I actually evaluate a #+CALL statement?
I have several named source blocks in an .org file. I can execute each of them by pressing `C-c C-c` when point is on (or in) them. Now I want to call them in a row. So I added some call statements:
```
#+CALL: named_function_1
#+CALL: named_function_2
```
How can I evaluate these call statements? `C-c C-c`does nothing.
# Answer
You have to add parentheses after the name of the function in order for the function to be called:
```
#+CALL: named_function_1()
#+CALL: named_function_2()
```
See the manual.
> 3 votes
---
Tags: org-mode, org-babel
---
|
thread-61557
|
https://emacs.stackexchange.com/questions/61557
|
How to build and install R package in ESS?
|
2020-11-03T16:25:02.303
|
# Question
Title: How to build and install R package in ESS?
Some time ago I've written function to build R package using "CMD INSTALL" the problem is that I can't do the same with ESS. There is function `ess-r-devtools-build` but it seems that it don't actually install the package I'm working on it just build tar.gz file.
How can I build and install R package I'm developing in Emacs ESS?
# Answer
> 0 votes
ESS provides the function `ess-r-devtools-load` that will run the function `devtools::load_all()` for you. That will load the current version of your package while you are working on it.
---
Tags: ess
---
|
thread-61543
|
https://emacs.stackexchange.com/questions/61543
|
Realgud to default to my most recent python executable
|
2020-11-03T00:37:13.317
|
# Question
Title: Realgud to default to my most recent python executable
When I run realgud for python debugging, with:
`M-x realgud:pdb`
I see this prompt:
```
Run pdb (like this): python -m pdb /home/username/work/place/scratch.py
```
I'm using a conda environment installed in `./place/environments/default/`, so I'd like to use the python executable at `./place/environments/default/bin/python`
This means I have to type out a correction to use a different python:\`
```
Run pdb (like this): /home/username/work/place/environments/default/bin/python -m pdb /home/username/work/place/scratch.py
```
installed in that directory every time I invoke pdb, which is tedious.
I have multiple projects in
```
/home/username/work/
```
So I can't just hard-code /one/, it needs to be configurable---but I'd like something like the following:
1. Default to using the last python binary I used but otherwise make me type this once.
2. Multi-step dialog, where the first step chooses a python (and defaults to last time).
3. Some variable I can set once per project and get picked up
4. Being able to tab complete here.
What options do I have to reduce the amount I have to type to change the python invoked?
# Answer
Realgud:ipdb has a variable that indicate the command-name, is called `realdu:pdb-command-name` by default is set to "python -m pdb", but it can easily be adapted to use with differents projects (I'm assuming that you are using projectile, if it's not the case, take a look at project.el)
We can assume that the location of the python executable has some similarities between projects (it's in the environment directory in the root project) if it's not the case, Directory-Variables may help you, as you can define this variable in every directory regardless of the project.
So, for the first case, we can use a `python-mode-hook` and add some logic:
```
(add-hook 'python-mode-hook
(lambda ()
(let* ((conda-python (format "%/environments/default/bin/python -m pdb" (projectile-project-root))))
(setq-local realgud:pdb-command-name conda-python))
))
```
This hook will ensure that for every file in a project, it will set a different variable, making possible to work with differents projects at the same time, mostly because we are using a buffer-local variable.
When realgud:pdb is launch, it will put the correct projectile base root, and will concat the file name at the end, making the file selection automatic.
For the 2 and 4 request, it is not implemented, but it can be an interesting addition to the realgud project, I really suggest you to contribute it (or open an issue) to the realgud project.
Good luck!
> 1 votes
---
Tags: debugging, elpy, realgud
---
|
thread-61497
|
https://emacs.stackexchange.com/questions/61497
|
elpy (and evil-mode) do not react on TAB
|
2020-10-31T11:23:26.973
|
# Question
Title: elpy (and evil-mode) do not react on TAB
This is my `elpy-config`
```
1Elpy Configuration
2
3Virtualenv........: None
4RPC Python........: 3.7.3 (/usr/bin/python3)
5Interactive Python: /usr/bin/python3 (/usr/bin/python3)
6Emacs.............: 26.1
7Elpy..............: 1.28.0
8Jedi..............: 0.17.2
9Rope..............: Not found
10Autopep8..........: 1.5.3
11Yapf..............: Not found
12Black.............: Not found
13Syntax checker....: flake8 (/usr/local/bin/flake8)
```
It runs on Debian 10.
When typing `TAB` nothing happens. No message. No change in the mode line or status line.
Is it default that elpy do not work with `TAB` and why?
How can I turn this on?
**EDIT**: I expect 4 empty chars when typing `TAB`.
**EDIT2**: `M-x describe-key <kbd>TAB</kbd>` results in
```
TAB (translated from <tab>) runs the command evil-jump-forward (found in
evil-motion-state-map), which is an interactive compiled Lisp function in
‘~/.MyAppData/emacs.d/elpa/evil-20201014.2043/evil-commands.el’.
It is bound to TAB.
(evil-jump-forward &optional COUNT)
Go to newer position in jump list.
To go the other way, press C-o.
```
I have `evil-mode` installed and activated. So there must be a reason why TAB is used by `evil-mode` but do not work.
# Answer
> 0 votes
This answer is based on this evil-mode mailinglist post
**Short answer**: This is expected behavior.
**Long answer**: In python-mode (and elpy), when you start typing, hitting `TAB` will not do anything, presumably preventing you from accidental `TAB` inserts which will trigger errors in Python interpreter. The other way arround `TAB` results in a "Tab" (e.g. 4 chars) in cases where it is allowed in python context.
e.g. type this two lines
```
def foo():
"""
```
after hitting `RET` the cursor jumps in the next (3rd) line but at the first character/column. Now you are "allowed" to hit `TAB` and it works as expected: A "Tab" (4 empty chars) are inserted. Hitting `TAB` again is like pressing `BACKSPACE`: The "Tab" is deleted and the cursor is back at column 1.
However, if you want to insert `TAB` forcefully see the section Indentation Controlled by Major Mode in the emacs-documentation. E.g. setting `(setq tab-always-indent nil)` will force `TAB` to be inserted, but will also adjust other indentation.
However, if you want `vi`-like `TAB` behavior with `evil-mode`, python and without too much of TAB science, set this in your init file:
```
(define-key evil-insert-state-map (kbd "TAB") 'tab-to-tab-stop)
```
If you are keen to look further for customization, check The Ultimate Guide To Indentation in Emacs.
# Answer
> 1 votes
I'm not sure but probably one of your minor modes overrides the `TAB` key.
You can find the bound function via `M-x describe-key` and `TAB`. Default should be `indent-for-tab-command`. If it is not, you should find which minor mode overrides the `TAB` binding (you can probably understand using `describe-key`) and unbind it on the minor-mode keymap or rebind `TAB` to `indent-for-tab-command`.
ex: https://stackoverflow.com/a/14316669/7216840
# Answer
> -1 votes
Evil faithfully emulates Vim, including the part of `C-i` and `C-o` being bound in normal state to commands going through the jump list. `C-i` happens to be equivalent to `TAB` for reasons (hello terminals), so another thing you'll observe is it being bound in insert state to something else, like an indentation command. If you dislike that behavior, you've got two options:
---
Tags: python, evil, elpy, tabs
---
|
thread-61544
|
https://emacs.stackexchange.com/questions/61544
|
How to modify a file you're debugging with realgud
|
2020-11-03T01:58:08.617
|
# Question
Title: How to modify a file you're debugging with realgud
I understand mechanically from here:
I can use `C-x C-q` to disable read-only mode on the python file I am debugging. I can then make changes and use `run` to restart the debugger.
However, I find that when I do this, whenever I edit the file that I am debugging, I am faced with the following error:
```
That’s all folks.... exited abnormally with code 1
```
How can I make changes to a file I am debugging and then re-run it without the debugger crashing? My read is that the file is read-only for a reason, and when I modify it while pdb is running I invite disaster---but this suggests to me there is an approved way to do this correctly. What is it?
# Answer
The thing is, the pdb debugger has the file loaded, so when you are editing the file (or buffer), it doesn't change it in the memory of the debugger, so it will ignore the changes until you call it again.
This issue is more related to the debugger itself, realgud it's just making sure of the file consistency, so it doesn't make too much sense to edit it in that scenario.
Still, there is probably a way to "hot reload" the debugger and get back to the pdb previous stage, but it's not implemented.
> 2 votes
---
Tags: python, debugging, realgud
---
|
thread-61465
|
https://emacs.stackexchange.com/questions/61465
|
speedbar sr-speedbar flush cache and full expand current buffer when saving it
|
2020-10-29T11:20:59.537
|
# Question
Title: speedbar sr-speedbar flush cache and full expand current buffer when saving it
I'm using sr-speedbar.
I would like it to automatically full expand current file buffer, and update the bar content when I save the current buffer.
I tried something like : `(add-hook 'after-save-hook 'speedbar-flush-expand-line)` in my init file but it does not work since my cursor is in my file buffer window. The point is to have tags of file buffer always displayed and up to date with file content on disk.
# Answer
> 1 votes
This was my approximation, it's a simple function that take care of the main nodes and updates the content when the buffer is save. **Explained below**
```
(defun sb/expand-tags ()
"Expand current `sr-speedbar' buffer file."
(interactive)
;; We assume that the speedbar name is the same as the file of the buffer
(let* ((current-buffer-name (file-name-nondirectory (buffer-file-name)))
(file-point nil)
(line-list '()))
(with-current-buffer speedbar-buffer
;; Refresh the current speedbar buffer
(speedbar-refresh)
(goto-char (point-min))
(re-search-forward current-buffer-name)
(setq file-point (point))
;; This function make the point go backwards so we have to save the location
(speedbar-flush-expand-line)
(goto-char file-point)
;; We enter the "expanded" attributes
(forward-line)
(while
;; Check if we reach another file, or the end of the buffer.
(and (not (speedbar-line-file))
(not (equal (point) (point-max))))
(push (point) line-list)
(forward-line))
;; Once we have the point of the main branches, we iterate
;; and expand his content
(seq-map (lambda (line)
(goto-char line)
(speedbar-flush-expand-line))
line-list))))
;; Add it to the save-hook
(add-hook 'after-save-hook 'sb/expand-tags)
```
There is a couple of things that I had to take into account in order to create this function:
1. I assume that the important nodes are the main ones just in the first depth.
2. When the speedbar buffer is refresh, it will only show the expanded information of the current file
3. The speedbar file node has the same name as the current buffer file.
This function can be added to the main file and has no external dependencies (except for sr-speedbar of course)
If it is necessary I can change the above points to fit the requirements.
Good luck!
---
Tags: speedbar
---
|
thread-30928
|
https://emacs.stackexchange.com/questions/30928
|
Control window splitting while opening on files with helm
|
2017-02-21T14:42:30.717
|
# Question
Title: Control window splitting while opening on files with helm
I am trying to be able to control where a new window should go, when I use `helm-find-files`. I am aware of `split-height-threshold` and `split-width-threshold`, and it works if I set them to behave appropriately (`setq` outside the defuns). But what I am trying to do is set them temporarily before calling the function that actually splits the window (here, `helm-ff-run-switch-other-window`). However, even though these 2 variables have the correct values (using `let`), the functions don't seem to do anything. Perhaps the code will explain it better:
```
(defun my/helm-switch-other-window-horizontally ()
(interactive)
(let ((split-height-threshold 0)
(split-width-threshold nil))
(helm-ff-run-switch-other-window)))
(defun my/helm-switch-other-window-vertically ()
(interactive)
(let ((split-height-threshold nil)
(split-width-threshold 0))
(helm-ff-run-switch-other-window)))
(define-key helm-find-files-map (kbd "C-c s") 'my/helm-switch-other-window-horizontally)
(define-key helm-find-files-map (kbd "C-c v") 'my/helm-switch-other-window-vertically)
```
I guess I'm doing something wrong with variable binding?
# Answer
> 0 votes
The following is based on your own code, which works as expected from here.
```
(defun my/helm-switch-other-window-horizontally ()
(interactive)
(with-helm-alive-p
(helm-exit-and-execute-action
(lambda (candidate)
(let ((split-height-threshold 0)
(split-width-threshold nil))
(helm-find-files-other-window candidate))))))
(defun my/helm-switch-other-window-vertically ()
(interactive)
(with-helm-alive-p
(helm-exit-and-execute-action
(lambda (candidate)
(let ((split-height-threshold nil)
(split-width-threshold 0))
(helm-find-files-other-window candidate))))))
(define-key helm-find-files-map (kbd "C-c s") 'my/helm-switch-other-window-horizontally)
(define-key helm-find-files-map (kbd "C-c v") 'my/helm-switch-other-window-vertically)
```
---
I don't have answer on why your let-binding don't work since I am not familiar with the internal of helm. Maybe the following may provide a clue:
```
(defvar x nil)
(defun foo ()
(message "-> %s" x))
(let ((x 42))
(foo))
;; Print "-> 42"
(let ((x 42))
(run-at-time nil nil 'foo))
;; Print "-> nil"
```
as you can see let-binding `x` doesn't work for `run-at-time`.
# Answer
> 0 votes
The variables in let can not be accessed by functions outside. `setq-local split-height-threshold nil` should work.
# Answer
> 0 votes
Solution that worked for me in current version of helm, was overriding **helm-window-prefer-horizontal-split**
```
(defun my/helm-switch-other-window-horizontally ()
(interactive)
(with-helm-alive-p
(helm-exit-and-execute-action
(lambda (candidate)
(let ((helm-window-prefer-horizontal-split nil))
(helm-find-files-other-window candidate))))))
(defun my/helm-switch-other-window-vertically ()
(interactive)
(with-helm-alive-p
(helm-exit-and-execute-action
(lambda (candidate)
(let ((helm-window-prefer-horizontal-split t))
(helm-find-files-other-window candidate))))))
(define-key helm-find-files-map (kbd "C-c 2") 'my/helm-switch-other-window-horizontally)
(define-key helm-find-files-map (kbd "C-c 3") 'my/helm-switch-other-window-vertically)
```
---
Tags: helm, window-splitting
---
|
thread-61570
|
https://emacs.stackexchange.com/questions/61570
|
save emacs desktop regarding tmux session
|
2020-11-04T11:07:51.623
|
# Question
Title: save emacs desktop regarding tmux session
I use emacs in different tmux sessions. Each time I run new emacs instance it says:
`Warning: desktop file appears to be in use by PID <pid>. Using it may cause conflicts. Use it anyway? (y or n)`
Is there standard way to save desktop per each tmux(screen) session?
# Answer
> 0 votes
As is stated in the warning, the desktop file is locked by emacs (you can see a `.emacs.desktop.lock` file alongside `.emacs.desktop`), otherwise free access to the file by multiple emacs instances can lead to a race condition.
How to solve this depends on your needs:
1. most likely, you want to save all desktop info (from different tmux sessions) in the same place, then you just need to start emacs in daemon mode, by either starting emacs with `emacs --daemon` or evaluating `(server-start)` somewhere like init file. Then in tmux session cli, you edit files with `emacsclient`, I personally do `alias e="emacsclient -n"`. Now you essentially use one same emacs instance howmany times you `emacsclient`, so it can hold the lock itself with no problem.
2. rare case is that you want different desktops for different tmux session etc.. Then you may start real emacs instances like you formerly do, but set different `desktop-basefilename` each time you start one. Something like `emacs --eval '(setq desktop-basefilename "tmux-1")'`
---
Tags: desktop, tmux
---
|
thread-61576
|
https://emacs.stackexchange.com/questions/61576
|
Ripgrep default search
|
2020-11-04T15:02:27.713
|
# Question
Title: Ripgrep default search
I have been using `projectile-ripgrep` for a few months and I'm pretty happy with it. A few days ago I was testing some of is options and the default search for ripgrep (what I see in the minibuffer) changed from:
```
[my-project] Ripgrep search for (default my_function):
```
to:
```
[my-project] Ripgrep search for: my_function
```
I find it a bit annoying since I like how it used to *suggest* the search (same as when you do a `query-replace`), meaning that if I did not enter any character, it would search the *suggested* term. Now that term is already part of the input, so if I want to search for something else I have to delete it first.
I am not sure how I changed this and I am not able to set it back to how it was. Any ideas?
# Answer
> 2 votes
I've figured out why this is happening to your environment after reading your comments below.
There are two `projectile-ripgrep` (package projectile & package projectile-ripgrep). Whichever is loaded second in order is being used, hence the different behavior on your machine.
---
Original answer:
(I don't have enough reputation to add a comment.)
Which version of `projectile` are you using? Are we looking at the same code here?
If so, could you try playing around with the following expression and see what happens? (Both in your current settings and `emacs -Q`)
```
(read-string (format "%s%s: " "prefix " "(default label)") nil nil "default retval")
```
---
Tags: projectile, ripgrep
---
|
thread-29512
|
https://emacs.stackexchange.com/questions/29512
|
emacsclient opens a file and does eval simultaneously
|
2016-12-22T18:53:05.580
|
# Question
Title: emacsclient opens a file and does eval simultaneously
I know that emacs can open a file while evaluating an expression:
```
emacs file --eval "(toggle-frame-maximized)"
```
However I failed to replicate this with emacsclient:
**1.emacsclient can open a file:**
```
emacsclient file
```
**2.And it can also evaluate an expression:**
```
emacsclient --eval "(toggle-frame-maximized)"
```
**3.But a problem happens when the two are put together:**
```
emacsclient file --eval "(toggle-frame-maximized)"
```
It starts to report error and does not open the file. So is it possible to use emacsclient to open a file while still do eval?
# Answer
After several attempts I think I found the solution, basically just put everything into eval and concatenate them use progn:
```
emacsclient --eval "(progn (find-file \"file\") (toggle-frame-maximized))"
```
> 2 votes
# Answer
Instead of using the `--eval` option for `emacsclient` you could just add your elisp code to `server-visit-hook` in its customization buffer. This way you still get the normal behaviour of returning to the shell after exiting the server buffer.
> 1 votes
---
Tags: emacsclient
---
|
thread-61556
|
https://emacs.stackexchange.com/questions/61556
|
Can we do `C-c >` and `>` and `>` to continue indentation
|
2020-11-03T15:59:38.390
|
# Question
Title: Can we do `C-c >` and `>` and `>` to continue indentation
I am using following answer to handle indentations Emacs bulk indent for Python
> `C-c >` or `C-c C-l` shifts the region 4 spaces to the right
> `C-c <` or `C-c C-r` shifts the region 4 spaces to the left
---
If I do `C-c >` and `>`; the selected text becomes `>`; or if I do `C-c <` and `<`; the selected text becomes `<`.
I was wondering can we do following:
=\> `C-c >` , `>` , `>` to continue to indent 4 space to right one after another
=\> `C-c <` , `<` , `<` to continue to indent 4 space to left one after another
# Answer
I have two suggestions, one, not using any non-default packages, very closely based on the definition of `text-scale-adjust` and one using `hydra`.
### Self-contained
```
;; -*- lexical-binding: t -*-
;; the previous line needs to be the first in the given file.
(require 'python) ;; alternatively use an appropriate `use-package` declaration
(defun python-indent-adjust (count)
"Shift relevant lines by COUNT columns to the right or left.
If the region is active, then the `relevant' lines are those in
the region. Otherwise, it's just the current line.
COUNT may be passed as a numeric prefix argument. It defaults to
‘python-indent-offset’.
The actual adjustment made depends on the final component of the
key-binding used to invoke the command, with all modifiers removed:
< Shift the indendation to the left
> Shift the indendation to the right
After adjusting, continue to read input events and further adjust
the indentation as long as the input event read \(with all
modifiers removed) is one of the above characters.
This command is a special-purpose wrapper around the
`python-indent-shift-right' and `python-indent-shift-left' commands."
(interactive "P")
(let ((start (if mark-active (region-beginning) (line-beginning-position)))
(end (if mark-active (region-end) (line-end-position)))
(count (if count count python-indent-offset)))
(let ((ev last-command-event)
(echo-keystrokes nil))
(let* ((base (event-basic-type ev))
(func
(pcase base
((or ?> ?.) 'python-indent-shift-right)
((or ?< ?,) 'python-indent-shift-left))))
(funcall func start end count)
(message "Use <,> for further adjustment")
(set-transient-map
(let ((map (make-sparse-keymap)))
(dolist (mods '(() (control)))
(dolist (key '(?> ?< ?, ?.)) ;; ,. are often unshifted <,>.
(define-key map (vector (append mods (list key)))
(lambda () (interactive)
(python-indent-adjust count)))))
map))))))
(define-key python-mode-map (kbd "C-c >") 'python-indent-adjust)
(define-key python-mode-map (kbd "C-c <") 'python-indent-adjust)
```
### Hydra
You need to install `hydra` first.
```
(require 'python) ;; alternatively use an appropriate `use-package` declaration
(defhydra python-indent (python-mode-map "C-c")
"Adjust python indentation."
(">" python-indent-shift-right "right")
("<" python-indent-shift-left "left"))
```
The hydra solution has the tiny disadvantage that if you explicitly specify the number of columns by which to indent (e.g. with a prefix argument (e.g. `C-u N` where `N` is an integer)), then that will only apply to the first indentation. Hence, if you wish to continue adjusting by, say 5 columns, you need to do something like `C-u 5 C-c > 5 > 5 >` etc. Normally, though, you'll want to adjust the indentation by the default amount, so you won't need to worry about this.
Global bindings
If you want to use the bindings both globally and within python mode, as suggested in the comments, *in addition* to the previous `defhydra` you also need:
```
(defhydra python-indent (global-map "C-c")
"Adjust python indentation."
(">" python-indent-shift-right "right")
("<" python-indent-shift-left "left"))
```
(If you wanted to use the stand-alone solution, you'd similarly need two extra `define-key`s with `global-map` (or `global-set-key`s).)
Regarding globabl use: I don't think it's a bad idea, as such but it's possible that the indent functions used for `python-mode` might not necessarily play well with all other possible language modes, though I can't currently think of any specific incompatibilities.
> 1 votes
---
Tags: key-bindings, python, indentation
---
|
thread-61589
|
https://emacs.stackexchange.com/questions/61589
|
Right way of accessing MELPA repository
|
2020-11-05T18:50:55.960
|
# Question
Title: Right way of accessing MELPA repository
I am working on Debian 10 with Emacs installed from official Debian repositories (ver 1:26.1+1-3.2) and using the following code I cannot connect to synchronize packages available on MELPA: Here's my init file:
```
(require 'package)
(setq package-archives
'(
("org" . "http://orgmode.org/elpa/")
("gnu" . "http://elpa.gnu.org/packages/")
("melpa" . "http://melpa.org/packages/")
))
(package-initialize)
(unless package-archive-contents
(package-refresh-contents))
(setq my-package-list '(use-package))
(dolist (package my-package-list)
(unless (package-installed-p package)
(package-install package)))
```
Whatever I do, I keep obtaining:
```
"Package 'use-package-' is unavailable"
```
I checked ~/.emacs.d/elpa/archives and I have no melpa directory in it, only gnu and org.
On the other hand I can fetch melpa's repositories via:
```
curl https://melpa.org/packages/archive-contents
```
I can also use melpa with the use of straight.el, for example via this code:
```
(defvar bootstrap-version)
(let ((bootstrap-file
(expand-file-name "straight/repos/straight.el/bootstrap.el" user-emacs-directory))
(bootstrap-version 5))
(unless (file-exists-p bootstrap-file)
(with-current-buffer
(url-retrieve-synchronously
"https://raw.githubusercontent.com/raxod502/straight.el/develop/install.el"
'silent 'inhibit-cookies)
(goto-char (point-max))
(eval-print-last-sexp)))
(load bootstrap-file nil 'nomessage))
(straight-use-package 'use-package)
```
But as far as I can see straight.el fetches MELPA repository on its own.
What is wrong with the original code? What can I do to track the problem?
# Answer
> 0 votes
OK. It's not really an answer to my question. It's only a workaround that I found here as a workaround to a similar problem (maybe even the same?) and it works for me. So I just replaced
```
("melpa" . "http://melpa.org/packages/")
```
with
```
("melpa" . "https://raw.githubusercontent.com/d12frosted/elpa-mirror/master/melpa/")
```
and now init file is processed and use-package is installed.
But still, anyone who knows the solution to the problem is wanted... alive...
---
Tags: package-repositories
---
|
thread-58306
|
https://emacs.stackexchange.com/questions/58306
|
Scale images to fit the frame width by default?
|
2020-05-06T00:36:36.853
|
# Question
Title: Scale images to fit the frame width by default?
When displaying images in Image mode the default seems to be to scale the image to fit completely within the frame. (Or within the document area of the frame to be more precise.) I find this inconvenient for images which are much taller than they are wide.
`M-x describe-mode` shows the command `increase-image-size` is bound, but many keystrokes may be required to scale the image appropriately. Within image-mode.el I found the command `image-transform-fit-to-width` which has the effect I want, but it is not bound. It is defined as follows:
```
(defun image-transform-fit-to-width ()
"Fit the current image to the width of the current window.
This command has no effect unless Emacs is compiled with
ImageMagick support."
(interactive)
(setq image-transform-resize 'fit-width)
(image-toggle-display-image))
```
I could bind this in my init.el of course, and may still do, but I think I'd like to find a way to have the images scaled in this way by default. Can it be done?
# Answer
> 2 votes
There is a variable `image-auto-resize` which you can customize to fit-width:
```
image-auto-resize is a variable defined in ‘image-mode.el’.
Its value is ‘fit-width’
Original value was t
You can customize this variable.
This variable was introduced, or its default value was changed, in
version 27.1 of Emacs.
Probably introduced at or before Emacs version 27.1.
Documentation:
Non-nil to resize the image upon first display.
Its value should be one of the following:
- nil, meaning no resizing.
- t, meaning to fit the image to the window height and width.
- ‘fit-height’, meaning to fit the image to the window height.
- ‘fit-width’, meaning to fit the image to the window width.
- A number, which is a scale factor (the default size is 1).
```
---
Tags: images, image-mode, scaling
---
|
thread-61493
|
https://emacs.stackexchange.com/questions/61493
|
Confused regarding .dir-locals.el and projectile
|
2020-10-31T07:36:06.073
|
# Question
Title: Confused regarding .dir-locals.el and projectile
I have a `python` project, it has tests and I can execute them from the command line. I just read about `.dir-locals.el` in the `projectile` documentation and I want to execute tests from inside emacs using `projectile`.
So I create a `.dir-locals.el` file like:
```
((nil .
(
(projectile-project-test-cmd . "pytest --color=no")
)))
```
The variable is set, but when do `C-c p P` (or `M-x projectile-test-project`) It asks for the command with `Test command:` (If I type there `pytest --color=no`, it will execute perfectly)
The documentation says that it is possible to avoid the question setting the variable `compilation-read-command` to no nil.
```
((nil .
((compilation-read-command . nil)
(projectile-project-test-cmd . "pytest --color=no")
)))
```
But if I do that, `C-c p P` stops asking, but it doesn't execute the tests, it executes a `Compilation` (!)
This is the result:
```
-*- mode: compilation; default-directory: "~/tmp/tsp/" -*-
Compilation started at Sat Oct 31 02:05:42
Compilation finished at Sat Oct 31 02:05:42
```
Would you mind to point me what I am doing wrong?
# Answer
> 2 votes
According to the docstring of projectile-test-command, this function first check `projectile-test-cmd-map` for the last command. It is likely you inadvertently invoked an empty `""` command in that emacs session, and that empty command was stored inside the hash-table. The problem will probably disappear when you restart emacs or invoke `(clrhash projectile-test-cmd-map)` to clear the hash-table.
It's worth mentioning though, according to the doc, `compilation-read-command` maybe risky if used as a file-local variable. So I'm not sure if it's a good idea to put this in your `.dir-locals.el`. Perhaps it's better to set it globally (or set inside emacs customization interface).
---
Tags: python, projectile
---
|
thread-61601
|
https://emacs.stackexchange.com/questions/61601
|
org-mode-hook is always evaluated
|
2020-11-06T16:34:08.653
|
# Question
Title: org-mode-hook is always evaluated
I'd like to use a particular theme. To this end, I've put the following in my `init.el`:
```
;; Setup org-mode theme
(defun org_setup()
"Setup org-mode"
(load-theme 'doom-laserwave)
)
;; Startup hook for org-mode
(add-hook 'org-mode-hook
(org_setup))
```
Curiously, *whatever* file I open (e.g., even `init.el`) this theme is used. Why is that? My (limited) understanding is that this code should only be run if `org-mode` is initiated. Am I doing something daft?
# Answer
> 4 votes
Assuming that the O.P. meant to use an underscore in the function name of `org_setup` (which is possible, but not the standard naming convention), then the problem is with the call to `add-hook` itself. Instead of using `(org_setup)`, it should be `'org_setup`. Try changing the call to `add-hook` as follows:
```
(add-hook 'org-mode-hook 'org_setup)
```
---
Tags: org-mode, init-file, hooks, themes
---
|
thread-61603
|
https://emacs.stackexchange.com/questions/61603
|
Adding extra "\source{something}" command inside table and figure latex environments exported from org-mode
|
2020-11-06T18:13:45.673
|
# Question
Title: Adding extra "\source{something}" command inside table and figure latex environments exported from org-mode
I'm writing a large document in org that I export to PDF through latex. The latex class that I'm using (set in `org-latex-classes`) defines a `\source` command that can be used inside table and figure environments to indicate the source of that material. Something like the code below in latex
```
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{figure.pdf}
\caption{\label{thelabel}The caption.}}
\source{Modified from~\cite{bibkey}.}
\end{figure}
```
In org-mode we can include the figure as (without the `\source command`)
```
#+NAME: thelabel
#+ATTR_LATEX: :width \textwidth
#+CAPTION: \caption{The caption.}
[[figure.pdf]]
```
My question is: How can I tell org-mode to add `\source{whatever}` inside the exported figure environment? Is there something I can pass to `#+ATTR_LATEX: ???` to add what I need inside the environment?
Note: Unfortunately the `\source` command cannot be put inside the caption.
---
Edit: After more research I found this question on stackoverflow which is the same question as this one. Essentially, it comes down to either NickD's answer, or creating a filter, but with the filter solution there does not allow specifying what comes inside the `\source` command and this using `:caption` seems like the only way to go.
# Answer
Try the `:caption` attribute in `#+ATTR_LATEX:` instead:
```
#+NAME: thelabel
#+ATTR_LATEX: :width \textwidth :caption \caption{The caption.}\source{the Source}
[[figure.pdf]]
```
The LaTeX file I get reads in part:
```
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{/path/to/figure.jpg}
\caption{The caption.}\source{The Source}
\end{figure}
```
which should work as expected.
> 2 votes
---
Tags: org-mode, org-export, latex
---
|
thread-61418
|
https://emacs.stackexchange.com/questions/61418
|
Call Python from YaSnippet and insert result
|
2020-10-25T16:31:24.930
|
# Question
Title: Call Python from YaSnippet and insert result
I'm trying to build a comparable functionality as described here: https://castel.dev/post/lecture-notes-1/#sympy-and-mathematica
Basically, he's using something comparable to yasnippet to send a dedicated region to yasnippet and sends it to python, printing it's return value.
I don't even know how to call python and just return it to the buffer in the first place, neither how to let yasnippet do it. Thanks in advance!
# Answer
> 1 votes
There are a few options I found, none of which completely address this issue.
## 1. Evaluating Python directly in the buffer
Python can be evaluated in the buffer with the function "eval-region-as-py" from Emacs SE - How to evaluate the selection through Python and replace the selection with it's result?. This returns the result in the buffer.
For example, let's evaluate this:
```
print("hello world!")
```
Running eval-region-as-py on this produces the following output.
```
hello world!
None
```
Then you can call this function in a yasnippet template to run it. Something like
```
`(eval-region-as-py yas-selected-text)`
```
should work.
You can suppress the "None" with another function. It's pretty involved, so I won't get into that here. (Maybe you can start researching it with SO - Redirecting the output of a python function from STDOUT to variable in Python .) I'm not sure how running sympy would work. When I tried it in my Emacs session, Sympy hangs while looking for definitions for each variable (e.g., `sin(x)` hangs because I didn't run `x = syms('x')` first.) using this implementation: Emacs SE - How to evaluate the selection through Python and replace the selection with it's result?. Normally, you would need to run `syms()` to define all the variables, but we don't know which variables we're using before trying to evaluate the expression.
---
## 2. Using org-mode instead of LaTeX (not really a way to resolve this problem)
Another option you could try is using org-mode (although this doesn't really answer your original question).
In org-mode, you can call something like
```
#+begin_src python :results output
import sympy as sp
x = sp.symbols('x')
print(sp.expand_trig(sp.sin(2*x) + sp.cos(2*x)))
#+end_src
```
which will result in the following.
```
#+RESULTS:
: 2*sin(x)*cos(x) + 2*cos(x)**2 - 1
```
---
# 3. Emacs Calc Embedded Mode
You type a command directly in your buffer. Suppose you typed in
```
solve(x^2 + 2*x - 1 = 0, x)
```
and evaluate it using `C-x * e`. This particular expression evaluates to
```
x = 0.414213562373
```
I got this idea from Emacs SE - Quickly Evaluate Infix Math Expression?
---
## 4. emaxima
You can try using emaxima (TeX SE - emaxima on beamer). Again, it won't give you the ability to run SymPy, but it will let you symbolically manipulate expressions and dump the results of that computation directly in the buffer.
---
## 5. Sage
You can use `sage-shell-mode` to evaluate things in the buffer. It doesn't dump the results directly in the buffer, though; you would need to write a wrapper function to do that. It also may run more slowly than the other options, depending on the Python implementation you're using.
---
Tags: python, yasnippet
---
|
thread-61612
|
https://emacs.stackexchange.com/questions/61612
|
"if" clause within s-format string
|
2020-11-07T10:53:14.660
|
# Question
Title: "if" clause within s-format string
Is it possible to add an "if" clause to a `s-format` string? The code below is adapted from `bibtex-completion-apa-format-reference` in the `helm-bibtex` package.
```
(s-format
"${author} (${date}). ${title}. In ${editor} (Eds.), ${booktitle} (pp. ${pages}). ${address}: ${publisher}."
'bibtex-completion-apa-get-value entry)
```
I would like to add the biblatex field `${origdate}` like so if it exists.
```
(s-format
"${author} (${date}[${origdate}]). ${title}. In ${editor} (Eds.), ${booktitle} (pp. ${pages}). ${address}: ${publisher}."
'bibtex-completion-apa-get-value entry)
```
The above code produces this when `origdate` is empty:
> author (2020\[\]). Title. In ...
I would like `s-format` to use `(${date})` when `origdate` is empty and `(${date}[${origdate}])` when `origdate` is present.
I can certainly nest the two sets of `s-format` code above under an `if` function to produce the desired results:
```
(if (origdate-is-empty)
(s-format
"${author} (${date}). ${title}. In ${editor} (Eds.), ${booktitle} (pp. ${pages}). ${address}: ${publisher}."
'bibtex-completion-apa-get-value entry)
(s-format
"${author} (${date}[${origdate}]). ${title}. In ${editor} (Eds.), ${booktitle} (pp. ${pages}). ${address}: ${publisher}."
'bibtex-completion-apa-get-value entry))
```
Just like to know whether there is a more concise way of doing this.
# Answer
Instead of a constant string you can use an expression that returns your template. Assuming `origdate-is-empty` is a valid function that returns `nil` if `origdate` is not empty you can use something like this
```
(s-format
(concat "${author} (${date}"
(unless (origdate-is-empty) "[${origdate}]")
"). ${title}. In ${editor} (Eds.), ${booktitle} (pp. ${pages}). ${address}: ${publisher}.")
'bibtex-completion-apa-get-value entry)
```
> 2 votes
---
Tags: string, helm-bibtex
---
|
thread-61617
|
https://emacs.stackexchange.com/questions/61617
|
Are commands not equivalent to functions in Emacs?
|
2020-11-07T14:28:07.297
|
# Question
Title: Are commands not equivalent to functions in Emacs?
The documentation for `M-x` says:
```
M-x runs the command execute-extended-command (found in global-map),
which is an interactive compiled Lisp function in ‘simple.el’.
It is bound to <execute>, <menu>, M-x.
(execute-extended-command PREFIXARG &optional COMMAND-NAME TYPED)
This function is for interactive use only;
in Lisp code use ‘command-execute’ instead.
Read a command name, then read the arguments and call the command.
To pass a prefix argument to the command you are
invoking, give a prefix argument to ‘execute-extended-command’.
```
I'm still a beginner at Elisp so I'm not sure I understand all of this, but it is saying that this should run an `interactive compiled Lisp function` somewhere.
I recently was looking for a way to find the current frame height & width. I stumbled across this website after searching about it in my favourite search engine: https://www.gnu.org/software/emacs/manual/html\_node/elisp/Frame-Size.html
Now, this is saying that, for example
> Function: frame-height &optional frame
>
> Function: frame-width &optional frame
>
> These functions return the height and width of the text area of frame, measured in units of the default font height and width of frame (see Frame Font). These functions are plain shorthands for writing (frame-parameter frame 'height) and (frame-parameter frame 'width).
>
> If the text area of frame measured in pixels is not a multiple of its default font size, the values returned by these functions are rounded down to the number of characters of the default font that fully fit into the text area.
that `frame-height` and `frame-width` are functions in Emacs. This seems like the legitimate gnu.org website so it should have the latest information. Not sure why this isn't working when I do `M-x frame-height` in Emacs; `frame-height` has `[No Match]` apparently.
Could anyone help me out in understanding this documentation?
# Answer
> 4 votes
A command is an interactively callable function (or keyboard macro). Therefore not every function is a command, but every command is a function (or keyboard macro).
The reason for this difference is that for executing a command, Emacs needs to obtain extra information from the user what arguments to pass to it. The most common way of specifying that is the `interactive` form, it allows declaring how each argument is obtained (for example by prompting the user for it, using the prefix argument or a hardcoded value).
To experiment with functions that don't happen to be commands, evaluate Emacs Lisp code directly, for example by typing it into the scratch buffer and using one of the many evaluation commands (like `C-M-x` to evaluate the form at point, `C-x C-e` to evaluate the s-expression behind point or `M-x eval-buffer` for the whole buffer).
# Answer
> 4 votes
`M-x` is a key binding, which runs the command `execute-extended-command`.
A command is an interactive function. To turn a function to command, put `(interactive SPEC)` at the beginning of the function. A command can be invoked by user interactivity via its name with `M-x` or its key binding, for example, `C-n` and `M-x` `next-line` do the same thing.
Some interactive functions have lots of features that only make sense when user calls directly, thus not suitable for called by other Lisp code.
Most functions are not commands, you turn a function into a command, only when you're sure the user need to run it.
---
Tags: commands
---
|
thread-59725
|
https://emacs.stackexchange.com/questions/59725
|
In a Python code is it possible to give a color to called functions?
|
2020-07-19T16:43:55.800
|
# Question
Title: In a Python code is it possible to give a color to called functions?
As a theme I am using Dracula.
For example I have this example code piece coloring:
When cursor is on `terminate()` and I typed `M-x customize-face` it is linked to `(default ‘all faces’)`. I am not sure which variable's color should I change.
---
This is example coloring in the `SublimeText` where functions such as: `terminate`, `is_internet_on`, `error`, `session_start_msg` has a different color rather than white. I was wondering is it possible to achive this in `emacs` as well?
# Answer
I know one interesting solution, emacs-tree-sitter which is the Emacs implementation of the general parser tree-sitter used in Atom.
It's quite easy to use and work out of the box, this is how it look the function with the modus-vivendi theme:
As tree-sitter inherit from the font-lock default variables (define by the Dracula theme) for Emacs basic, stuff like the function name (in this case tools), is enough to call customize-face and then font-lock-function-name-face. BUT if you want to change more specific face colour (method,function call) those are define by tree-sitter, there is two main ways to achieve this, with the built in Emacs font customization, or setting the variables manually The first way:
* Get the function at point (where the cursor is) with face-at-point - Call customize-face with the face name (keep in mind that it may scape some characters like the dot), and change the colours clicking in Show all attributes.
* Same as the first one - Use the function face-spec-set for every face you want to change, in this case, the method call face: `(face-spec-set 'tree-sitter-hl-face:method\.call '((t (:inherit tree-sitter-hl-face:function\.call :foreground "red"))))`
In this case, I put the face in red color.
For more information, emacs-tree-sitter documentation
> 2 votes
---
Tags: colors, coloring
---
|
thread-61621
|
https://emacs.stackexchange.com/questions/61621
|
How can I get the search string from incremental regexp search to use with replace regexp
|
2020-11-07T20:54:20.120
|
# Question
Title: How can I get the search string from incremental regexp search to use with replace regexp
If I want to do a `replace-regexp` I usually start with a `isearch-forward-regexp` so I can get immediate visual feedback on the search string.
From there I'd like to grab the search string for using in the `replace-regexp`. Right now all I can see to do is use my OS to copy and paste it. Is there a way to do this built in? I had hoped those commands shared history but it didn't in my experiments.
Or is my whole approach wrong?
(Using spacemacs if that adds anything useful.)
# Answer
Is this for interactive use? I suppose so. As the doc string for `replace-regexp` says:
```
This function is for interactive use only; in Lisp code
use `re-search-forward' and `replace-match' instead.
```
Are you really asking about `replace-regexp`, and not `query-replace-regexp`?
Because if you use the latter then the answer is included in Isearch by default: Just use `C-M-%` when you're regexp-isearching, and you immediately switch to `query-replace-regexp`, using the search regexp as the regexp to search for with `query-replace-regexp`. And of course with `query-replace-regexp` you can always hit `!`, to replace all subsequent matches.
But if you really want to use `replace-regexp` explicitly then you can use Isearch+ to get the regexp you use with `C-M-s`, to use it as the regexp to use with `replace-regexp`. For that, you just use `M-w` while isearching, to copy the current search pattern to the kill ring. And then use `M-x replace-regexp` and use `C-y`, to yank that regexp as the one to use for that command.
If you want this behavior and you don't want to load library Isearch+ then you can just use the code for it:
```
(defun isearchp-kill-ring-save () ; Bound to `M-w' in `isearch-mode-map'.
"Copy the current search string to the kill ring."
(interactive)
(kill-new isearch-string)
(let ((message-log-max nil)) (message "Copied search string as kill"))
(sit-for 1)
(isearch-update))
(define-key isearch-mode-map "\M-w" 'isearchp-kill-ring-save)
```
> 2 votes
---
Tags: regular-expressions, search, replace, isearch, query-replace-regexp
---
|
thread-61625
|
https://emacs.stackexchange.com/questions/61625
|
How do I use a function from subr.el?
|
2020-11-08T06:38:48.263
|
# Question
Title: How do I use a function from subr.el?
I found a function in lisp/subr.el that I would like to use: `version>=`. How do I use it?
`(require 'subr)` does not work: `Required feature ‘subr’ was not provided`.
# Answer
> 2 votes
`subr.el` is one of the numerous libraries which is pre-loaded. You do not need to load it; you can simply go ahead and use the functions.
Note that there is no `version>=` -- the function you have referenced is `version<=`
---
Tags: require
---
|
thread-61630
|
https://emacs.stackexchange.com/questions/61630
|
emacs org mode do not expand heading when pasted
|
2020-11-08T15:07:30.493
|
# Question
Title: emacs org mode do not expand heading when pasted
I often cut and paste folded top-level headings (only the heading is displayed, not its subcontent and tree).
When I do a paste, the heading is pasted unfolded - ie all subcontent and the tree is shown. After the paste, the current cursor point is at the bottom of the subcontent.
If I have eg 200 lines of subcontent, then I have to scroll back up to the heading to fold it.
Is there a setting in org mode to paste a heading and subcontent but not expand/unfold the subcontent?
Thanks ahead of time for any help......
# Answer
Using Emacs functionality, you could either: 1) call `yank` with an argument, `C-u C-y`, that will leave point at the beginning of the yanked text; 2) call `yank` and then pop the mark, `C-y C-u C-SPC`, that would bring point back to the beginning of the yanked text after yanking.
Using Org functionality, you could use its specialized commands for the purpose: `org-cut-special` (bound by default to `C-c C-x C-w`) and `org-paste-special` (bound by default to `C-c C-x C-y`). This should carry around the folded state of your subtrees. Note that `org-paste-special` may promote/demote the yanked subtree, according to context. If that's not wanted, regular `org-yank` (`C-y`) should also deliver it folded, if it was killed as a subtree (that is, with `C-c C-x C-w`) to start with.
> 1 votes
---
Tags: org-mode
---
|
thread-61638
|
https://emacs.stackexchange.com/questions/61638
|
Preview all LaTeX fragments in org mode?
|
2020-11-08T21:19:46.800
|
# Question
Title: Preview all LaTeX fragments in org mode?
How can I call `org-toggle-latex-fragment` on all LaTeX fragments in an Org mode doc? I'm coming from Vim, so my instinct is to put something in the `init.el` that loops through the document and looks for `$` and `\[` to call `org-toggle-latex-fragment` on if the file extension is `.org`. How can I implement this, and is this generally a good approach?
# Answer
`org-toggle-latex-fragment` is obsolete since Org 9.3. Use `org-latex-preview`.
To preview all latex fragments in the buffer pass `C-u` twice before calling `org-latex-preview`. Note that a single `C-u` before `org-latex-preview` actually removes all previews. For instance, I set the keybinding `C-f5` to `org-latex-preview` then `C-u C-f5` removes all previews and `C-u C-u C-f5` preview latex fragments on the whole buffer.
Note: `org-toggle-latex-fragment` has the same behavior, in case you are using an org-mode version before 9.3.
---
You might be also interested in org-fragtog.
> Automatically toggle org-mode latex fragment previews as the cursor enters and exits them
> 5 votes
---
Tags: org-mode, latex, preview-latex
---
|
thread-61637
|
https://emacs.stackexchange.com/questions/61637
|
How to run Python code and obtain its result in the minibuffer
|
2020-11-08T21:11:39.503
|
# Question
Title: How to run Python code and obtain its result in the minibuffer
I am using the following answer for How do you run Python code using Emacs.
I was wondering instead of opening python shell using `C-c C-z` and running `C-c C-c` to get results;
=\> Can only the output results show up on the mini-buffer?
Opened Python shell buffer takes half of the window. I just want to see the output results in the minibuffer, or most compact buffer windows as possible.
# Answer
One idea would be to use `call-process` or `shell-command-to-string`. Here is an example:
```
(defun python-fn (code)
(let* ((temporary-file-directory ".")
(tmpfile (make-temp-file "py-" nil ".py")))
(with-temp-file tmpfile
(insert code))
(car (split-string (shell-command-to-string (format "python %s" tmpfile)) "\n$"))))
(python-fn "a = 150
b = 125
if b > a:
print(\"b is greater than a\")
elif a == b:
print(\"a and b are equal\")
else:
print(\"a is greater than b\")")
```
> 1 votes
---
Tags: python
---
|
thread-7982
|
https://emacs.stackexchange.com/questions/7982
|
Getting `:distant-foreground` face attribute to work
|
2015-02-04T20:22:33.780
|
# Question
Title: Getting `:distant-foreground` face attribute to work
Emacs's faces let you set `:distant-foreground`, which according to the docs, "is like `:foreground` but the color is only used as a foreground when the background color is near to the foreground that would have been used."
I'm not really sure how "near" is computed, but it doesn't seem to be good enough. I would like to use it with my `region` face, so that the text is in the same face it's normally in, except when it's unreadable. My `region` is currently set to `:background "lightgoldenrod2"`. Selecting some white text with this makes it unreadable. When I set `:distant-foreground "black"`, it doesn't change.
How is "near" calculated here? How can I adjust this calculation to be a more reasonable contrast calculation?
# Answer
> 1 votes
In Emacs 27.1, there is a new variable `face-near-same-color-threshold`, which can be adjusted to control when `distant-foreground` is chosen over `foreground`:
```
Threshold for using distant-foreground color instead of foreground.
The value should be an integer number providing the minimum distance
between two colors that will still qualify them to be used as foreground
and background. If the value of ‘color-distance’, invoked with a nil
METRIC argument, for the foreground and background colors of a face is
less than this threshold, the distant-foreground color, if defined,
will be used for the face instead of the foreground color.
Lisp programs that change the value of this variable should also
clear the face cache, see ‘clear-face-cache’.
```
It defaults to 30,000. I am currently experimenting with a value of 160,000. I arrived at this value when I noticed that comments in the active region were unreadable, so I rounded up from this result of `color-distance`:
```
ELISP> (color-distance (face-foreground 'font-lock-comment-face) (face-background 'region))
150984 (#o446710, #x24dc8)
```
This very question was even cited in the discussion that resulted in adding this variable: https://debbugs.gnu.org/cgi/bugreport.cgi?bug=34001
# Answer
> 4 votes
I found part of the answer by reading the source code. In `xfaces.c`, there is (in `load_face_colors`)
```
dfg = attrs[LFACE_DISTANT_FOREGROUND_INDEX];
if (!NILP (dfg) && !UNSPECIFIEDP (dfg)
&& color_distance (&xbg, &xfg) < NEAR_SAME_COLOR_THRESHOLD)
{
if (EQ (attrs[LFACE_INVERSE_INDEX], Qt))
face->background = load_color (f, face, dfg, LFACE_BACKGROUND_INDEX);
else
face->foreground = load_color (f, face, dfg, LFACE_FOREGROUND_INDEX);
}
```
where
```
/* Returns the `distance' between the colors X and Y. */
static int
color_distance (XColor *x, XColor *y)
{
/* This formula is from a paper titled `Colour metric' by Thiadmer Riemersma.
Quoting from that paper:
This formula has results that are very close to L*u*v* (with the
modified lightness curve) and, more importantly, it is a more even
algorithm: it does not have a range of colors where it suddenly
gives far from optimal results.
See <http://www.compuphase.com/cmetric.htm> for more info. */
long r = (x->red - y->red) >> 8;
long g = (x->green - y->green) >> 8;
long b = (x->blue - y->blue) >> 8;
long r_mean = (x->red + y->red) >> 9;
return
(((512 + r_mean) * r * r) >> 8)
+ 4 * g * g
+ (((767 - r_mean) * b * b) >> 8);
}
```
and
```
#define NEAR_SAME_COLOR_THRESHOLD 30000
```
Since this is in C, I think this means that this is not really customizable (maybe by rewriting the C function in lisp).
Doing some research, it would be nice to get an algorithm that uses http://web.mst.edu/~rhall/web\_design/color\_readability.html (the "Algorithm" section), which gives a formula and a good recommended contrast ratio from W3C.
# Answer
> 1 votes
It works for me, but yes, you need to pick a color that is "nearer" than that for it to take effect. From `emacs -Q`.
I set face `default` to have a `white` foreground and a background of `#000000004`. And I set face `region` to have a distant foreground of `black` and a background of `#ffffffff3`.
Selecting white text shows the region with black text (foreground). Selecting another color of text (e.g. green foreground) shows the region with that same color (green) as foreground.
Try closer colors to see if it at least works in your Emacs version. I'm on MS Windows and using a dev version of Emacs 25 from last October (2014).
And while you're at it, you might consider filing an Emacs bug (`M-x report-emacs-bug`) for (at least) insufficient doc. If there isn't already (and I couldn't find any in the doc or in `NEWS`), there should perhaps be a **user option**, to let you control how close "*near*" needs to be for `:distant-foreground` to kick in.
---
Tags: faces
---
|
thread-61642
|
https://emacs.stackexchange.com/questions/61642
|
(org-do-promote) on keyboards without arrow keys
|
2020-11-09T00:49:37.793
|
# Question
Title: (org-do-promote) on keyboards without arrow keys
I'm using a keyboard without arrow keys because well... its Emacs!
However, I realized that (org-do-promote) is bound to M-left.
I find it hard to accept this 'tragic' situation ;D
Do I really have to custom global-set-key this?
Ideas on keybindings are also very welcome
Thanks in advance
# Answer
> 1 votes
Org does provide some extra bindings "for TTY access". They are on by default only if `window-system` is nil, but otherwise disabled. However, you can enable them manually by setting `org-use-extra-keys` to non-nil *before loading Org*.
With `org-use-extra-keys`, you can use `C-c C-x l`/`C-c C-x r`, which are also bound to `org-metaleft`/`org-metaright` in `org-mode-map`.
---
Tags: org-mode
---
|
thread-61631
|
https://emacs.stackexchange.com/questions/61631
|
Tangled 0 code blocks from ahk file
|
2020-11-08T15:14:53.510
|
# Question
Title: Tangled 0 code blocks from ahk file
I am planning to (re)organize my ahk code as code blocks into an org file and tangle this file to obtain the source file.
This is my `ahk-guivho.org` input file, with two code blocks, empty for the sake of this post:
```
#+TITLE: AHK config file
+AUTHOR: Guido Van Hoecke
+EMAIL: (concat "guivho" at-sign "gmail.com")
#+PROPERTY: header-args :tangle ahk-guivho.ahk
#+PROPERTY: header-args+ :padline yes
#+PROPERTY: header-args+ :eval never
#+PROPERTY: header-args+ :eval no
#+PROPERTY: header-args+ :exports code
* HideWindow - hides the active window
#+BEGIN_SRC ahk
HideWindow(title="", x=0, y=0) { ;hides the active window
}
#+END_SRC
* ActivateWindow
#+BEGIN_SRC ahk
ActivateWindow(title="") {
}
#+END_SRC
```
I expect `org-babel-tangle` to produce a file called `ahk-guivho.ahk` with two empty subs (HideWindow and ActivateWindow) but it does not.
It simply complains: `Tangled 0 code blocks from ahk-guivho.org`
I am pretty sure that my org and babel setup is ok: I tangle my `.emacs` from an org file without any problems.
I do realize that ahk is not among the officially supported languages.
But when I edit a code block from the org file, I get a buffer with `ahk-mode` as expected.
Do I need to initialize something somewhere to be able to tangle ahk code from an org file?
# Answer
> 4 votes
I'm pretty sure the problem here is that you did not refresh the buffer before tangling. You can do that by pressing `C-c C-c` on one of the keyword lines (a line starting with `#+`), because then Org mode activates changes to in-buffer settings; alternatively, you can save the file and revert the buffer from the file; or save the file, kill the buffer and reopen the file - see In buffer settings in the manual.
Here's an explanation of @gregoryg's findings in the comment: when you first add a `#+PROPERTY` line in the file (or you cut and paste the OP's Org mode file into a new local file), the `#+PROPERTY:` settings are *NOT* active: you need to activate them as pointed out above. So if you try to tangle before activating, you get the `Tangled 0 code blocks` message. If you then activate them, it all works as it should.
If OTOH you add the `:tangle foo` header to the code blocks instead, you don't need to activate anything: the babel code parses the code blocks in their entirety and it tangles the two code blocks successfully.
I hope that clarifies the situation.
---
Tags: org-mode, tangle
---
|
thread-61641
|
https://emacs.stackexchange.com/questions/61641
|
Penguin character in file
|
2020-11-08T23:30:29.407
|
# Question
Title: Penguin character in file
I use Spacemacs. I tried to type a command, but I mistyped. Instead of what I intended, a character was inserted that renders as this:
I suppose that is Tux. When I try to copy the character, I get this: .
1. How did this happen?
2. Is this behaviour documented anywhere?
I use the official `.spacemacs`, with little additions. This happened in `org-mode`, if that matters.
# Answer
Since we do not know what you typed (neither what you tried), it is hard to know what happened.
You can insert it by typing `C-x 8 RET e000`. (Note that this hexadecimal value is displayed within the tofu rendering for this character.)
About the character, only the font you use is relevant. Some fonts show different symbols.
This character \[`57344 (#o160000, #xe000)`\] is the first from Private Use Area (PUA) plane 0 (U+E000-U+F8FF). Thus, it is not defined, it is not a Tux/Penguin char by definition, if you want a penguin char there is `128039 (#o372047, #x1f427)` (`C-x 8 RET 1f427` or `C-x 8 RET penguin`).
> 1 votes
---
Tags: spacemacs, unicode
---
|
thread-61633
|
https://emacs.stackexchange.com/questions/61633
|
Can company-mode show the doc of the functions?
|
2020-11-08T16:52:37.203
|
# Question
Title: Can company-mode show the doc of the functions?
I am using `company-mode` for backends to auto-complete in Python and `emacs` is used as command line.
```
(add-hook 'after-init-hook 'global-company-mode)
(setq company-auto-complete t)
(setq company-auto-complete t)
(global-set-key (kbd "C-c C-k") 'company-complete)
```
During autocompletion, it shows the name of the fuctions and their type. In addition to those, I was wondering can it show the `doc` of the each function like `jedi` does (example first image on the jedi site)?
---
`company` (information of functions are missing on the right hand-side):
`jedi`:
# Answer
> 1 votes
By default company-mode doesn't seems to have that feature, BUT there is a package called company-box that take care of the documentation among other things:
* **Without** company-box:
* **With** company-box:
(To trigger the doc, you may have to wait like a second)
---
Tags: jedi, company
---
|
thread-55520
|
https://emacs.stackexchange.com/questions/55520
|
hand draw arrow in pdf-tools
|
2020-02-13T23:14:17.450
|
# Question
Title: hand draw arrow in pdf-tools
I like using pdf-tools to annotate a pdf file. **Is there a way of hand-drawing an arrow (by dragging the mouse) in pdf-tools?** It would help a lot in annotating pdf files. Even a template arrow (instead of hand drawn) would be good. As a possible solution I noticed that forward search from latex to pdf-tools does put a temporary arrow in the pdf file. Maybe a similar mechanism can be used to add an annotation arrow?
# Answer
There is pymupdf-mode now. It is hacky but does a nice job and is very customizable with only very basic elisp and some custom python pymupdf commands from the excellent pymupdf documentation.
> 0 votes
---
Tags: pdf-tools
---
|
thread-61652
|
https://emacs.stackexchange.com/questions/61652
|
How can I get an outline in org-beamer export without changing the other frames?
|
2020-11-09T12:34:12.763
|
# Question
Title: How can I get an outline in org-beamer export without changing the other frames?
I have this org-beamer example:
```
#+TITLE: Example
#+LANGUAGE: en
#+SELECT_TAGS: export
#+EXCLUDE_TAGS: noexport
#+CREATOR: Emacs 26.3 (Org mode 9.1.9)
#+STARTUP: beamer
#+BEAMER_FRAME_LEVEL: 2
#+COLUMNS: %40ITEM %10BEAMER_env(Env) %9BEAMER_envargs(Env Args) %4BEAMER_col(Col) %10BEAMER_extra(Extra)
#+OPTIONS: num:t toc:t \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t
#+OPTIONS: TeX:t LaTeX:t skip:nil d:nil todo:t pri:nil tags:not-in-toc
* Section
** Frame
Pellentesque condimentum, magna ut suscipit hendrerit, ipsum augue ornare nulla, non luctus diam neque sit amet urna.
* Other Section
** Other Frame
Nullam rutrum.
* Third Section
** Third Frame
Pellentesque tristique imperdiet tortor.
```
It does what - almost. The "normal" pages look like this:
But: the Outline is empty. I found that I can add an outline for the 2nd level org items with the option `#+OPTIONS: H:2`. With that option, I get an outline, but now the pages look like this:
Is there a way to get both?
# Answer
Based on Joe Corneli's answer here, you can create an outline manually as a list of your frames.
Create a file named `list-of-frames.tex` and edit your org file as follows:
`list-of-frames.tex:`
```
\makeatletter
\newcommand\listofframes{\@starttoc{lbf}}
\makeatother
\addtobeamertemplate{frametitle}{}{%
\addcontentsline{lbf}{section}{\protect\makebox[2em][l]{%
\protect\usebeamercolor[fg]{structure}\insertframenumber\hfill}%
\insertframetitle\par}%
}
```
`your-file.org:`
```
#+TITLE: Example
#+LANGUAGE: en
#+SELECT_TAGS: export
#+EXCLUDE_TAGS: noexport
#+CREATOR: Emacs 26.3 (Org mode 9.1.9)
#+STARTUP: beamer
#+BEAMER_FRAME_LEVEL: 2
#+COLUMNS: %40ITEM %10BEAMER_env(Env) %9BEAMER_envargs(Env Args) %4BEAMER_col(Col) %10BEAMER_extra(Extra)
#+OPTIONS: num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t
#+OPTIONS: TeX:t LaTeX:t skip:nil d:nil todo:t pri:nil tags:not-in-toc
#+LaTeX_HEADER: \input{list-of-frames.tex}
* Outline
:PROPERTIES:
:BEAMER_env: ignoreheading
:END:
\addtocounter{framenumber}{-1}
\begin{minipage}[c][\textheight][c]{\linewidth}
\listofframes
\end{minipage}
* Section
** Frame
Pellentesque condimentum, magna ut suscipit hendrerit, ipsum augue ornare nulla, non luctus diam neque sit amet urna.
* Other Section
** Other Frame
Nullam rutrum.
* Third Section
** Third Frame
Pellentesque tristique imperdiet tortor.
```
> 1 votes
---
Tags: org-export
---
|
thread-7238
|
https://emacs.stackexchange.com/questions/7238
|
Info file emacs does not exist
|
2015-01-10T11:10:52.707
|
# Question
Title: Info file emacs does not exist
When I type `C-h r` I get error:
> Debugger entered--Lisp error: (error "Info file emacs does not exist") signal(error ("Info file emacs does not exist")) error("Info file %s does not exist" "emacs") Info-find-file("emacs")
> Info-find-node("emacs" "Top") Info-goto-node("(emacs)")
> info-setup("emacs" #) info("emacs")
> info-emacs-manual() call-interactively(info-emacs-manual nil nil)
I am using Emacs 24.3 on Ubuntu 14.04. (I have installed package `emacs24-common-non-dfsg`.. )
# Answer
> 3 votes
You have to set the correct path to the Emacs info files in the `INFOPATH` environment variable:
```
export INFOPATH=$INFOPATH:/usr/share/info/emacs-24
```
# Answer
> 16 votes
That error is because the full documentation is not installed by default.
Solve it by installing `emacs25-common-non-dfsg`
```
# aptitude install emacs25-common-non-dfsg
```
Test it by trying,
```
C-h i h
```
It should now work.
# Answer
> 1 votes
I found it easier to build Emacs from source: you get not only full Emacs documentation but also a more recent version, presently 27.1 instead of 26.3 (in Ubuntu 20.10).
Configure is straightforward because all the dependencies can be obtianed with: `sudo apt-get build-dep emacs`.
Add to $INFOPATH: `/usr/local/share/info /usr/share/info/emacs /usr/share/info`.
# Answer
> 0 votes
Just setting INFOPATH didn't solve it for me.
I'm running Debian 9.4 derived Bunsen Helium. Somehow, I didn't get info, or the Emacs info files installed. So:
Set INFOPATH in .bashrc:
```
export INFOPATH=/usr/share/info
export INFOPATH=$INFOPATH:/usr/share/info/emacs
```
Then installed info:
```
$ sudo apt-get install info
```
Then downloaded these gnu info files and installed them in directory /usr/share/info/emacs
(did it as root)
https://www.gnu.org/software/emacs/manual/info/emacs.info.gz
https://www.gnu.org/software/emacs/manual/info/elisp.info.gz
Finally, upgraded my emacs version (got me up to Emacs 25.2.2):
```
$ sudo apt-get install emacs
```
Not sure if all this was the 'right' way to do it, but I'm tired of fooling with it...
---
Tags: documentation, help
---
|
thread-61659
|
https://emacs.stackexchange.com/questions/61659
|
Can `eshell-command` direct its output like `shell-command` into minibuffer?
|
2020-11-09T21:39:53.047
|
# Question
Title: Can `eshell-command` direct its output like `shell-command` into minibuffer?
=\> When I do `M-x shell-command` and `python run.py` (which only print `Hello World\nHello World` string), I get the result on the minibuffer and when cursor moves up/down minibuffer is closed.
=\> When I do `M-x eshell-command` and `pwd` I get the result on another window instead of the mini-buffer I had to do C-x-1 to close it. Please note that, if the output is single line it is printed in the minibuffer.
=\> Can `eshell-command` direct its output like `shell-command` into minibuffer if the output is more than a single line?
# Answer
> 2 votes
It can't without modifying the code, but you can do it yourself
```
(defun your-eshell-command (command)
"Execute eshell COMMAND and display output in the echo area."
(interactive "sEshell command: ")
(message "%s" (eshell-command-result command)))
```
`shell-command`'s output behavior is smarter
> If the output is short enough to display in the echo area (which is determined by the variables `resize-mini-windows` and `max-mini-window-height`), it is shown there
---
Tags: eshell
---
|
thread-61663
|
https://emacs.stackexchange.com/questions/61663
|
How to turn off python-mypy in spacemacs flycheck-mode?
|
2020-11-09T23:19:39.690
|
# Question
Title: How to turn off python-mypy in spacemacs flycheck-mode?
I'm using the latest Spacemacs with the Python layer. I'd like to turn off `python-mypy` in `flycheck-mode`, but the following in my `~/.spacemacs` doesn't work:
```
(defun dotspacemacs/user-config ()
(add-to-list 'flycheck-disabled-checkers 'python-mypy)
)
```
How do I turn it off?
# Answer
> 1 votes
From the doc:
```
flycheck-disabled-checkers is a variable defined in ‘flycheck.el’.
Its value is nil
Automatically becomes buffer-local when set.
This variable is safe as a file local variable if its value
satisfies the predicate ‘flycheck-symbol-list-p’.
You can customize this variable.
```
This variable is a buffer-local variable.
When you call `add-to-list` on it, it was set as locally. Check out the example call from **ielm** below.
One possible option is to customize it using the `customize` interface to let it set globally for you.
---
Edit:
1. In fact you can set it in `.dir-locals.el`. This will set the variable for a lot of files ("directory local" variable is still file local, I might add). E.g. I tried setting the following (see below), and checkers are all disabled for every python file in the entire projectile dir.
```
;;; Directory Local Variables
;;; For more information see (info "(emacs) Directory Variables")
((python-mode . ((flycheck-disabled-checkers . (python-mypy python-flake8 python-pylint)))))
```
2. How to customize & set it globally once and for all
* Do `C-h v` (or `SPC h d v`, spacemacs only) and select `flycheck-disabled-checkers`.
* Click `customize` in the sentence "You can customize this variable.".
* In the interface, click `INS` to insert a value
* Enter `python-mypy` as you wish
* Click `State` and choose what you want
* You can try out in the current session only
* You can persist the customization for future use also
* OR you can revert if you mess up
---
Tags: spacemacs, python
---
|
thread-40979
|
https://emacs.stackexchange.com/questions/40979
|
Enter hex numbers continuously in hexl-mode
|
2018-04-11T17:07:16.690
|
# Question
Title: Enter hex numbers continuously in hexl-mode
In `hexl-mode` how can I make Emacs enter a state where it takes everything I enter as hex input until I tell it to stop? Eg. I want to tap "A", "B", "1", "0", etc., and have this entered as $AB, $10, etc. in the binary file, be able to cursor around, enter more hex values, and so forth, until I'm satisfied.
By default I have to press `C-M-x` for every hex value I want to enter, which is very counterproductive at least for the type of binary file I'm working with at the moment.
# Answer
`hexl-insert-hex-string` can enter a hex string in a `hexl-mode` buffer, but the string length cannot be greater than the file size.
> 2 votes
# Answer
You could try something like (guaranteed 100% untested):
```
(defvar hexl-hex-insert-mode-map
(let ((map (make-sparse-keymap)))
(mapc (lambda (c)
(define-key map (vector c) 'hexl-hex-self-insert))
"0123456789abcdef")
map))
(defvar hexl-hex--last-char nil)
(defun hexl-hex-self-insert ()
(interactive)
"Self-insert \"nibble\"."
(if (not (and hexl-hex--last-char
(eq this-command last-command)))
(setq hexl-hex--last-char last-command-event)
(hexl-insert-multibyte-char
(hexl-hex-string-to-integer
(string hexl-hex--last-char last-command-event))
1)
(setq hexl-hex--last-char nil)))
(define-minor-mode hexl-hex-insert-mode
"Hex insertion mode."
:lighter " HI")
```
> 1 votes
---
Tags: hexl-mode
---
|
thread-61660
|
https://emacs.stackexchange.com/questions/61660
|
How to print colorful and bold string in the mini-buffer
|
2020-11-09T22:54:41.860
|
# Question
Title: How to print colorful and bold string in the mini-buffer
When I do `echo "\033[1;31mThis is bold red text\033[0m"` it should print `This is bold red text` as red and bold. When I try it in the emacs's shell it prints it as it is instead showing the ansi-color.
example:
`M-x shell-command` and `echo "\033[1;31mThis is bold red text\033[0m"` enter.
=\> How could I fix this?
my setup:
```
(require 'ansi-color)
(defun colorize-compilation-buffer ()
(toggle-read-only)
(ansi-color-apply-on-region (point-min) (point-max))
(toggle-read-only))
(add-hook 'compilation-filter-hook 'colorize-compilation-buffer)
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on) ;;
```
---
Please note that: output is printed in the minibuffer, I am not sure can color could be shown in the minibuffer.
# Answer
Unlike the `M-x shell`, the `M-x shell-command` does not provide color.
You can write your own, e.g.,
```
M-x your-shell-command echo "\033[1;31mThis is bold red text\033[0m"
```
```
(require 'ansi-color) ; for `ansi-color-apply-on-region'
(require 'subr-x) ; for `string-trim-right'
(defun your-ansi-color-apply (s)
"Like `ansi-color-apply' but use `face' instead of `font-lock-face'."
(with-temp-buffer
(insert s)
(let ((ansi-color-apply-face-function
(lambda (beg end face)
(when face
(put-text-property beg end 'face face)))))
(ansi-color-apply-on-region (point-min) (point-max)))
(buffer-string)))
(defun your-shell-command (command)
"A simplified `shell-command' to support color."
(interactive (list (read-shell-command "Shell command: ")))
(message "%s"
(string-trim-right
(your-ansi-color-apply
(shell-command-to-string command)))))
```
`your-ansi-color-apply` is required because the echo area does not support Font Lock mode thus `font-lock-face` won't work.
> 2 votes
---
Tags: shell
---
|
thread-60814
|
https://emacs.stackexchange.com/questions/60814
|
How to end text-insert undo segment after cursor jump (caused by mouse)?
|
2020-09-23T15:56:33.107
|
# Question
Title: How to end text-insert undo segment after cursor jump (caused by mouse)?
Coming from vim into (evil-mode) spacemacs, I sometimes get frustrated that undo segment is not ended when a mouse-caused cursor movement occurs. An example : While I am inserting text, touchpad gets often touched, causing the cursor to jump elsewhere. If I have entered five sentences just where I wanted them, without any jump, but sixth sentence gets by mistake entered all over the place because of multiple (three) touchpad touches in different places, when I notice this, I need to be able to execute (three times) "undo" so that the fives sentences stay intact, and the undo operation erase only the sixth sentence from all over the place.
Right now when insert gets this way screwed up, the undo tree contains only one segment. When I press undo, all six sentences disappear. I have to choose all-or-nothing, neither of which is very useful!!
Appending after "blabla" by entering insert mode and typing "This is first sentence. " /now mouse click occurs by mistake/ "This is second sentence." I get: `blabla This is This is second sentence. first sentence.` Pressing U for undo I need to get : `blabla This is first sentence.` , but I am instead getting: `blabla`
Interestingly enough, when text is being replaced and not inserted, everything works as expected - undo segment ends when mouse moves the cursor, so replacing by mistake I can in sequence undo the previous changes made after mouse-caused jump.
How can I fix this? Is it a bug, or some funny feature?
PS: Please do not advise me to get "disable touch pad while typing" working.
# Answer
On 2020-10-18 00:34, Stefan Monnier wrote:
> > How to end text-insert undo segment after cursor jump (caused by mouse)?
>
> Note that the behavior you describe comes from code in Evil. The way undo steps are divided in non-Evil Emacs is different (mostly, finer grained).
>
> More specifically, I believe that if you perform the `undo` *before* you finish your insertion (i.e. before hitting ESC), you should get (more or less) the behavior you want, i.e. the cursor jump due to your mouse event will indeed have ended an undo sequence. Evil then collapses those undo steps into a single one when you leave insertion mode.
>
> In any case, maybe setting `evil-want-fine-undo` will also do the trick.
The issue was caused by evil layer. The solution suggested by Stefan, to set `evil-want-fine-undo` worked.
I went to Emacs customization interface for this option, set it to non-nil, and saved. Then I was able to undo up until the problematic point, and the undo action no longer grouped everything between start and end of insert command, but recognized piece-wise undo segments.
> 0 votes
---
Tags: insert, undo
---
|
thread-61668
|
https://emacs.stackexchange.com/questions/61668
|
setf + alist-get but with "equal" instead of "eq"?
|
2020-11-10T12:01:56.263
|
# Question
Title: setf + alist-get but with "equal" instead of "eq"?
I got a suggestion to use `setf` to replace value in an alist: Replace element in a list / add in case of absence, with custom test/key functions
The example was provided, but it doesn't work if key is a string:
```
(let ((al (list (cons "a" 1) (cons "b" 2))))
(setf (alist-get "c" al) 3)
(setf (alist-get "c" al) 4)
al)
;; evaluates to: (("c" . 4) ("c" . 3) ("a" . 1) ("b" . 2))
```
The keys of `tramp-methods` are strings. Is it possible to alter equality predicate of `setf` in a a declarative way (without tons of elisp)?
# Answer
> Is it possible to alter equality predicate of `setf` in a a declarative way (without tons of elisp)?
See the docstring of `alist-get`:
```
alist-get is a compiled Lisp function in ‘subr.el’.
(alist-get KEY ALIST &optional DEFAULT REMOVE TESTFN)
Probably introduced at or before Emacs version 25.1.
Find the first element of ALIST whose ‘car’ equals KEY and return its ‘cdr’.
If KEY is not found in ALIST, return DEFAULT.
Equality with KEY is tested by TESTFN, defaulting to ‘eq’.
You can use ‘alist-get’ in PLACE expressions. This will modify
an existing association (more precisely, the first one if
multiple exist), or add a new element to the beginning of ALIST,
destructively modifying the list stored in ALIST.
Example:
(setq foo '((a . 0)))
(setf (alist-get 'a foo) 1
(alist-get 'b foo) 2)
foo => ((b . 2) (a . 1))
When using it to set a value, optional argument REMOVE non-nil
means to remove KEY from ALIST if the new value is ‘eql’ to
DEFAULT (more precisely the first found association will be
deleted from the alist).
Example:
(setq foo '((a . 1) (b . 2)))
(setf (alist-get 'b foo nil 'remove) nil)
foo => ((a . 1))
```
The key point to note is the `TESTFN` argument, which defaults to `eq` but can also be set to `equal`:
```
(let (alist)
(setf (alist-get "a" alist nil nil #'equal) 1)
(setf (alist-get "a" alist nil nil #'equal) 2)
alist) ; => (("a" . 2))
```
> 3 votes
# Answer
After reading of `emacs/27.1/lisp/emacs-lisp/gv.el`:
```
(gv-define-expander alist-get
(lambda (do key alist &optional default remove testfn)
```
I came up with:
```
(let ((al (list (cons "a" 1) (cons "b" 2))))
(setf (alist-get "c" al nil t #'equal) 3)
(setf (alist-get "c" al nil t #'equal) 4)
al)
;; produces: (("c" . 4) ("a" . 1) ("b" . 2))
```
It correlates with a `alist-get` signature:
```
(alist-get KEY ALIST &optional DEFAULT REMOVE TESTFN)
```
> 2 votes
---
Tags: equality, setf, alists
---
|
thread-28819
|
https://emacs.stackexchange.com/questions/28819
|
eshell goes to the bottom of the page after executing a command
|
2016-11-22T00:29:03.000
|
# Question
Title: eshell goes to the bottom of the page after executing a command
when I execute a command on eshell the prompt switches to the bottom of the window. I have to `C-l` a few times to get it back on top. Once again after I execute anything it goes back to the bottom of the window. It is infuriating. How do I make sure the eshell prompt stays on 'top' of the window at all times with the previous commands being hidden above the window. I don't know if 'window' is correct terminology. Please correct me if not.
# Answer
> 3 votes
You can disable the Eshell's scroll feature using:
```
(add-hook 'eshell-mode-hook
(defun chunyang-eshell-mode-setup ()
(remove-hook 'eshell-output-filter-functions
'eshell-postoutput-scroll-to-bottom)))
```
Notes, `(eval-after-load "eshell" (remove-hook ...))` doesn't work correctly according to my experiment, it simply sets `eshell-output-filter-functions` to nil, I don't know the cause. You can also use the Custom interface with:
```
M-x customize-option RET eshell-output-filter-functions RET
```
this way works too and is much easier, since this option is available until Eshell has been invoked, if you can't find this option, type `M-x eshell` then try again.
# Answer
> 3 votes
You might check whether `eshell-scroll-to-bottom-on-output` is set to `nil`. Here's the documentation:
> Documentation: Controls whether interpreter output causes window to scroll. If nil, then do not scroll. If t or ‘all’, scroll all windows showing buffer. If ‘this’, scroll only the selected window. If ‘others’, scroll only those that are not the selected window.
# Answer
> 0 votes
You need to set `eshell-scroll-show-maximum-output` to `nil`.
Sadly the documentation doesn't really explain the difference to `eshell-scroll-to-bottom-on-output`, but its default value is `nil` anyway and therefore isn't responsible for the described behaviour. In contrast the default of `eshell-scroll-show-maximum-output` is `t`.
My understanding is that enabling `eshell-scroll-to-bottom-on-output` causes eshell to scroll to the bottom if you have scrolled upwards the buffer and you have a program running which produces some output. It will just scroll in a way though, that the last line will be visible in the buffer, and will not align the last line to the bottom of the window.
An enabled `eshell-scroll-show-maximum-output` on the other hand ignores output produced by a third party program when you scroll upwards, but will align the current prompt with the bottom of the window (hence "maximising" the last output) when you issue any kind of input with triggers a new prompt.
---
Tags: eshell
---
|
thread-61677
|
https://emacs.stackexchange.com/questions/61677
|
make `display-buffer` open buffer in new tab
|
2020-11-11T01:50:08.157
|
# Question
Title: make `display-buffer` open buffer in new tab
The `display-buffer` function seems to be used quite heavily within Emacs. It has a lot of options to determine where to open a new buffer (a new window, a new frame, an existing window, etc).
Emacs introduced a concept of tabs in 27.1. However, there doesn't appear to be an easy way to tell `display-buffer` that you want new buffers to open in a tab, instead of just a new window.
Is there some way to configure `display-buffer` to open all buffers in a new (or existing?) tab?
---
The solution from NickD suggests using a function like `display-buffer-in-tab`.
I was able to get this working by setting `display-buffer-base-action` like the following:
```
(setq display-buffer-base-action '(display-buffer-in-tab))
```
However, this doesn't seem to play nicely with functions like `help` and `magit-status`. They tend to open up too many tabs every time they are run.
More specific settings may be necessary per command or per new buffer.
# Answer
> 3 votes
There is `display-buffer-in-new-tab`. Its doc string says:
```
display-buffer-in-new-tab is a compiled Lisp function in ‘tab-bar.el’.
(display-buffer-in-new-tab BUFFER ALIST)
Display BUFFER in a new tab.
ALIST is an association list of action symbols and values. See
Info node ‘(elisp) Buffer Display Action Alists’ for details of
such alists.
Like ‘display-buffer-in-tab’, but always creates a new tab unconditionally,
without checking if a suitable tab already exists.
If ALIST contains a ‘tab-name’ entry, it creates a new tab with that name
and displays BUFFER in a new tab. The ‘tab-name’ entry can be a function,
then it is called with two arguments: BUFFER and ALIST, and should return
the tab name. When a ‘tab-name’ entry is omitted, create a new tab without
an explicit name.
This is an action function for buffer display, see Info
node ‘(elisp) Buffer Display Action Functions’. It should be
called only by ‘display-buffer’ or a function directly or
indirectly called by the latter.
```
Untested.
EDIT: I found this by using the Emacs help system. I don't use `tab-bar-mode` and I didn't know about this beforehand, but doing `C-h f display-buffer-TAB` shows me a completion buffer. Quickly scanning that, I found `display-buffer-in-tab` and `display-buffer-in-new-tab`. I chose the latter and got the doc string that I pasted above.
If the completion buffer is too long to scan easily by eye, you can switch to the buffer with `C-x o` and then just search e.g. for `tab` in the buffer using `C-s`.
Learning to use `Help` and also learning to search through the manuals with `Info` is an excellent investment of your time.
---
Tags: tabbar, display-buffer
---
|
thread-2490
|
https://emacs.stackexchange.com/questions/2490
|
package-install reports "no match"
|
2014-10-23T13:27:45.540
|
# Question
Title: package-install reports "no match"
From the Emacs Eclim github page:
> Install emacs-eclim. You have two options:
>
> * Installation from the MELPA package archive.
>
> Just add the archive to package-archives if you haven't already, and
>
> then install emacs-eclim with the package-install command.
> * Manual installation from GitHub.
>
> (git clone git://github.com/senny/emacs-eclim.git)
>
> Add (add-to-list 'load-path "/path/to/emacs-eclim/") to your startup script.
If followed the first option and:
1. Added the following package-archives to my `~/.emacs.d/init.el` file:
```
(setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
("marmalade" . "http://marmalade-repo.org/packages/")
("melpa" . "http://melpa.milkbox.net/packages/")))
```
2. Then typed `M-x``package-install` and hit `RET` and the following message poped up:
`Install package: emacs-eclim [No Match]`
---
Why does this error pop up?
Thanks in advance.
# Answer
Maybe refreshing package contents could help: try evaluating `(package-refresh-contents)` or typing `M-x``package-refresh-contents`.
> 24 votes
# Answer
Just wanted to add my experience. I installed Emacs on my Mac via Homebrew and couldn't get it to find or list any packages from repositories other than the standard GNU ELPA, despite adding MELPA and MELPA Stable to my `package-archives` in my init.el (similar to above), and despite doing `package-refresh-contents`, restarting Emacs, rebooting my machine, etc.
I noticed status messages about using TLS as it was loading `list-packages` (although they all appeared to be successful), and checked my Homebrew Emacs install -- I hadn't installed with the `with-gnutls` option. I uninstalled Emacs and reinstalled, this time using `with-gnutls`, and this fixed the problem for me. So, for me, something like:
```
brew install emacs --with-cocoa --with-gnutls
```
> 5 votes
# Answer
To my experience, this failed to detect (and autocomplete) the package I wanted, given a correct setup if you have already installed the package. A way to check that your configuration is properly set up and working is to `package-list-packages` and manually search for the package you want to install.
> 1 votes
---
Tags: package
---
|
thread-29242
|
https://emacs.stackexchange.com/questions/29242
|
How to do backend-dependent actions in org-mode export?
|
2016-12-12T07:22:10.470
|
# Question
Title: How to do backend-dependent actions in org-mode export?
How do I specify different actions for different export backends in org-mode?
To be more specific, I would like to export an pdf figure in latex export, while using a png in html export (in fact, a png thumbnail linking to the pdf, if that is of relevance):
```
#+CAPTION: cation of figure
#+NAME: myfig
# case export to latex: [[file:./figure.pdf]]
# case export to html: [[file:./figure.pdf][file:./figure.png]]
```
I tried macros and this answer, which did not work. There are also answers on similar cases for tikz pdf/svg/png export like this thread, which do not seem to be transferable to my case.
**Note:** I initially posted this question on stackoverflow. It occured to me later that emacs stackexchange is a more appropriate site for this question. So I deleted it on stackoverflow (there were no answers) to repost it here.
# Answer
> 4 votes
I finally found a way to do this, using a macro provided by fniessen:
```
#+MACRO: if-latex-else (eval (if (org-export-derived-backend-p org-export-current-backend 'latex) "$1" "$2"))
```
If more/other export-backends than LaTeX and HTML are used, a condition statement can be used instead:
```
#+MACRO: if-latex-html-else (eval (cond ((org-export-derived-backend-p org-export-current-backend 'latex) "$1") ((org-export-derived-backend-p org-export-current-backend 'html) "$2") (t "$3") ))
```
Usage would be something like
```
{{{if-latex-html-else([[file:./figure.pdf]], [[file:./figure.pdf][file:./figure.png]], /Figure *figure.pdf* is supposed to be here/)}}}
```
Not as short as a simple switch, but substantially better than providing native LaTeX/HTML/whatever code for every figure that is to be included.
# Answer
> 1 votes
Using macros as the accepted answer is a great option, which I also used following this question. But there is one alternative that I started using and that some may prefer: define a `src` block with emacs-lisp and a call it with `#+CALL` for each figure we want to include.
It works like this, add the block below to your org-mode document (it can be inside a heading with the `:noexport:` tag) and change it according with your preferences.
```
#+NAME: get-filename-by-backend
#+begin_src emacs-lisp :var filename="default" :exports none :results raw
(concat "[[file:"
(case org-export-current-backend
(html (concat filename ".svg"))
(twbs (concat filename ".svg"))
(latex (concat filename ".pdf"))
(t (concat filename ".png")))
"]]")
#+end_src
```
Now, whenever you want to include a figure just add something like
```
#+NAME: a_name_for_this_figure_call
#+CALL: get-filename-by-backend(filename="figs/my_nice_figure")
```
and execute the block with `C-c C-c`. This will add the result as
```
#+RESULTS: a_name_for_this_figure_call
[[file:figs/my_nice_figure.png]]
```
Now you can add `#+NAME: figure_label`, `#+CAPTION: The figure caption.`, `#+ATTR_LATEX: ...`, etc above the `#+RESULTS:` line.
The *trick* here is that we get a `png` image when we are not exporting, which can be **nicely displayed** with `org-toggle-inline-images`. However, during the export **the `#+CALL:` line is re-evaluated** and we get a `pdf` image for latex export and an `svg` image for HTML export.
The advantage of this solution, compared with a macro solution, goes beyond just displaying the image inline. Since you can pass a variable to a `src` block that receives the result of another `src` block it means that you can have a `src` block using your preferred language that generates "backend dependent" export code.
---
Tags: org-mode, org-export
---
|
thread-50905
|
https://emacs.stackexchange.com/questions/50905
|
wrong cwd in python mode
|
2019-06-08T12:10:51.150
|
# Question
Title: wrong cwd in python mode
When i do `C-c C-c` on a python module, it leads to `*Python*` buffer with Inferior Python : run Shell-Compile mode. Suppose the correct cwd is `/x/y/z/`
The problem is when I print `os.getcwd()`, i get wrong cwd = `/x/y/`
Due to this, modules from the same directory can not be imported.
But when i run `M-x run-python` from the same module, `os.getcwd()` is fine and modules can be imported.
Anyone knows what is happening here ?
# Answer
> 2 votes
If the `elpy-shell-starting-directory` variable is set to `project-root` then you will see the behaviour described. That is, the default directory for the Python shell is `/x/y`, the root of `/x/y/z`. Thus while editing code in a project `z`, it makes sense to run the code from `y`.
To get what you want, set `current-directory` as the value of `elpy-shell-starting-directory`.
So "`M-x customize-variable elpy-shell-starting-directory`", change to `current-directory`, and then apply and save for future sessions.
This will add the following to `~/.emacs-custom`
```
'(elpy-shell-starting-directory (quote current-directory))
```
---
Tags: python
---
|
thread-61656
|
https://emacs.stackexchange.com/questions/61656
|
realgud pdb with .dir-locals.el
|
2020-11-09T17:22:56.130
|
# Question
Title: realgud pdb with .dir-locals.el
I'm trying to use directory local variables so my `realgud:pdb` invocation can be:
```
Run pdb (like this): /home/username/work/place/environments/default/bin/python -m pdb /home/username/work/place/scratch.py
```
Instead of :
```
Run pdb (like this): python -m pdb /home/username/work/place/scratch.py
```
as suggested here.
However, in order to transform the suggestion there to be compatible with `.dir-locals.el`, I understand I need to use nil and eval per this answer.
So I am left with this:
```
;; .dir-locals.el
;; set the test runner
((nil . ((eval . (add-hook 'python-mode-hook
(function (lambda ()
(let* ((conda-python (format "%/envs/default/bin/python -m pdb" (projectile-project-root))))
(setq-local realgud:pdb-command-name conda-python))
)))
))
))
```
This doesn't complain or fail, except for asking me whether I trust the eval parameters. However, it doesn't seem to work, as my `M-x realgud:pdb` invocation is still:
```
Run pdb (like this): python -m pdb /home/username/work/place/scratch.py
```
My `init.el` contains:
```
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(column-number-mode t)
'(conda-anaconda-home (expand-file-name "~/anaconda3"))
'(elpy-test-pytest-runner-command '("py.test"))
'(elpy-test-runner 'elpy-test-pytest-runner)
```
...which I don't think interferes but include for completeness.
What should I change so that my `.dir-local.el` picks up the correct test runner for pdb? Essentially, I am trying to combine the suggestion of the linked answer to modify my `init.el`, but in a per directory basis, using `.dir-locals.el`, as my projects have different environment names and I'm stuck having one per project.
# Answer
I tried instead of setting a hook, just eval the variable with the `python-mode` association and seems to work fine, here is the code:
```
((python-mode . ((eval .
(setq-local realgud:pdb-command-name (concat
(projectile-project-root)
"envs/default/bin/python -m pdb"))))))
```
> 1 votes
---
Tags: directory-local-variables, realgud
---
|
thread-61696
|
https://emacs.stackexchange.com/questions/61696
|
Emacs font-highlighting does not work on my own files?
|
2020-11-12T10:16:31.267
|
# Question
Title: Emacs font-highlighting does not work on my own files?
I have an issue that probably has been asked and answered before but I am unable to find it because I seem to be using the wrong search terms for it.
However, the issue I have is that if I make my own file, which I have my bash-aliases in e.i `~/.bash_aliases` I get no syntax highlighting as I am getting in my `.bashrc`? When I am making a new systemd service I however get syntax/font highlighting?
# Answer
The syntax highlighting of a file is determined by what mode or modes are active. The most common way to choose what mode to activate is based on the file name extension. `python-mode` will be activated for `.py` files, `c-mode` for `.c` files, `html-mode` for `.html` files, and so on. `sh-mode` is the mode that provides syntax highlighting for shell scripts, and it is primarily activated for files with the `.sh` extension.
However, file name extensions are not universally used. In fact, the notion that all file names should have an extension seems to come primarily from DOS and CP/M machines, where every file had a metadata field that was presented after the file name, separated from it by a period. Macintosh computers had a separate metadata field for the type that wasn't part of the name (and if I recall correctly wasn't even directly editable by the user). Unixes had no type field in the file metadata, so extensions were used in some contexts but not others. File names like `.bashrc`, `.bash_profile` and others of that style have no extension; the leading period was just a trick to hide the file from directory listings. As such, Emacs can also choose a mode for the file based on its contents, rather than on its name.
For shell scripts in particular, Emacs looks for the shebang at the top of the file to choose the mode. Your `.bash_aliases` file is probably sourced by your other scripts, so it doesn't really need a shebang to work. But you could add one so that Emacs recognizes it as a shell script.
You can also put information for Emacs in the first line of the file, and this is most commonly used to tell Emacs what mode to use. Emacs expects this information to have `-*-` characters surrounding it, so for your shell script you could do this:
```
# -*- Shell -*-
```
The `#` makes sure that this line is treated as a comment by your shell.
All of this (and more) is documented in the Emacs manual in chapter 23.3 Choosing modes.
> 2 votes
---
Tags: syntax-highlighting
---
|
thread-61700
|
https://emacs.stackexchange.com/questions/61700
|
Run an external shell command to mutate text
|
2020-11-12T12:39:06.907
|
# Question
Title: Run an external shell command to mutate text
I would like to run par or fmt to format my `.md` file. In vim this would be `%!fmt` (for the whole buffer) or `13,16!fmt` (for line 13 - line 16). What's the "emacs way" to achieve something like this
**PS:** I am aware of `evil-mode`(If I wanted vi keystrokes, I would have used vim) and the `M-!` key binding. I also am quite new to emacs
# Answer
> 5 votes
1. Create a region (for example via `C-SPC` or `M-h`, see "Mark" in Emacs' manual: `C-h r m Mark RET`)
2. Use `shell-command-on-region` with a prefix argument: `C-u M-|`
You can find more information in the Emacs documentation via `C-h F shell-command-on-region RET`.
---
Tags: shell, mutability
---
|
thread-61699
|
https://emacs.stackexchange.com/questions/61699
|
How to create an annotated tag with an empty message in Magit?
|
2020-11-12T11:49:00.583
|
# Question
Title: How to create an annotated tag with an empty message in Magit?
## Objective
Create an annotated tag with an empty message, as would be created with the following command.
```
$ git tag --annotate epic-tag --message=""
```
## Attempts
1. Create it with `M-x magit-tag<RET> -a t tag-name<RET> <RET> C-c C-c`. This does not work, because git interprets no message specified interactively as don't create tag, resulting in the following in the magit-process buffer.
```
...
git … tag --annotate tag-name master
hint: Waiting for your editor to close the file...
Waiting for Emacs...
fatal: no tag message?
```
2. Add argument `--message=` to `magit-tag`. I added a `--message=` argument to `magit-tag`(see branch or patch), but when I try using my argument with an empty value it interprets it as cancelling the argument. Using '' or "" as a value literally uses '' or "" for the tag message.
3. Add a "virtual argument" `-e` that adds `--message=''` to the command. That also used '' as a literal tag message. See branch or patch.
## Anti-solutions
* Use lightweight tags. The tags must be annotated because they are meant for release\*.
* Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels. - GIT-TAG(1)
# Answer
## Solution
I updated my transient argument to accept empty values and now it works. commit patch
## Update
Instead of customising Magit itself, one can add the argument to your personal configuration. Add the following code to your configuration to add an argument `-m`, to `magit-tag`, that accepts a optionally-empty message string.
```
(transient-define-argument magit-tag:--message ()
:description "Use message"
:class 'transient-option
:shortarg "-m"
:argument "--message="
;; Empty (annotated)tag messages must be permitted because it is
;; impossible to create them interactively.
:allow-empty t)
(transient-append-suffix
'magit-tag
"-u"
'(magit-tag:--message)))
```
> 2 votes
---
Tags: magit
---
|
thread-8147
|
https://emacs.stackexchange.com/questions/8147
|
Using desktop-mode with Emacs Daemon
|
2015-02-11T08:08:23.103
|
# Question
Title: Using desktop-mode with Emacs Daemon
I am using emacs 24.3 (ubuntu 14.10) and would like the daemon to participate in the graphical desktop session lifecycle while using `desktop-mode`. I went through http://www.emacswiki.org/emacs/EmacsAsDaemon but it still does not play nice for me. One problem is that the daemon SIGTERM termination does not clean up `.emacs.desktop.lock` so the next start will refuse to pick up the saved state.
Does anyone have a recipe to make emacs daemon + desktop mode play nice with the graphical desktop session?
As a sidenote: Sending SIGHUP frequently crashes emacs for me.
# Answer
> 6 votes
Don't kill the process.
Use `M-x` `kill-emacs` `RET` to terminate the server.
# Answer
> 1 votes
This is how I solved it for me: (you need to disable elsewhere desktop-save-mode)
```
(require 'desktop)
;; (setq desktop-restore-forces-onscreen nil)
(if (not (daemonp))
(desktop-save-mode 1)
(defun restore-desktop (frame)
"Restores desktop and cancels hook after first frame opens.
So the daemon can run at startup and it'll still work"
(with-selected-frame frame
(desktop-save-mode 1)
(desktop-read)
(remove-hook 'after-make-frame-functions 'restore-desktop)))
(add-hook 'after-make-frame-functions 'restore-desktop))
```
Uncomment first line if you get the `Error (frameset): Wrong type argument: number-or-marker-p, nil`.
Btw, use `(global-set-key (kbd "C-x C-M-c") 'save-buffers-kill-emacs)` to leave emacsclient safely.
---
Tags: daemon, desktop
---
|
thread-45794
|
https://emacs.stackexchange.com/questions/45794
|
Activating Latex snippets in org mode
|
2018-11-06T18:42:31.237
|
# Question
Title: Activating Latex snippets in org mode
I have downloaded the yasnippet package which works very nicely for my Latex files. However, I often use Org mode to write my Latex documents.
The latex snippets from yasnipet dont seem to be "active" in org-mode. i.e. typing `begin` and pressing `tab` does not expand into `\begin{..} \end{..}`
How can I make the Latex yasnippets active in Org mode?
# Answer
Don't know how to do it directly in the org file, but if you are writing LaTeX in export blocks then you can use `org-edit-special`. For instance, with the point in the following export block
```
#+begin_export latex
LaTeX snippets
#+end_export
```
`C-c '` runs the command `org-edit-special` and in this case a buffer is opened with the content `LaTeX snippets` and in this buffer you can use all commands and functions that you can use for your LaTeX files.
> 1 votes
# Answer
As answered here you can active snippets for other major-modes with `yas-activate-extra-mode`
> 1 votes
---
Tags: org-mode
---
|
thread-61708
|
https://emacs.stackexchange.com/questions/61708
|
clang-format package looking for wrong executable
|
2020-11-12T18:59:08.147
|
# Question
Title: clang-format package looking for wrong executable
I'm trying to setup emacs to use the `clang-format` package. I have installed the `clang-format` package from MELPA and also have `clang-format-10` (`apt install` only installs version 6 on Ubuntu) installed on my local machine. I also have the following lines in `~/.emacs`:
```
(require 'clang-format)
(setq clang-format-style "file")
(setq exec-path (append exec-path '("/usr/bin/clang-format-10")))
```
I added the last last line because `M-x clang-format-region` throws the error:
```
Searching for program: No file or directory, clang-format
```
However, the `clang-format` package appears to still be looking for a `clang-format` binary without the version suffix. Also, it's worth noting I made an alias in my `~/.bashrc` so `clang-format` points to `clang-format-10`, however that doesn't help me in emacs.
# Answer
First of all, .bashrc doesn’t help since it’s for non-login shell if I remember correctly.
Secondly, I believe a “path” in `exec-path` should end with “bin”, like it would be in environment variable `PATH`. Also, `/usr/bin` should already be there, thus no need to add.
What you should have done is adding a symlink. You can do:
* `sudo ln -sf clang-format-10 /usr/bin/clang-format` if you have sudo access, OR
* `ln -sf /usr/bin/clang-format-10 ~/bin/clang-format` and add `/home/yourusername/bin` to `exec-path`.
> 1 votes
---
Tags: package, clang
---
|
thread-61709
|
https://emacs.stackexchange.com/questions/61709
|
Searching in a subtree in orgmode without narrowing
|
2020-11-12T19:56:31.417
|
# Question
Title: Searching in a subtree in orgmode without narrowing
Is there a way to search in org mode in emacs in a certain subtree without narrowing or "narrowing" and "widening" the way to go?
# Answer
Can you easily select a tree that you want to search? I don't use Org, but I imagine there are commands to do that kind of thing: select specific subtrees etc.
If you use Isearch+ (code: `isearch+.el`) then you can limit isearch to within the active *region* \- you need not *narrow* to the region.
That lets you continue to see the surrounding context. (You can optionally dim it a bit, to concentrate on the text you're searching.)
You can also limit isearch to a *multi*-region, that is, to a *set of **zones*** (which are easy to define, either interactively or programmatically) or its *complement*. For this, you also need library Zones or library `isearch-prop.el`.
> 1 votes
---
Tags: org-mode, search, region, isearch
---
|
thread-61647
|
https://emacs.stackexchange.com/questions/61647
|
Why ivy-immediate-done is not shown in counsel-M-x
|
2020-11-09T05:23:35.410
|
# Question
Title: Why ivy-immediate-done is not shown in counsel-M-x
I realize that `ivy-immediate-done` is not shown in `counsel-M-x`. Since it's an interactive command, I'm assuming `counsel-M-x` somehow filters it from its result. But a quick search of the function name in its code directory fails to find the relevant logic. I'm wondering what I am missing here. Thx!
# Answer
Found it! Don't know why I missed the first time.
Here's why: Code
```
(defun ivy-define-key (keymap key def)
"Forward to (`define-key' KEYMAP KEY DEF).
Remove DEF from `counsel-M-x' list."
(put def 'no-counsel-M-x t)
(define-key keymap key def))
```
> 1 votes
---
Tags: commands, ivy
---
|
thread-55569
|
https://emacs.stackexchange.com/questions/55569
|
What's the difference between ‘global-set-key "\M-…’ and ‘define-key esc-map "…’?
|
2020-02-16T15:56:33.797
|
# Question
Title: What's the difference between ‘global-set-key "\M-…’ and ‘define-key esc-map "…’?
Same for `global-set-key "\C-x …` and `define-key ctl-x-map "…`.
I prefer `(global-set-key (kbd "M-KEYS") #'COMMAND)` because it's more readable, but I would like to know if the two kinds of binding -- expliciting the `Meta` key and using the `ctl-x-map` -- differ in some ways.
# Answer
The potential difference is that `esc-map` and `ctl-x-map` can be bound to keys other than `ESC` and `C-x`.
If you don't do that, then the two approaches are effectively the same.
> 2 votes
# Answer
Consider using function `kbd`, which is described here.
`(global-set-key (kbd "C-x M-v") #'command)`
> 0 votes
---
Tags: key-bindings, prefix-keys
---
|
thread-54491
|
https://emacs.stackexchange.com/questions/54491
|
magit-status open selected buffer change hunk in other window rather then in the same window
|
2019-12-22T08:41:05.930
|
# Question
Title: magit-status open selected buffer change hunk in other window rather then in the same window
I used to have this functionality using code below:
```
(setq magit-display-file-buffer-function
(lambda (buffer)
(setq current-prefix-arg t)
(magit-display-file-buffer-traditional buffer)))
```
But it doesn't work anymore when I updated to magit 20191217.23.
# Answer
As addition to @tarsius comment, there is a code example of the configuration:
```
(define-key magit-hunk-section-map (kbd "RET") 'magit-diff-visit-file-other-window)
```
Also if you want the same behavior for the file section:
```
(define-key magit-file-section-map (kbd "RET") 'magit-diff-visit-file-other-window)
```
Using 'use-package':
```
(use-package magit
:bind (:map magit-file-section-map
("RET" . magit-diff-visit-file-other-window)
:map magit-hunk-section-map
("RET" . magit-diff-visit-file-other-window))
)
```
> 5 votes
# Answer
I did not remember what I have done here and why, so I went to magit's repository and used magit to find out about its own history. Using `l - F``magit-display-file-buffer-function``RET l` I got a limited log consisting of a single commit. I looked at that commit (https://github.com/magit/magit/commit/8a214c9fb27280af6b01b6b18d04aca26d24fe2e) and behold its commit message explains what I did and why, and how you can get the behavior that you want:
```
Remove variable magit-display-file-buffer-function
The is one step in modeling the `magit-diff-visit-file' and
`magit-diff-visit-worktree-file' families of commands after
the `find-file' family.
The next step will be to implement the missing `*-other-window'
and `*-other-frame' variants.
In other words, users can no longer configure the base variant to
not reuse the selected window. Instead they can use the variant
that behaves the way they like. That may involve changing key
bindings.
One inconsistency compared to the `find-file' family is preserved:
the base aka. same-window variants continue to display in another
window if a prefix argument is used.
```
So bind `RET` to `magit-diff-visit-file-other-window`.
> 2 votes
---
Tags: magit
---
|
thread-52324
|
https://emacs.stackexchange.com/questions/52324
|
Prevent org source block face from bleeding out in fold
|
2019-08-24T18:07:51.333
|
# Question
Title: Prevent org source block face from bleeding out in fold
The problem is that when there is one line in between folded headings with source blocks the text properties of the *#end-src* line bleeds out. You can see the lines bleeding on the right in the image.
### Update Progress So Far
### step 1
To do this I have taken two steps.
The first is to unfontify the end of the last line of a subtree when hiding it if that line is the end of a source block. That's the line responsible for the bleeding. This will ensure that the font face doesn't bleed out when a block is hidden with `outline-hide-subtree`.
```
(defun dwim-unfontify-last-line-of-subtree (&rest _)
"Unfontify last line of subtree if it's a source block."
(save-excursion
(org-end-of-subtree)
(beginning-of-line)
(when (looking-at-p (rx "#+end_src"))
(font-lock-unfontify-region
(line-end-position) (1+ (line-end-position))))))
(advice-add #'outline-hide-subtree :after #'dwim-unfontify-last-line-of-subtree)
```
### step 2
The second step is the hard one. I determined that `outline-show-heading` is the fundamental function for showing headings. This function checks if the heading being shown has
```
(defun dwim-fontify-last-line-of-block (&rest _)
"Do what I mean: fontify last line of source block.
When the heading has a source block as the last item (in the subtree) do one of the
following:
If the source block is now visible, fontify the end its last line.
If it's invisible, unfontify its last line."
(let (font-lock-fn invisible-p heading-name)
(save-excursion
;; Debugging
;; (save-match-data
;; (beginning-of-line)
;; (looking-at
;; (rx bol (+ "*") "\s" (submatch (+ (not (any "\n"))))))
;; (setq heading-name (match-string-np 1)))
(org-end-of-subtree)
(beginning-of-line)
(when (looking-at-p (rx "#+end_src"))
(setq invisible-p (outline-invisible-p (line-end-position)))
(setq font-lock-fn
(if invisible-p
#'font-lock-unfontify-region
#'font-lock-fontify-region))
;; Debugging
;; (message "-%s-’s end_src is %svisible"
;; heading-name
;; (if invisible-p "in" ""))
(funcall font-lock-fn
(line-end-position)
(1+ (line-end-position)))))))
(advice-add #'outline-show-heading :after #'dwim-fontify-last-line-of-block)
```
### problem
This is extremely close to working. If you use `outline-toggle-children` to display the children of a subtree and every child is a subtree (in other words each is displayed as a folded headline), the last source block of every headline should be invisible. That's because all the headings are folded. But `(outline-invisible-p (line-end-position))` says the last child of that subtree remains visible.
The picture below shows what I mean. You can see the last child of the Top level headings is bleeding out. And the last child of the level `Completion` heading is bleeding. This is what happens when I displayed them with `outline-toggle-fold`.
\]
# Answer
> 1 votes
## First attempt. Doesn't work, disregard. See below:
I just ran into the same issue and, inspired by @Aquaactress's attempt, added a simple advice to `org-flag-region`:
```
(defun org-flag-region-hide-last (from to flag spec)
"Unfontify last char of hidden region when folding, fontify it
when showing.
This avoids the bleeding of `org-block-end-line' when block or
parent heading is folded."
(unless (= (point-max) to)
(save-excursion
(if flag
(font-lock-unfontify-region to (1+ to))
(font-lock-fontify-region to (1+ to))))))
(advice-add 'org-flag-region :after #'org-flag-region-hide-last)
```
It seems to work well!
(Edit: no it doesn't. It doesn't work well with `org-separator-lines` and it would leave the last char unfontified in some situations.)
## Second attempt. Seems to work:
The above code is still useful (after some adaptations) to deal with hiding the block itself. But, when cycling the outline, we need to hook into `org-cycle-hook`:
```
(defun org-fix-bleed-end-line-block (from to flag spec)
"Toggle fontification of last char of block end lines when cycling.
This avoids the bleeding of `org-block-end-line' when block is
folded."
(when (and (eq spec 'org-hide-block)
(/= (point-max) to))
(save-excursion
(if flag
(font-lock-unfontify-region to (1+ to))
(font-lock-flush to (1+ to))))))
(advice-add 'org-flag-region :after #'org-fix-bleed-end-line-block)
(defun org-fix-bleed-end-line-cycle (state)
"Toggle fontification of last char of block lines when cycling.
This avoids the bleeding of `org-block-end-line' when outline is
folded."
(save-excursion
(when org-fontify-whole-block-delimiter-line
(let ((case-fold-search t)
beg end)
(cond ((memq state '(overview contents all))
(setq beg (point-min)
end (point-max)))
((memq state '(children folded subtree))
(setq beg (point)
end (org-end-of-subtree t t))))
(when beg ; should always be true, but haven't tested enough
(goto-char beg)
(while (search-forward "#+end" end t)
(end-of-line)
(unless (= (point) (point-max))
(if (org-invisible-p (1- (point)))
(font-lock-unfontify-region (point) (1+ (point)))
(font-lock-flush (point) (1+ (point)))))))))))
(add-hook 'org-cycle-hook #'org-fix-bleed-end-line-cycle)
```
If this doesn't work, try to remove the check for `org-fontify-whole-block-delimiter-line`. That is org-mode's own mechanism for dealing with whole line fontification; maybe some themes define their own methods for achieving whole line fontification, I don't know.
### Last (?) issue
There is still ONE issue I couldn't resolve... When `org-startup-folded` is `t` or `contents`, the lines still bleed when the file first opens up. You can manually cycle the visibility and they'll behave again, but I could not figure out how to do that automatically at startup.
I tried creating a hook:
```
(defun org-fix-bleed-startup ()
(when (memq org-startup-folded '(t content))
(org-fix-bleed-end-line-cycle 'all)))
(add-hook 'org-mode-hook #'org-fix-bleed-startup)
;; also tried:
(remove-hook 'after-change-major-mode-hook #'org-fix-bleed-startup)
```
But for some reason it doesn't work. I guess some other functions run after org is loaded which also change the visibility of some parts of the buffer? I don't know.
Please test this and let me know if it works!
# Answer
> 0 votes
May not be the answer you were looking for, but the simplest way might be to change the `org-block-end-line` variable face to that of the default background, thus ensuring that there's nothing to leak in the first place. Also, end\_src line generally seems useless in that all the code-block arguments belong in the begin\_line, or better yet an entirely separate #+header:.
---
Tags: org-mode
---
|
thread-17673
|
https://emacs.stackexchange.com/questions/17673
|
"no org-babel-execute function for c" and "no-org-babel-execute function for c++"
|
2015-10-27T06:16:35.553
|
# Question
Title: "no org-babel-execute function for c" and "no-org-babel-execute function for c++"
my emacs version is 24.3.1.
i understand i have to put the ob-C.el (available from here) in a path where Emacs can read it.
i first copy-pasted the code from that .el file to my .emacs file and restarted emacs. then i went to a C code block (within an org file) and tried to execute it (using C-c C-c). the minibuffer said 'no org-babel-execute function for C'. the same story played out with trying to execute a C++ code block. note that R and python evaluate perfectly from within my org files. the problems seems to be only with these compiled languages.
i then tried putting this ob-C.el inside the ~/.emacs.d directory to see if that helped matters. restarted emacs and checked. it didn't work.
then i tried putting it into a directory ~/.emacs.d/lisp and added the following lines to my .emacs file
```
(add-to-list 'load-path "~/.emacs.d/lisp/")
(load "ob-C.el")
(require 'ob-C)
```
after restarting emacs, evaluating the C or C++ code blocks from within an org file still doesn't work. i keep getting the same error "no org-babel-execute function for C" or "no org-babel-execute function for C++".
**Update**
i upgraded my emacs version to 24.5, deleted all the previous elpa and melpa subdirectories in my ~/.emacs.d directory. suspecting that it had to do with the order in which i placed my
```
(custom-set-variables
'(org-babel-load-languages
(quote
((emacs-lisp . t)
(C . t)
(css . t)
(sh . t)
(awk . t)
(R . t))))
```
and
```
;; load the pathnames to custom lisp files
(add-to-list 'load-path "~/.emacs.d/lisp/")
(load "ob-C.el")
(require 'ob-C)
```
code blocks, i put the load "ob-C.el" before the org-babel-load-languages thing. i then executed the c++ code block multiple times. no luck.
then i removed everything (cleaned out the custom-set-variables block in the .emacs file) and now my .emacs file looks like
```
;; load the pathnames to custom lisp files
(add-to-list 'load-path "~/.emacs.d/lisp/")
(load "ob-C.el")
(require 'ob-C)
;; load the languages that are needed
(org-babel-do-load-languages
'org-babel-load-languages '((C . t)))
```
Its still not working.
The code that i am trying to evaluate in an orgmode buffer is :
```
#+BEGIN_SRC c
printf("Hello world");
#+END_SRC
```
My *Messages* buffer looks like this after restarting emacs and attempting to execute the above code block :
```
Loading /home/taeten/.emacs.d/lisp/ob-C.el (source)...done
Wrote /home/taeten/.emacs.d/.emacs.desktop.lock
Desktop: 1 frame, 0 buffers restored.
For information about GNU Emacs and the GNU system, type C-h C-a.
Quit [2 times]
Making completion list... [3 times]
org-babel-execute-src-block: No org-babel-execute function for c! [5
times]
Ignoring unknown mode `elisp-mode'
File local-variables error: (void-function elisp-mode)
byte-code: Beginning of buffer [6 times]
byte-code: Beginning of buffer
```
# Answer
> 34 votes
You really only need this bit in your init file:
```
(org-babel-do-load-languages
'org-babel-load-languages '((C . t)))
```
Note it's a capital `C`. This enables Babel to process C, C++ and D source blocks.
# Answer
> 2 votes
It should be a capital 'C' not a lower case 'c' for the name of the source code block.
```
#+BEGIN_SRC C
#+END_SRC
```
After solving this independently, I noticed @syntaxError also posted this solution above in the comments for @wvxvw's answer. I am submitting it here as an answer because it might be hard to see in a comment on an answer.
---
Tags: org-babel
---
|
thread-31616
|
https://emacs.stackexchange.com/questions/31616
|
How to know which function triggered an autoload of a library
|
2017-03-21T20:17:33.900
|
# Question
Title: How to know which function triggered an autoload of a library
How can I monitor when Emacs loads a library because of an autoloaded function, and also know the name of that function?
**EXAMPLE**: I type `M-x eval-buffer` in a buffer where one of the functions uses `setf` (and I have not previously used this function during my Emacs session). I would like to see a message similar to: "**`setf` called within `name-of-function`, causing it to load `macroexp.el` by virtue of a `require` statement within `gv.el`.**"
Here is a start ...
```
(defun load-tracing-function (orig-fun &rest args)
(message "`load' called with args %S" args)
(let ((res (apply orig-fun args)))
(message "`load' returned %S" res)
res))
(advice-add 'load :around #'load-tracing-function)
(defun require-tracing-function (orig-fun &rest args)
(message "`require' called with args %S" args)
(let ((res (apply orig-fun args)))
(message "`require' returned %S" res)
res))
(advice-add 'require :around #'require-tracing-function)
```
# Answer
> 1 votes
```
(require 'help-fns)
(defun require--tracing-function (orig-fun &rest args)
"When testing with `emacs -q`, start by requiring `help-fns.el`."
(message "`require' called with args %S" args)
(with-current-buffer (get-buffer-create "*TRACE*")
(let* ((standard-output (current-buffer))
(print-escape-newlines t)
(print-level 8)
(print-length 50)
beg end)
(goto-char (point-max))
(setq beg (point))
(setq truncate-lines t)
(set-buffer-multibyte t)
(setq buffer-undo-list t)
(backtrace)
(insert "===============================\n")
(setq end (point))
(narrow-to-region beg end)
(let ((regex
(concat
"^\s+byte-code\("
"\\(\\(?:.\\)*?\\)"
"\s"
"\\[\\(.*\\)\\]"
"\s"
"\\([0-9]+\\)"
"\)"))
(bytestr (propertize "BYTESTR" 'face '(:foreground "RoyalBlue")))
(maxdepth (propertize "MAXDEPTH" 'face '(:foreground "RoyalBlue"))))
(goto-char (point-max))
(while (re-search-backward regex nil t)
(when (match-string 1)
(replace-match bytestr nil nil nil 1))
(when (match-string 2)
(let ((constants
(propertize (match-string 2) 'face '(:foreground "purple"))))
(replace-match constants nil 'literal nil 2)))
(when (match-string 3)
(replace-match maxdepth nil nil nil 3))))
;;; See the Emacs Lisp manual: Byte-Code Function Objects
(let ((regex
(concat
"#\\["
;;; argdesc
"\\([0-9]+\\)"
;;; byte-code
"\\(?:\s\\(.*?\\)\\)?"
"\s"
;;; constants
"\\[\\(.*\\)\\]"
"\s"
;;; stacksize
"\\([0-9]+\\)"
;;; docstring
"\\(?:\s\\(.*?\\)\\)?"
;;; interactive
"\\(?:\s\\(.*?\\)\\)?"
"\\]"))
(argdesc
(propertize "ARGDESC" 'face '(:foreground "orange")))
(byte-code
(propertize "BYTE-CODE" 'face '(:foreground "orange")))
(stacksize
(propertize "STACKSIZE" 'face '(:foreground "orange")))
(docstring
(propertize "DOCSTRING" 'face '(:foreground "orange")))
(interactive
(propertize "INTERACTIVE" 'face '(:foreground "orange"))))
(goto-char (point-max))
(while (re-search-backward regex nil t)
(when (match-string 1)
(replace-match argdesc nil nil nil 1))
(when (match-string 2)
(replace-match byte-code nil nil nil 2))
(when (match-string 3)
(let ((constants
(propertize
(match-string 3) 'face '(:foreground "ForestGreen"))))
(replace-match constants nil 'literal nil 3)))
(when (match-string 4)
(replace-match stacksize nil nil nil 4))
(when (match-string 5)
(replace-match docstring nil nil nil 5))
(when (match-string 6)
(replace-match interactive nil nil nil 6))))
(let ((regex
(concat
"^\s+\(let\\*\s\(\(standard-output.*\(current-buffer\)\)\)$"
"\\|"
"^\s+\(let\s\(\(res\s.*res\)\sres\)$"
"\\|"
(concat "^\s+\(save-current-buffer\s\(set-buffer.*"
"\(current-buffer\)\)\)\)$")
"\\|"
"^\s+backtrace\(\)$"
"\\|"
"^\s+apply\(require--tracing-function .*\)$"
"\\|"
"^\s+require--tracing-function\(.*\)$")))
(goto-char (point-max))
(while (re-search-backward regex nil t)
(delete-region (match-beginning 0) (1+ (match-end 0)))))
(goto-char (point-min))
;;; A slight variation of the built-in `debugger-make-xrefs'.
(while (progn
(goto-char (+ (point) 2))
(skip-syntax-forward "^w_")
(not (eobp)))
(let* ((beg (point))
(end (progn (skip-syntax-forward "w_") (point)))
(fn (function-called-at-point))
(sym (intern-soft (buffer-substring-no-properties beg end)))
(file
(if fn
(let* (
(function fn)
(advised (and (symbolp function)
(featurep 'nadvice)
(advice--p (advice--symbol-function function))))
;; If the function is advised, use the symbol that has the
;; real definition, if that symbol is already set up.
(real-function
(or (and advised
(advice--cd*r
(advice--symbol-function function)))
function))
;; Get the real definition.
(def (if (symbolp real-function)
(or (symbol-function real-function)
(signal 'void-function (list real-function)))
real-function))
(aliased (or (symbolp def)
;; Advised & aliased function.
(and advised (symbolp real-function)
(not (eq 'autoload (car-safe def))))))
(file-name
(find-lisp-object-file-name
function (if aliased 'defun def))))
file-name)
(and sym (symbol-file sym 'defun)))))
(when file
(goto-char beg)
;; help-xref-button needs to operate on something matched
;; by a regexp, so set that up for it.
(re-search-forward "\\(\\sw\\|\\s_\\)+")
(help-xref-button 0 'help-function-def sym file)))
(forward-line 1))
(widen)
(display-buffer (current-buffer))))
(let ((res (apply orig-fun args)))
(message "`require' returned %S" res)
res))
(advice-add 'require :around #'require--tracing-function)
```
* Highlighting C source code functions in the debugging buffer was addressed in the answer to *"Debugging — debugger-mode — how to highlight the culprit"*: https://emacs.stackexchange.com/a/29879/2287 It entails a slight variation of the built-in `debugger-make-xrefs`.
I have submitted a feature request regarding tracing autoloaded functions and here is the tracking link: https://debbugs.gnu.org/cgi/bugreport.cgi?bug=26470
# Answer
> 3 votes
Currently, autoloading a function is done all in C code with fairly few Lisp-visible effects (other than the loading itself). As you have discovered advising `load` may not catch it, for example.
I can see two ways to attack the problem:
* use hooks (e.g. `after-load-functions`) and advice to detect loads, and then use the backtrace mechanism to try and discover what triggered the load (see around `macroexp--trim-backtrace-frame` for code messing with the backtrace for a somewhat related purpose).
* redefine the autoloaded functions you're interested in so they use your own autoloading mechanism rather than the built-in one. It's not terribly hard to do, you can start with:
```
(defun my-autoload (fun file)
(defalias fun (lambda (&rest args) (load file) (apply fun args))))
```
which you can then refine to look at the backtrace to find the caller.
# Answer
> 0 votes
Insert `(backtrace)` at the start of the library.
---
Tags: debugging, autoload
---
|
thread-37247
|
https://emacs.stackexchange.com/questions/37247
|
Specifying filetype when using counsel-git-grep
|
2017-12-02T09:07:46.307
|
# Question
Title: Specifying filetype when using counsel-git-grep
I'm using `counsel-git-grep` to search inside a project for a specific string, which works great. However, I would like to additionally specify a filetype pattern to reduce the result set. I tried queries like `string -- '*.filetype'` but none of them worked. I know I can customize the `counsel-git-grep-cmd-default` but this seems to be a very static approach.
So the question is, is there a way to define a filetype pattern inside a query string of `counsel-git-grep`?
# Answer
I had the same requirement and have found this question on the internet search.
Because I didn't want to modify the git command every timeI wrote a small wrapper which adapts the git grep command to the current file extension:
```
(defun counsel-git-grep-current-mode ()
"Like `counsel-git-grep', but limit to current file extension."
(interactive)
(pcase-let ((`(_ . ,cmd) (counsel--git-grep-cmd-and-proj nil))
(ext (file-name-extension (buffer-file-name))))
(counsel-git-grep nil nil (format "%s -- '*.%s'" cmd (shell-quote-argument ext)))))
```
Source: counsel-git-grep-current-mode
> 1 votes
---
Tags: ivy, counsel
---
|
thread-61730
|
https://emacs.stackexchange.com/questions/61730
|
Is there a way to create an org-mode link that opens help?
|
2020-11-13T22:44:38.457
|
# Question
Title: Is there a way to create an org-mode link that opens help?
For example:
```
* Purpose
Keep some notes to elisp functions.
[[link:elisp-func][elisp-func help]]
```
I want to open the link via `C-c C-o` which would show a buffer with help as though I had ran instead:
`C-h f` `elisp-func` `RET`.
I'm not sure what the right format for the link would be though. I'm suspecting it might be elisp itself, but haven't found the right way to do it.
# Answer
There is. See `(info "(org) External Links")`:
```
[[help:princ]]
```
> 8 votes
# Answer
You can execute arbitrary elisp code from a link:
```
[[elisp:(message "Hello")][Greeting]]
```
Clicking on the link runs the code and you get a greeting in the echo area.
All you have to do is figure out what code to run. The first step is to find out the keybinding of `C-h f`, so do `C-h c C-h f RET` and you see that `C-h f` is bound to the command `describe-function`. Now you can do `C-h f describe-function RET` to get help for this command and find out how to call it. It says that it takes a symbol as argument, e.g. `(describe-function 'describe-function)` gives you the same help. So you could say:
```
[[elisp:(describe-function 'find-file)][Help for find-file]]
```
to do what you asked for.
There are two annoyances:
* you need a separate link for each separate function whose doc string you want to examine. I don't know about you but I'd rather do `C-h f` and enter which function I'm interested in. Or put the cursor on the name and do `C-h f`, so even if I write notes about a function, all I need is the name of the function and the doc string is a couple of keystrokes away.
* when you click on an elisp link, you are asked for confirmation. That's a security precaution: you want to look at the code and make sure that there is nothing dangerous there (either by design or by accident). Being able to execute arbitrary code at the click of a link is dangerous. You can customize the variable `org-link-elisp-confirm-function` to modify this behavior, but check its docstring and heed the warning.
> 5 votes
# Answer
The built-in `help` link type is made for this purpose. Your example would be written as: `[[help:elisp-func][elisp-func help]]`.
> 1 votes
---
Tags: org-mode, help, org-link
---
|
thread-61742
|
https://emacs.stackexchange.com/questions/61742
|
How to keep magit from prompting me for my GitHub username
|
2020-11-15T03:55:58.917
|
# Question
Title: How to keep magit from prompting me for my GitHub username
I'd like to configure magit so that it does not prompt me for my GitHub username when it needs to interact with GitHub in some way (like, say, when doing a push).
My GitHub username is already in the `github.user` elisp variable and git variable, which should be enough according to the ghub documentation, but for some reason it keeps prompting me for my username every time I push.
magit gets my password from an external program which prompts me for my gpg key password which is used to decrypt my GitHub password in pass, and that part works fine.
I also have forge set up to use pass, and when using forge functions from magit I'm not prompted for my username, and only prompted for my gpg key password which decrypts my GitHub password in the same way it does for magit. So if forge could be set up not to prompt for my username, I'd expect there should be some way to configure magit act the same.
Here is my setup:
In my emacs config:
```
(require 'auth-source-pass)
(setq auth-sources '(password-store))
(add-hook 'magit-process-find-password-functions
'magit-process-password-auth-source))
(setq github.user "myusername")
```
From a shell, I typed:
```
git config --global github.user myusername
```
So now my `~/.gitconfig` contains:
```
[github]
user = myusername
```
My `~/.password-store` directory tree looks like this:
```
.
├── api.github.com
│ └── myusername^forge.gpg
└── github.com
└── myusername.gpg
```
I also tried sticking `^magit` after `myusername` and putting both of these variations under `api.github.com`, like the forge entry was, but that didn't help.
# Answer
> 3 votes
I use `pass` and the `password` package in Emacs but for GitHub/GitLab interaction I use SSH keys. Upload your public key to your account and use something like keychain to store your keys on initial login.
Ocassionally I find Emacs doesn't find the Keychain agent so I've the following key-binding to reload..
```
(global-set-key (kbd "C-c k") 'keychain-refresh-environment)
```
---
Tags: magit, github
---
|
thread-61735
|
https://emacs.stackexchange.com/questions/61735
|
Replace existent link in org-mode with org-stored link
|
2020-11-14T08:15:18.573
|
# Question
Title: Replace existent link in org-mode with org-stored link
Assume that I have a hyperlink to a file in org-mode
```
- [[file:~/Documents/one_document.txt][this is a link to one file]]
```
And then for some reason I want to update the linked file to some other file using `org-store-link`.
After using `C-c l`, I move back to my org file(pre-existent link), I hit `C-c C-l` and would hope that UP, DOWN or `M-p` would show me stored links--but it doesn't! Even if I delete the pre-existent link I never get to see the `*Org links*` buffer.
From reading the documentation it seems that I should be able to see the stored links. If so, does anyone knows why I can't? Thank you in advance.
# Answer
Unfortunately, `org-insert-link` (`C-c C-l`) on an existing link does *not* use `org-stored-links`, as you can see in its source:
```
;; Answers note: code taken from `org-insert-link' on commit ff8683aa35
...
(cond
(link-location) ; specified by arg, just use it.
((org-in-regexp org-link-bracket-re 1)
;; We do have a link at point, and we are going to edit it.
(setq remove (list (match-beginning 0) (match-end 0)))
(setq desc (when (match-end 2) (match-string-no-properties 2)))
(setq link (read-string "Link: "
(org-link-unescape
(match-string-no-properties 1)))))
...
```
Instead `org-insert-link` only uses `read-string` with your current link. However, we can use an advice to modify both `org-stored-links` as well as the current link:
```
(defun remove-link-and-mark-description (&rest args)
"Removes the link at point and marks the description.
The previous link gets stored into `org-stored-links'. ARGS is unused"
(cond
((org-in-regexp org-link-bracket-re 1)
(let* ((link (match-string-no-properties 1))
(desc (if (match-end 2) (match-string-no-properties 2) link))
(deactivate-mark))
(push (list (org-link-unescape link) desc) org-stored-links)
(replace-match desc)
(push-mark (match-beginning 0) t t)))
(t nil)))
(advice-add 'org-insert-link :before #'remove-link-and-mark-description)
```
However, the code above is merely a proof of concept. There are some bugs, e.g. the stored link doesn't follow Org's usual `file:...` format if used on files, and `push` should probably get replaced by `add-to-list`.
> 1 votes
---
Tags: org-mode, org-link, hyperlinks
---
|
thread-61747
|
https://emacs.stackexchange.com/questions/61747
|
Any way to remap the meta key with evil?
|
2020-11-15T11:57:11.167
|
# Question
Title: Any way to remap the meta key with evil?
Function modifiers in Emacs conflicts with many hotkeys I have (for example, conflicts with i3wm). By using evil I could use evil to avoid most of conflict hotkeys.
However, I do still need to use those function modifiers to use, for example, `M-x`, but it conflicts with other hotkeys. (For Emacs keymap, `ESC` can be used. But now `ESC` is used by evil, and is no longer a meta substitute.)
What I want to achieve is in normal mode, `;` acts as `ctrl`, and `'` as `alt`, the meta key.
I tried the following but none of them worked:
```
(define-key evil-normal-state-map (kbd "'") 'event-apply-meta-modifier)
(define-key evil-normal-state-map (kbd "'") 'meta)
```
Any ideas how to achieve that?
# Answer
`event-apply-meta-modifier` is only to be used in translation keymaps. You should try
```
(define-key key-translation-map "'" 'event-apply-meta-modifier)
(define-key key-translation-map ";" 'event-apply-control-modifier)
```
This will also make it possible to use these keys in the middle of a key sequence. If you want the keys to only work in normal state, you could use something like
```
(defun evil-normal-state-filter (cmd)
(and (fboundp 'evil-normal-state-p)
(evil-normal-state-p)
cmd))
(define-key key-translation-map "'"
'(menu-item "" event-apply-meta-modifier :filter evil-normal-state-filter))
(define-key key-translation-map ";"
'(menu-item "" event-apply-control-modifier :filter evil-normal-state-filter))
```
See info node `(elisp) Translation Keymaps` and `(elisp) Extended Menu Items` for more information.
> 0 votes
---
Tags: key-bindings, evil
---
|
thread-61086
|
https://emacs.stackexchange.com/questions/61086
|
Emacs freezes when pressing ESC
|
2020-10-09T12:43:54.567
|
# Question
Title: Emacs freezes when pressing ESC
My Emacs usually works well, but sometimes it freezes, to be more specific:
1. It only freezes after pressing ESC.
2. When the freeze begins, it will always freeze after pressing ESC: I kill Emacs, restart it, press ESC, then it freeze again. Unless I restart the the computer. After restarting, Emacs goes to normal again.
3. I can do nothing to bring it back to normal, including `C-g`, `pkill -USR2 emacs`, even `emacsclient -nw` in the terminal freezes.
4. `Emacs -Q` still freezes after pressing `ESC`.
Is there any way to find out the reason and solve it?
I'm using archlinux with GNU Emacs 27.1, this is `uname -a`:
```
Linux archlinux 4.19.18-1-lts #1 SMP Sat Jan 26 13:20:43 CET 2019 x86_64 GNU/Linux
```
# Answer
I solved the problem by upgrading the Linux Kernel from 4.19 to 5.4. Not a perfect answer I know. But in case it's helpful for someone, I posted the answer here.
> 1 votes
---
Tags: debugging
---
|
thread-61672
|
https://emacs.stackexchange.com/questions/61672
|
elpy flymake does not recognize local .pylintrc
|
2020-11-10T17:13:54.320
|
# Question
Title: elpy flymake does not recognize local .pylintrc
I have the following in the project root for my .pylintrc:
```
[FORMAT]
# Maximum number of characters on a single line.
max-line-length=1000
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
# Use 2 spaces consistent with TensorFlow style.
indent-string=' '
```
I am using `elpy` and while I see my syntax checker is correctly recognized as my project's `flake8` binary within its environment, the `.pylintrc` is not being picked up, with the result that long lines and indents are still being highlighted.
How can I tell elpy/flymake/flake8/flycheck to recognize my directory local .pylintrc in my project?
# Answer
Edit:
I remember having this issue once. Turn out my `flycheck-flake8rc` value is ".flake8rc", not ".flake8". Not sure if this applies to you.
---
Original:
According to the OP, you are using `flake8` as your checker, but you are setting `.pylintrc` which is the config file for `pylint`. I've never used pylint, so I might be wrong about this one. But according to `flake8` documentation, it doesn't mention anything about `.pylintrc`:
> Flake8 supports storing its configuration in the following places:
>
> * Your top-level user directory
> * In your project in one of `setup.cfg`, `tox.ini`, or `.flake8`.
>
> Values set at the command line have highest priority, then those in the project configuration file, then those in your user directory, and finally there are the defaults. However, there are additional command line options which can alter this.
> 0 votes
# Answer
`flake8` does not have a plugin for `pylint`. It uses `pyflakes`:
```
→ flake8 --version
3.8.4 (mccabe: 0.6.1, pycodestyle: 2.6.0, pyflakes: 2.2.0) CPython 3.8.6 on Linux
```
There is currently no way to set the indent size in flake8 or pyflakes
I have written a `pylint` backend function for `flymake` function which may also meet your needs:
https://github.com/juergenhoetzel/flymake-pylint
> 0 votes
---
Tags: python, syntax-highlighting, projectile, elpy, directory-local-variables
---
|
thread-61754
|
https://emacs.stackexchange.com/questions/61754
|
How can I enable lexical binding for Elisp code in org-mode?
|
2020-11-15T16:09:55.027
|
# Question
Title: How can I enable lexical binding for Elisp code in org-mode?
I have the following code:
```
#+begin_src elisp
(setq lexical-binding t)
(let ((a 1)) ; binding (1)
(let ((f (lambda () (print a))))
(let ((a 2)) ; binding (2)
(funcall f)))) ; result: 2
#+end_src
```
Since I set `lexical-binding` to `t`, lexical bindings should be used instead of dynamic bindings. So I think the result of the above should be `1`. But the result is `2`. It's as if Emacs is still using dynamic bindings. Why? How can I make it use lexical bindings?
# Answer
Turn on the header `:lexical`, e.g.,
```
#+begin_src elisp :lexical t :results pp
(lambda ())
#+end_src
#+RESULTS:
: (closure
: (t)
: nil)
```
You can also use `#+PROPERTY: header-args:elisp :lexical t` to turn it on for the whole org file. Or change `org-babel-default-header-args:emacs-lisp` to turn it on globally.
`(setq lexical-binding t)` in the code does not work since it's too late, the scope (dynamic or lexical) is already decided BEFORE any of your code runs, hence to turn on lexical-binding, Emacs requires a special comment, which can be added via
```
M-x add-file-local-variable-prop-line lexical-binding t
```
> 6 votes
---
Tags: org-babel, lexical-binding
---
|
thread-61760
|
https://emacs.stackexchange.com/questions/61760
|
Lags when navigating vc-root-diff buffer
|
2020-11-15T22:18:16.757
|
# Question
Title: Lags when navigating vc-root-diff buffer
When I move around the buffer `*vc-diff*` from `vc-root-diff` I experience lags.
GNU Emacs 27.1 (build 1, x86\_64-pc-cygwin) of 2020-10-29.
With `procmon` I detected lots of:
```
C:\opt\cygwin64\bin\git.exe --no-pager ls-files -z --full-name -- application.yml
C:\opt\cygwin64\bin\git.exe --no-pager cat-file blob 4f6e63900c275c7c53519ac0a2f6bc1cdd65abf8:application.yml
```
that generated for each new file in diff...
It is from `vc-git-find-revision`.
Even though I enabled debugging on entering that function Emacs didn't stop there, so I cannot get stack trace which hook is responsible to process spawning.
I want to disable that "feature".
**UPDATE 2023-04-10** Bug report: Emacs keeps opening related file from vc-diff buffer
# Answer
> 2 votes
I already had an issue with hunk refinement, that fixed by:
```
;; Since 27.1 it is enabled during font-lock. Need to disable explicitly.
(setq diff-refine nil)
```
So I checked `/usr/share/emacs/27.1/lisp/vc/diff-mode.el.gz` again and found:
```
(defcustom diff-font-lock-syntax t)
```
So basically Emacs opens file behind in order to build proper syntax highlighting. That triggers slow VC commands. Yes, Cygwin is slow on `fork()`.
Solution:
```
(setq diff-font-lock-syntax 'hunk-only)
```
I think it is a bug that Emacs tries to do `vc-git-find-revision` behind the scene when `diff-font-lock-syntax` it `t`. Exhausted to report it ((
---
Tags: git, vc-mode
---
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.