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-58811
|
https://emacs.stackexchange.com/questions/58811
|
How to expand different snippets depending upon file directory
|
2020-05-30T11:53:11.230
|
# Question
Title: How to expand different snippets depending upon file directory
I have a yasnippet for cperl-mode:
```
# -*- mode: snippet -*-
# name: print Dumper
# key: vd
# --
print Dumper($0);
```
I need to expand this snippet to different strings depending upon the directory of the file I'm editing:
* if dir contains `/mnt/beta/` \- output "die Dumper($0);"
* otherwise - output "print Dumper($0);"
I created the following function:
```
(defun print-dumper ()
"Print certain snippet depending upon file directory"
(interactive)
(let ((file-name (buffer-file-name)))
(if (string-match "/mnt/beta/" file-name)
(insert "die Dumper();")
(insert "print Dumper();")))
(backward-char 2))
```
It works. But how to call it in cperl mode instead of expanding yasnippet? Is there a better way to do this?
# Answer
You can define an abbrev that uses the function you defined:
```
(eval-after-load "perl-mode"
(define-abbrev perl-mode-abbrev-table "vd" "" #'print-dumper))
```
Don't forget to turn on `abbrev-mode` as a minor mode in your perl buffers:
```
(add-hook 'perl-mode-hook #'abbrev-mode)
```
Alternatively, you can probably define conditional yasnippets using the `# condition` directive in the snippet's definition (although I am only slightly familiar with yasnippets, so *caveat emptor*). The documentation says this:
> # condition: snippet condition
>
> This is a piece of Emacs-lisp code. If a snippet has a condition, then it will only be expanded when the condition code evaluate to some non-nil value.
>
> See also yas-buffer-local-condition in Expanding snippets
The problem that I see is that you might not be able to give the same key to the two snippets and I'm not familiar enough with the expansion mechanism to say what would happen if you *were* able to do that. Maybe a yasnippet expert will provide an answer in that case.
> 2 votes
---
Tags: yasnippet
---
|
thread-53153
|
https://emacs.stackexchange.com/questions/53153
|
Python and electric-indent: newline autoindent disregards previous blank line
|
2019-10-14T23:21:59.513
|
# Question
Title: Python and electric-indent: newline autoindent disregards previous blank line
This is (yet) another question related to electric-indent-mode and Python, but since I couldn't find what I address here in the other ones, here we go.
I find the behavior of electric-indent-mode quite useful in general, but there is a minor thing that annoys me:
Say we have the following buffer, where `|` (pipe) represents the cursor position:
```
def example():
if True:
print("Electricity")
|
```
With electric-indent-mode on, pressing `RET` results in the following state:
```
def example():
if True:
print("Electricity")
|
```
The automatic indentation of the newline regards only the first non-empty (i.e., that consists not only of whitespace) previous line. However, what I would like is to have it take into account the **cursor position** of the previous line *if* the previous line consists only of whitespace (and after pressing enter, still remove the whitespace on the previous line afterwards if there was any):
```
def example():
if True:
print("Electricity")
|
```
How can I tweak electric-indent-mode configurations to achieve the desired behavior? Conversely, what are the possible solutions (regardless of using electric-indent-mode or not)?
# Answer
After investigating a related question, I designed a solution that fits me well so far. As electric mode automatically removes whitespace from the previous line, there is no way we could modify a Python-specific function to conform to our desired behavior. Hence, the solution I found was to advise `electric-indent-post-self-insert-function`. With a buffer-local variable that is set to true in the major modes we choose, I modified the behavior of this function to **not remove whitespace from previous line and apply the previous indentation level IF the previous line is an empty line**; if previous line not empty, then perform the default behavior. I hope this can help.
Here is the commit in my dotfiles, and below the code, adapted to be posted here by refactoring necessary functions from my dotfiles to a single place:
```
(defvar-local acg/electric-indent-newline-as-previous-if-blank nil
"Buffer-local variable that indicates one wants to have
`electric-indent-post-self-insert-function' indent a newly
inserted line with the same indentation as the previous line, if
the previous line was a blank line. This variable is used in
`acg/advice--electric-indent-post-self-insert-function'.
Particularly, I find this behavior quite useful in Python, as
discussed in https://emacs.stackexchange.com/q/53153/13589")
(defun acg/line-empty-p (&optional pos)
"Returns `t' if line (optionally, line at POS) is empty or
composed only of whitespace. Adapted from
https://emacs.stackexchange.com/a/16825/13589"
(save-excursion
(goto-char (or pos (point)))
(= (current-indentation)
(- (line-end-position) (line-beginning-position)))))
(defun acg/advice--electric-indent-post-self-insert-function (orig-fun)
"Advice to be put around `electric-indent-post-self-insert-function';
see `acg/electric-indent-newline-as-previous-if-blank'."
(let (pos prev-indent prev-line-blank-p)
(if (and acg/electric-indent-newline-as-previous-if-blank
(save-excursion
(previous-line)
(setq prev-line-blank-p (acg/line-empty-p))))
;; Section below is part of the original function that I adapted
(when (and electric-indent-mode
;; Don't reindent while inserting spaces at beginning of line.
(or (not (memq last-command-event '(?\s ?\t)))
(save-excursion (skip-chars-backward " \t") (not (bolp))))
(setq pos (electric--after-char-pos))
(save-excursion
(goto-char pos)
(let ((act (or (run-hook-with-args-until-success
'electric-indent-functions
last-command-event)
(memq last-command-event electric-indent-chars))))
(not
(or (memq act '(nil no-indent))
;; In a string or comment.
(unless (eq act 'do-indent) (nth 8 (syntax-ppss))))))))
;; Get value of previous indentation
(save-excursion
(previous-line)
(setq prev-indent (current-indentation)))
;; Indent current line catching errors
(let ((at-newline (<= pos (line-beginning-position))))
(unless (and electric-indent-inhibit
(not at-newline))
(condition-case-unless-debug ()
;; (indent-according-to-mode)
(indent-line-to prev-indent)
(error (throw 'indent-error nil))))))
;; If not using modification or not blank line above, back to default
(funcall orig-fun))))
(advice-add 'electric-indent-post-self-insert-function :around #'acg/advice--electric-indent-post-self-insert-function)
;; (advice-remove 'electric-indent-post-self-insert-function #'acg/advice--electric-indent-post-self-insert-function)
(add-hook
'python-mode-hook
(lambda () (setq acg/electric-indent-newline-as-previous-if-blank t)))
```
> 0 votes
# Answer
Typing \[control j\] instead of RET should jump to the beginning of line when electric-indent-mode is on. If EIM is off, RET jumps to the BOL and C-j to indent.
> 1 votes
# Answer
I see the need for this every day. The current behavior is really annoying, to the point of distracting me from the flow of writing code productively.
I have entered the previous code:
```
def example():
if True:
print("Electricity")
```
Entering a newline lines up the next line with the beginning of the print statement. To start a new definition, I have to hit TAB three times to get the cursor to the left margin. Then I realize I want a blank line, so I hit newline. This puts the indent back at the "print" level. 3 more TABS, then enter a comment:
```
# The following def does ...
```
Hitting newline then indents the comment to the "print" level.
```
def example():
if True:
print("Electricity")
# The following def does ...
```
Now, position the cursor at the comment's #, hit M-\ (or 3 tabs), and the comment is at the left margin. Move to next line, hit M-\ (or 3 tabs) to get to left margin, and type:
```
def foo():
```
hitting newline indents the "def" to the "print" level, leaving the preceding comment at the left margin.
```
def example():
if True:
print("Electricity")
# The following def does ...
def foo():
```
Move to the next line, hit enough tab characters to get to the left margin, and we're ready to start typing the def's body. At this point, the indentation stays where I want it to be, unless, after modifying the def's header, I hit newline, which will indent the def back to the "print" level. This happens even if there is a multi-line comment block before the "def"!
So, that's at least 3 instances of unwanted indentation, along with 9 tabs to undo the unwanted behavior, namely, lining up the indent with the previous line, especially when the previous line has been indented correctly, manually, by me.
@ArthurColombiniGusmΓ£o suggests that this will disturb users. Sure, it might. But it's a lot less disturbing to have properly-indented lines un-indented multiple times. If I end up with an unexpected indentation because the previous line was indented for some other reason, I should be able to fix it (by hitting TAB enough times), and know that my "def" won't be unwantedly indented, and not have that work undone by hitting newline.
> 1 votes
---
Tags: python, electric-indent
---
|
thread-58815
|
https://emacs.stackexchange.com/questions/58815
|
How to set name of an Emacs frame?
|
2020-05-30T16:22:24.383
|
# Question
Title: How to set name of an Emacs frame?
I am new to Emacs, I use text Emacs (inside Putty) and I am from Vim land. So, bare with me about the terminologies that I use.
I want to have a custom string in the mode line for the frame name (to remember why I created this frame) as the defaults like "F6" is of no use to me.
I found how to create new frame and set-frame-parameter from gnu.org. I gave a try to create new frame from elisp (the first link):
```
(setq x '(("name" . "parsing")))
(make-frame x)
```
But the frame it created has the name F6. I checked it executing `(frame-list)` (shown in picture above). What am I doing wrong here? Is there an easy way?
# Answer
The parameter name needs to be a *symbol* rather than a *string*, i.e.
```
(make-frame '((name . "parsing")))
```
rather than
```
(make-frame '(("name" . "parsing")))
```
> 3 votes
---
Tags: frames
---
|
thread-58814
|
https://emacs.stackexchange.com/questions/58814
|
How to bind C-h to delete-backward-char when doing isearch?
|
2020-05-30T15:10:46.130
|
# Question
Title: How to bind C-h to delete-backward-char when doing isearch?
I use C-h as an alias for `delete-backward-char` everywhere.
But when I do isearch it exits the search instead of deleting the character before the cursor.
I tried binding C-h in isearch maps, but that didn't work:
```
(define-key minibuffer-local-isearch-map (kbd "C-h") 'delete-backward-char)
(define-key isearch-mode-map (kbd "C-h") 'delete-backward-char)
```
Character gets deleted, but it is deleted in the buffer, not in the isearch prompt.
Is there a way to rebind C-h so it works in isearch prompt?
# Answer
First, in general, Isearch uses the minibuffer only for `M-e`. So your `minibuffer-local-isearch-map` key binding is useless here. That's the keymap used when editing after `M-e`.
Second, your `isearch-mode-map` binding means that `C-h` ends up deleting the char in the buffer you're searching, not deleting a char from the search string. The current buffer remains the buffer you're searching.
This is what you need to do. It defines a command that pops the last char off of the end of the search string.
```
(defun foo ()
"Delete last char of the search string."
(interactive)
(unless (equal isearch-string "") (isearch-pop-state))
(isearch-update))
(define-key isearch-mode-map (kbd "C-h") 'foo)
```
> 1 votes
---
Tags: key-bindings, isearch, deletion
---
|
thread-58796
|
https://emacs.stackexchange.com/questions/58796
|
Adding a lambda function as hook in use-package
|
2020-05-29T15:53:15.307
|
# Question
Title: Adding a lambda function as hook in use-package
I'm trying to adapt this answer to use-package elegantly. It requires that I hook a lambda function to python-mode. I came up with this solution β which works:
```
(use-package python
:hook
(python-mode . (lambda ()
(setq indent-tabs-mode t)
(setq tab-width 4)
(setq python-indent-offset 4))))
```
but I find it inelegant, as it requires me to repeat "python-mode" inside the use-package for python (shouldn't that be obvious?). Is there a better way, and if not, why? I'm not sure I understand well the hook process in use-package.
# Answer
> 1 votes
Potentially the simplification of defaulting to `<modename>-mode-hook`, for a given `<modename>`, could have been implemented in `use-package`, yes, since it is in the Major Mode Conventions. However, it seems the authors decided to use this notation to simplify adding the current package (the package in the current use-package declaration) to another hook; see \[here\]. Also, notice that hooks may be used for several other reasons than to start major modes, so their name may vary a lot.
---
Tags: hooks, use-package
---
|
thread-58799
|
https://emacs.stackexchange.com/questions/58799
|
clang-format-buffer with tramp doesn't actually format buffer
|
2020-05-29T18:48:18.057
|
# Question
Title: clang-format-buffer with tramp doesn't actually format buffer
I'm using Tramp to edit files on a remote machine, and when I run `clang-format-buffer`, it doesn't actually format the buffer. I get a message `(clang-format: success)` in the minibuffer, but the expected changes are not made in the buffer. If I use `clang-format-buffer` on a local copy of the file, it formats the file correctly.
What am I missing to get it to operate correctly on the buffer in Emacs using Tramp?
# Answer
> 2 votes
I don't know which package you are using, but I guess it is `clang-format-20191121.1708` from MELPA. I've inspected the source code, and it uses `call-process-region` internally. `call-process` is agnostic to remote files, I suggest you contact the author of that package for supporting of remote files.
---
Tags: tramp, clang-format
---
|
thread-58650
|
https://emacs.stackexchange.com/questions/58650
|
RCS Version Control on Tramp Mode
|
2020-05-21T20:01:04.323
|
# Question
Title: RCS Version Control on Tramp Mode
Began using `RCS` Version Control within Emacs with no problem while locally, but having dificulty on Tramp mode, once it says:
```
Debugger entered--Lisp error: (error "This file is already registered")
signal(error ("This file is already registered"))
error("This file is already registered")
vc-register((RCS ("/scp:user@192.168.1.3#2222:/home/user/Teste/Teste01.txt") ("/scp:user@192.168.1.3#2222:/home/user/Teste/Teste01.txt") unregistered locking))
vc-next-action(nil)
funcall-interactively(vc-next-action nil)
call-interactively(vc-next-action nil nil)
command-execute(vc-next-action)
```
Created file, stroke `C-v-v`, set `RCS` as backend, made some changes, saved it, when stroke `C-v-v` to insert changes, received upward error massage.
Already certified that both directory and files were on `Tramp` user login.
Anyway that `RCS` could be used within `Tramp` mode?
# Answer
> 2 votes
There seems to be an error in the `vc-rcs` backend. I've tried to register a remote file in RCS, like you did. My debug trace looks different:
```
Debugger entered--Lisp error: (error "Failed (status 1): ci -u -t- /ssh:gandalf:/tmp/aa...")
signal(error ("Failed (status 1): ci -u -t- /ssh:gandalf:/tmp/aa..."))
error("Failed (%s): %s" "status 1" "ci -u -t- /ssh:gandalf:/tmp/aaa/aaa")
vc-do-command("*vc*" 0 "ci" "/ssh:gandalf:/tmp/aaa/aaa" nil "-u" "-t-")
apply(vc-do-command "*vc*" 0 "ci" "/ssh:gandalf:/tmp/aaa/aaa" nil "-u" "-t-" nil)
vc-rcs-register(("/ssh:gandalf:/tmp/aaa/aaa") nil)
apply(vc-rcs-register (("/ssh:gandalf:/tmp/aaa/aaa") nil))
vc-call-backend(RCS register ("/ssh:gandalf:/tmp/aaa/aaa") nil)
vc-register((RCS ("/ssh:gandalf:/tmp/aaa/aaa") unregistered locking))
(progn (vc-register '(RCS ("/ssh:gandalf:/tmp/aaa/aaa") unregistered locking)))
eval((progn (vc-register '(RCS ("/ssh:gandalf:/tmp/aaa/aaa") unregistered locking))) t)
elisp--eval-last-sexp(nil)
eval-last-sexp(nil)
funcall-interactively(eval-last-sexp nil)
call-interactively(eval-last-sexp nil nil)
command-execute(eval-last-sexp)
```
However, the `vc-do-command` uses `"/ssh:gandalf:/tmp/aaa/aaa"` as file name, which is wrong. It should use only the local part of that file name, `"/tmp/aaa/aaa"`.
I recommend that you write an Emacs bug report.
---
Tags: tramp, version-control
---
|
thread-58629
|
https://emacs.stackexchange.com/questions/58629
|
Function `cd` not working correctly in conjunction with `tramp` and `compile`
|
2020-05-21T02:49:27.613
|
# Question
Title: Function `cd` not working correctly in conjunction with `tramp` and `compile`
For context I am looking at a remote file; for example: `/ssh:desktop:/home/user/project/src/file.cpp`.
I then issue the interactive command `compile` like so:
`cd /ssh:desktop:/home/user/project/Release && make`
And get the following output:
```
-*- mode: compilation; default-directory: "/ssh:desktop:/home/user/project/Release/" -*-
Compilation started at Wed May 20 22:42:42
cd /ssh:desktop:/home/user/project/Release && make
/bin/sh: 2: cd: can't cd to /ssh:desktop:/home/user/project/Release
Compilation exited abnormally with code 2 at Wed May 20 22:42:43
```
---
Then I tried issuing the interactive command `compile` differently (without the remote prefix):
`cd /home/user/project/Release && make`
And get the following error:
```
No such directory found via CDPATH environment variable
```
---
I can't quite figure it out, but I suspect that the function `cd` (in site-lisp file `emacs/lisp/files.el`) has something to do with it:
```
(defun cd (dir)
"Make DIR become the current buffer's default directory.
If your environment includes a `CDPATH' variable, try each one of
that list of directories (separated by occurrences of
`path-separator') when resolving a relative directory name.
The path separator is colon in GNU and GNU-like systems."
(interactive
(list
;; FIXME: There's a subtle bug in the completion below. Seems linked
;; to a fundamental difficulty of implementing `predicate' correctly.
;; The manifestation is that TAB may list non-directories in the case where
;; those files also correspond to valid directories (if your cd-path is (A/
;; B/) and you have A/a a file and B/a a directory, then both `a' and `a/'
;; will be listed as valid completions).
;; This is because `a' (listed because of A/a) is indeed a valid choice
;; (which will lead to the use of B/a).
(minibuffer-with-setup-hook
(lambda ()
(setq-local minibuffer-completion-table
(apply-partially #'locate-file-completion-table
cd-path nil))
(setq-local minibuffer-completion-predicate
(lambda (dir)
(locate-file dir cd-path nil
(lambda (f) (and (file-directory-p f) 'dir-ok))))))
(unless cd-path
(setq cd-path (or (parse-colon-path (getenv "CDPATH"))
(list "./"))))
(read-directory-name "Change default directory: "
default-directory default-directory
t))))
(unless cd-path
(setq cd-path (or (parse-colon-path (getenv "CDPATH"))
(list "./"))))
(cd-absolute
(or
;; locate-file doesn't support remote file names, so detect them
;; and support them here by hand.
(and (file-remote-p (expand-file-name dir))
(file-accessible-directory-p (expand-file-name dir))
(expand-file-name dir))
(locate-file dir cd-path nil
(lambda (f) (and (file-directory-p f) 'dir-ok)))
(error "No such directory found via CDPATH environment variable"))))
```
# Answer
> 3 votes
Your command `cd /ssh:desktop:/home/user/project/Release && make` will be given to a shell on the remote machine. This doesn't know any Tramp syntax, and it runs already on the proper host. So you shall use the command `cd /home/user/project/Release && make` instead.
---
Tags: tramp, files, environment, compile
---
|
thread-58824
|
https://emacs.stackexchange.com/questions/58824
|
How to jump to backward found word when switched into reverse incremental search?
|
2020-05-31T11:29:08.537
|
# Question
Title: How to jump to backward found word when switched into reverse incremental search?
When I do `I-search:` or `I-search-backward` , it starts right away from the first word it find.
Original behavior:
```
word1 |[cursor]word1 ; cursor moves here
wor[cursor]d2 ;<= I press `ctrl+r` word [enter] |word2
word3 |word3
```
---
For example, when I am in `I-search`, I want to start doing backward search and press `ctrl+r` but in the first press it remains in the current found word (cursor move into its beginning) and on the second press to `ctrl+r`, \`emacs jumps to the found word on backward.
**Example:**
```
word1 |word1
wor[cursor]d2 ;<= I press `ctrl+s` word [enter] |word2
word3 |word3[cursor]; cursor moves here
```
then
```
word1 |word1
word2 |word2
word3[cursor] ;<= I press `ctrl+r` word [enter] |[cursor]word3 ; cursor moves here
```
at this stage I want cursor to move beginning of `word2` like it should do on its original behavior.
---
=\> I was wondering when the switch from `I-search:` to `I-search-backward` or visa versa, can the action take place on the first click instead of two?
# Answer
It's all based on where the cursor is when you start the search.
`C-h``i``g` `(emacs)Basic Isearch` says:
> A backward search finds matches that **end before** the starting point, just as a forward search finds matches that **begin after** it.
Hence for:
```
word1
wor[cursor]d2
word3
```
Searching backwards for `word` cannot find word2 because that instance of "word" doesn't end before \[cursor\].
```
word1
word2
word3[cursor]
```
Searching backwards here, we will initially find word3, as that instance of "word" ends before \[cursor\].
---
Edit: The following is *extremely* minimally tested, but give this a whirl:
```
(define-advice isearch-repeat (:before (direction &optional count) goto-other-end)
"If reversing, start the search from the other end of the current match."
(unless (eq isearch-forward (eq direction 'forward))
(when isearch-other-end
(goto-char isearch-other-end))))
```
> 1 votes
---
Tags: isearch, words
---
|
thread-58683
|
https://emacs.stackexchange.com/questions/58683
|
Using tramp and ESS-mode, how can I get the R interpreter to execute locally?
|
2020-05-23T20:33:41.567
|
# Question
Title: Using tramp and ESS-mode, how can I get the R interpreter to execute locally?
I use tramp to edit R files on a remote server. When I evaluate R code within ESS-mode, it starts an R interpreter on the remote machine. However, at the moment `ssh -X` to the server does not work, so any R command that produces graphics does not connect to my local X11 server.
Is it possible to configure things so that ESS launches a local R interpreter and, hence, graphics would be displayed locally?
# Answer
I don't think that TRAMP can work well in this use case. You mention `sshfs` in a comment, but the two work differently.
`sshfs` and TRAMP take opposite approaches. `sshfs` makes remote files appear local with a mount, allowing all processing to be local. TRAMP sends all processing to the remote machine, where files are dealt with as local only.
So I don't think you can solve your use case with TRAMP. If you do want to save the remote graphics as files without invoking a viewer, you will be able to view those files in Emacs. But that's a different workflow.
> 1 votes
# Answer
I've fixed my `ssh -X` problem. Using `tramp`, in the remote R interpreter launched by `ESS`
```
> View(tibble)
```
with a 3,722-row tibble is not responsive with my 200 Mbps download speed. But using `sshfs` the same R interpreter is local and, hence, the `View` graphic is just as responsive as if I were sitting at the console of the remote machine. For me, this is the best workflow for creating R scripts at the remote machine. Thanks to gregoryg for comparing tramp/sshfs workflows and explaining that launching a local R process with `tramp` is not possible.
> 2 votes
---
Tags: tramp, ess, x11
---
|
thread-58831
|
https://emacs.stackexchange.com/questions/58831
|
Can I execute a code block in org-mode without exporting it?
|
2020-06-01T01:05:15.487
|
# Question
Title: Can I execute a code block in org-mode without exporting it?
I was following this blog about using org-mode for writing papers, and the author said
> Use C-c C-e l l to create a LaTeX file. Then, **from the terminal**, use Pandoc as follows to create an odt or a docx file.
```
pandoc --bibliography=biblidatabase.bib --filter pandoc-citeproc \
latexfile.tex -o outputfile.odt
```
*Is it possible to run this shell command within the same org document?*
I tried to add a bash source code block in the `.org` file:
```
#+BEGIN_SRC bash
pandoc --bibliography=biblidatabase.bib --filter pandoc-citeproc \
latexfile.tex -o outputfile.odt
#+END_SRC
```
But then, this code block showed up in the exported `.odt` file. This is expected, but of course, I don't want this shell command (*or its output*) in the final paper.
*Would it be possible to suppress this code block during the export and prevent it from showing up in the exported file?*
# Answer
Adding `:exports none` should take care of that:
```
#+BEGIN_SRC bash :exports none
pandoc --bibliography=biblidatabase.bib --filter pandoc-citeproc \
latexfile.tex -o outputfile.odt
#+END_SRC
```
See Exporting Code Blocks in the manual.
> 3 votes
---
Tags: org-mode, org-export
---
|
thread-58826
|
https://emacs.stackexchange.com/questions/58826
|
How do I insert a breakpoint so that edebug starts only when that point is reached
|
2020-05-31T18:42:32.920
|
# Question
Title: How do I insert a breakpoint so that edebug starts only when that point is reached
I want to instrument a function so that edebug gets control when that point is reached. I can insert `(edebug)` in the code, however, unless the function is instrumented with edebug (`C-u M-S-x`), that will be interpreted as `(debug)`, which I don't want. But if the function is instrumented with edebug, then a break occurs everytime the function is called, not just when the particular point in the function is reached. I only want the break to occur (and get control with edebug) when a particular place in the function is reached.
# Answer
> 4 votes
Customize the user option `C-h``v` `edebug-initial-mode` or use `M-x` `edebug-set-initial-mode`<sup>1</sup> to set the value `go` instead of the default `step`.
In the absence of relevant breakpoints, an instrumented function will now simply run to completion without interruption.
Note that you can set breakpoints in an instrumented function with `M-x edebug-set-breakpoint` or `M-x edebug-set-conditional-breakpoint`, or using the `C-x``X``C-h` bindings, without the debugger being active at the time.
---
<sup>1</sup> See `C-h``i``g` `(elisp)Edebug Execution Modes` for the valid options.
In `emacs-lisp-mode` buffers (but not in the `*scratch*` buffer's `lisp-interaction-mode`, which seems like a bug) you also have the following GUD-style bindings available when edebug has been loaded:
```
C-x C-a C-c edebug-go-mode
C-x C-a C-s edebug-step-mode
C-x C-a C-n edebug-next-mode
C-x C-a C-l edebug-where
```
As well as this non-GUD binding under the same prefix:
```
C-x C-a RET edebug-set-initial-mode
```
Hence:
* `C-x``C-a``RET``g` -- change initial mode to `go`.
* `C-x``C-a``RET``SPC` -- change initial mode to `step`.
---
Tags: edebug
---
|
thread-58835
|
https://emacs.stackexchange.com/questions/58835
|
How to provide keyboard input programmatically for org-export-dispatch UI in elisp?
|
2020-06-01T03:39:19.700
|
# Question
Title: How to provide keyboard input programmatically for org-export-dispatch UI in elisp?
The `org-export-dispatch` command in org-mode (`C-c C-e`) brings up an UI from which one can, e.g. select `l` and `l` to export the .org file to latex format.
My question is:
*Can one use elisp to fix the input to `l` and `l` programmatically in order to get the exported (latex) file without any keyboard interaction?*
If so, what would the expression/command be?
This is with Emacs 26 under Ubuntu 20.04. I read this article but just don't know elisp enough to understand its workings.
# Answer
Unless you spend your days exporting org documents I'd stick to the export interface because it's mature and takes care of the little details.
If you still want something to bind to a single key, a very minimal implementation of it could be:
```
(defun my/to-latex-file()
(interactive)
(org-export-to-file 'latex (read-from-minibuffer "Filename for latex file: ")))
```
Note that it won't test if the filename you choose already exists or anything.
This snippet will use original file path/name to automatically use the same with `.tex` extension, still, it won't care about any previous file:
```
(defun my/to-latex-file()
(interactive)
(let ((filename (buffer-file-name)))
(setq filename (replace-regexp-in-string "\.org\$" "\.tex" filename))
(org-export-to-file 'latex filename)))
```
> 4 votes
---
Tags: org-mode, keyboard, inputs
---
|
thread-58820
|
https://emacs.stackexchange.com/questions/58820
|
How can I make abbreviations expand instantly?
|
2020-05-31T04:49:46.580
|
# Question
Title: How can I make abbreviations expand instantly?
Is there a way to make emacs expand abbreviations as soon as I finish typing them, rather than having to use a key combination, tab, or space?
For example, I want "\`a" to expand to "\alpha". It would be nice if it could expand as soon as I type the "a".
I have tried abbrev-mode, but I can't figure out how to do expansions without typing a space (or other expansion character) after the abbreviation. The EmacsWiki explains how to prevent the expansion character from appearing after typing it, but that's not what I want. I also tried yasnippet, but it requires a trigger key, as far as I can tell from the documentation.
My specific motivation is to reproduce Vim-LaTeX-Suite macros, similar to this more general question asked here before.
# Answer
> 0 votes
Following Dan's suggestion, I figured it out using input methods:
```
(quail-define-package
"vim-LaTeX-suite" "" "v-LTX-s" t
"Input method to reproduce vim-LaTeX-suite keybindings"
nil t nil nil nil nil nil nil nil nil t)
(quail-define-rules
("`a" ["\\alpha"])
("`b" ["\\beta"])
)
```
In vim-latex-suite, typing ``/` for example produces `\frac{}{<++>}<++>`, with the cursor inside the first set of braces. This behavior can be reproduced using the advice feature of `quail-define-rules`. For example:
```
(quail-define-package
"vim-LaTeX-suite" "" "v-LTX-s" t
"Input method to reproduce vim-LaTeX-suite keybindings"
nil t nil nil nil nil nil nil nil nil t)
; Jump cursor back to the first instance of <++>, like in vim-latex-suite
(defun my/quail-vls-jumper (str)
(interactive)
(let
((len (length str))
(jpos (cl-search "<++>" str))
)
(if jpos
(progn
(backward-char (- len jpos))
(delete-forward-char 4)
(evil-insert-state)
)
)
)
)
(quail-define-rules
((advice . my/quail-vls-jumper))
("`a" ["\\alpha"])
("`b" ["\\beta"])
("`/" ["\\frac{<++>}{<++>}<++>"])
("^^" ["^{<++>}<++>"])
)
```
I only started emacs and lisp in the last couple weeks, so there may be various bugs and poor style. But, this solution seems to work for me.
---
Tags: yasnippet, abbrev, vim-emulation
---
|
thread-58838
|
https://emacs.stackexchange.com/questions/58838
|
Add element to org-refile-targets
|
2020-06-01T08:51:32.230
|
# Question
Title: Add element to org-refile-targets
I am keeping a common `init.el` for work and private on separate machines. So dependent on my machine I have common settings and machine dependent settings.
How do I get to add an element to the `org-refile-targets` variable?
This works well:
```
(setq org-refile-targets '(("~/sync/common.org" :maxlevel . 2)
("~/org/machine1.org" :maxlevel . 2)))
```
How can I separate this variable definition?
Not working:
```
(add-to-list 'org-refile-targets ("~/sync/common.org" :maxlevel . 2))
[...]
(add-to-list 'org-refile-targets ("~/org/machine1.org" :maxlevel . 2))
```
Testing results in an error of:
`*** Eval error *** Invalid function: "~/org/machine1.org"`
# Answer
> 0 votes
If you try to add a list such way it will be evaluated and interpreted as function. Quote it.
```
(add-to-list 'org-refile-targets '("~/sync/common.org" :maxlevel . 2))
```
---
Tags: org-mode, variables
---
|
thread-58840
|
https://emacs.stackexchange.com/questions/58840
|
How to search with a regexp before point?
|
2020-06-01T10:11:19.657
|
# Question
Title: How to search with a regexp before point?
I would like to know *a function* that searches a pattern located before point.
`re-search-backward` is mentioned in the Elisp manual but I do not understand its purpose. Indeed, I do not understand the explanation given in the manual nor some of the cases found.
> **re-search-backward** *regexp &optional limit noerror count*
>
> This function searches backward in the current buffer for a string of text that is matched by the regular expression *regexp*, leaving point at the beginning of the first text found.
>
> This function is analogous to `re-search-forward`, but they are not simple mirror images. `re-search-forward` finds the match whose beginning is as close as possible to the starting point. `re-search-forward` finds the match whose beginning is as close as possible to the starting point. If `re-search-backward` were a perfect mirror image, it would find the match whose end is as close as possible. However, in fact it finds the match whose beginning is as close as possible (and yet ends before the starting point). The reason for this is that matching a regular expression at a given spot always works from beginning to end, and starts at a specified beginning position.
I did a search but found only unsatisfactory answers.
1. emacs greedy search-backward-regexp
2. Why is the order of : and - important in a regexp character class
These threads suggest that there is no standard solution. The use of `skip-chars-backward` seems to me particularly unsuitable because it is used for the internal workings of Emacs (see `syntax.c`).
Suppose the current buffer contains only a string of text composed of alphabetic characters (e.g. `abc`), anywhere before the point. In this case, `(re-search-backward "[[:alpha:]]+")` moves the point between the last two characters (between `b` and `c`) when the position is expected to be at the beginning of the text (before `a`).
# Answer
It gives you the first match it finds.
In your `abc` example, `c` is a match for `[[:alpha:]]+`, so it stops there. The actual regexp matching is always forwards; it's just the starting position which is moved backwards until a match is found. If you searched for `"\\b[[:alpha:]]+"` then `abc` would be the first match.
Note that what you are (IIUC) expecting would require not merely finding a successful match; but continuing to iteratively perform the pattern match from *every earlier starting position in the buffer* in turn (within the specified bounds), in order to discover the longest match -- potentially a *very* expensive operation. Note that you can't stop at the first non-matching position, because there might be positions before that which once again match through to the required end-point. Unless the pattern is anchored in some way which provides a *guaranteed* limit to how far back it could start, you can't know which of the potential start points will provide the longest match<sup>1</sup> without checking all of them.
(In your example, we can of course see that any non-alpha character imposes a guaranteed limit for matching the regexp `[[:alpha:]]+`; but that is a very trivial case, whereas any such behaviour in Emacs would need to be generalised for regexps of *arbitrary complexity*.)
Searching forwards is usually better than searching backwards, if you can make it work. If you know the bounds of the searchable text (and you generally want to have those regardless), then a forwards search from that start point may be easier to reason about.
---
<sup>1</sup> Not that the normal regexp searches guarantee the longest match in any case, which is why we have `C-h``i``g` `(elisp)POSIX Regexps` -- but those also don't behave any differently with respect to the backwards-search start-point issue, and so using `posix-search-backward` doesn't change the outcome of your example at all.
> 1 votes
---
Tags: regular-expressions, search
---
|
thread-58845
|
https://emacs.stackexchange.com/questions/58845
|
Export only headlines of a certain level
|
2020-06-01T16:04:33.613
|
# Question
Title: Export only headlines of a certain level
This one is pretty straightforward. I'm translating in emacs org-mode, and my workflow looks a bit like this:
```
* Source text sentence
** Translation of source text sentence
* Another source text sentence
** The translation of that other sentence
```
What I'd like to do is take all (and only) second level headlines (which are my translations) and copy them into a separate document. Is this possible, or am I thinking too outside the box?
Thanks!
# Answer
> 5 votes
Another approach is to delete all non-level-2 entries before parsing the export buffer. This is different to what @gregoryg is proposing in that it also skips the body/text directly following non-level-2 headings. No need to use tags.
```
(defun export-translation (backend)
(org-map-entries
(lambda ()
(unless (= (org-current-level) 2)
(let ((beg (line-beginning-position))
(end (or (save-excursion
(outline-next-heading))
(point-max))))
(delete-region beg end))))))
```
You can add this function to `org-export-before-parsing-hook` as a file variable by adding the following line to the beginning of the Org document.
```
# -*- org-export-before-parsing-hook: export-translation -*-
```
Now to also skip the contents of level-2 entries, use:
```
(defun export-translation (backend)
(save-excursion
(goto-char (point-max))
(while (re-search-backward org-complex-heading-regexp nil t)
(let ((beg (save-excursion
(when (= (org-current-level) 2)
(forward-line))
(point)))
(end (or (save-excursion
(outline-next-heading))
(point-max))))
(delete-region beg end)))))
```
# Answer
> 2 votes
You can use `ox-extra` functions from the `org-plus-contrib` package.
This would require you to tag all top-level headlines with the "ignore" tag.
```
(require 'ox-org) ; if exporting to Org Mode
(require 'ox-extra)
(ox-extras-activate '(ignore-headlines))
```
After tagging your top-level headlines, export to a plain text or Org file, e.g. `C-c C-e O o`
You can cancel your filter with
```
(ox-extras-deactivate '(ignore-headlines))
```
As @NickD points out, this method removes the headlines only - it will still export any text under that headline.
---
Tags: org-mode
---
|
thread-58406
|
https://emacs.stackexchange.com/questions/58406
|
Tramp is operating on host filesystem instead of container filesystem
|
2020-05-10T06:12:47.823
|
# Question
Title: Tramp is operating on host filesystem instead of container filesystem
I'm using a slightly modified version of the usual docker tramp integration (below) which works fine to complete up to `/docker:container_name:` but where it goes wrong is it opens files on the host computer, and performs completion from the host file-system instead of in the container. Can anyone help me fix this?
```
(require 'tramp)
(setq tramp-verbose 10)
(push
(cons
"docker"
'((tramp-login-program "docker")
(tramp-login-args (("exec" "-it") ("%h") ("/bin/bash")))
(tramp-remote-shell "/bin/bash")
(tramp-remote-shell-args ("-i") ("-c"))
))
tramp-methods)
(defadvice tramp-completion-handle-file-name-all-completions
(around dotemacs-completion-docker activate)
"(tramp-completion-handle-file-name-all-completions \"\" \"/docker:\" returns
a list of active Docker container names, followed by colons."
(if (equal (ad-get-arg 1) "/docker:")
(let* ((dockernames-raw (shell-command-to-string "/usr/local/bin/docker ps | awk '$NF != \"NAMES\" { print $NF \":\" }'"))
(dockernames (cl-remove-if-not
#'(lambda (dockerline) (string-match ":$" dockerline))
(split-string dockernames-raw "\n"))))
(setq ad-return-value dockernames))
ad-do-it))
```
# Answer
This was somehow `ido-mode`'s fault. Disabling `ido-mode` in my emacs config fixed it. No idea why.
> 1 votes
---
Tags: tramp, docker
---
|
thread-58850
|
https://emacs.stackexchange.com/questions/58850
|
using bibtex in org-mode messes up inlineimages of latex preview?
|
2020-06-01T22:40:08.743
|
# Question
Title: using bibtex in org-mode messes up inlineimages of latex preview?
I had latex preview working with inlineimages as in the following .org file:
```
#+STARTUP: latexpreview
#+STARTUP: inlineimages
$A \to B$
```
The latex formula is correctly changed into a png image as follows:
However, once I start to add a bibtex line, the image preview breaks down. With this slightly changed .org file:
```
#+STARTUP: latexpreview
#+STARTUP: inlineimages
#+LATEX_HEADER: \addbibresource{test.bib}
$A \to B$
```
, org-mode generates an incorrect image for the same formula with the name of the bibtex file (`test.bib`) in it:
*Does anyone know what's happening here and how to fix it?*
By the way, this is with the default Emacs 26 in Ubuntu 20.04. And I used the setup of this tutorial. When the .org file is exported to ODT format, the formula are actually correct, and bibliography (not shown in this minimal example) also works well. It's just the preview in emacs that went wrong (for every formula).
# Answer
You need to use `LATEX_HEADER_EXTRA` instead of `LATEX_HEADER`. You also need Org mode release 9.1 or later. Be sure to clean out the `ltximg/` subdirectory in order to regenerate clean preview images after you apply the necessary fixes.
The documentation says
> The LaTeX export back-end appends values from βLATEX\_HEADERβ and βLATEX\_HEADER\_EXTRAβ keywords to the LaTeX header. The docstring for βorg-latex-classesβ explains in more detail. Also note that LaTeX export back-end does not append βLATEX\_HEADER\_EXTRAβ to the header when previewing LaTeX snippets (see \*note Previewing LaTeX fragments::).
Pre-9.1 releases contained a bug that was fixed with the following commit:
```
commit e903288e5080775cbd4d87c69deeba3268cda5c1
Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
Date: Sun Jun 25 09:39:32 2017 +0200
ox-latex: Fix LATEX_HEADER_EXTRA keyword
* lisp/ox-latex.el (org-latex-make-preamble): Do not include
LATEX_HEADER_EXTRA keywords' contents when previewing a LaTeX
fragment.
Reported-by: Mario RomΓ‘n <mromang08@gmail.com>
<http://lists.gnu.org/archive/html/emacs-orgmode/2017-06/msg00477.html>
```
It was fixed in release 9.1 (I'm not sure when it was introduced). The easiest thing to do is upgrade Org mode. You can get the current stable version from ELPA or check these instructions from the Org mode site.
Or you can apply the following patch:
```
diff --git a/lisp/ox-latex.el b/lisp/ox-latex.el
index f11a8a63a..ec4b49585 100644
--- a/lisp/ox-latex.el
+++ b/lisp/ox-latex.el
@@ -1623,15 +1623,15 @@ non-nil, only includes packages relevant to image generation, as
specified in `org-latex-default-packages-alist' or
`org-latex-packages-alist'."
(let* ((class (plist-get info :latex-class))
- (class-options (plist-get info :latex-class-options))
- (header (nth 1 (assoc class (plist-get info :latex-classes))))
(class-template
(or template
- (and (stringp header)
- (if (not class-options) header
- (replace-regexp-in-string
- "^[ \t]*\\\\documentclass\\(\\(\\[[^]]*\\]\\)?\\)"
- class-options header t nil 1)))
+ (let* ((class-options (plist-get info :latex-class-options))
+ (header (nth 1 (assoc class (plist-get info :latex-classes)))))
+ (and (stringp header)
+ (if (not class-options) header
+ (replace-regexp-in-string
+ "^[ \t]*\\\\documentclass\\(\\(\\[[^]]*\\]\\)?\\)"
+ class-options header t nil 1))))
(user-error "Unknown LaTeX class `%s'" class))))
(org-latex-guess-polyglossia-language
(org-latex-guess-babel-language
@@ -1644,7 +1644,9 @@ specified in `org-latex-default-packages-alist' or
snippet?
(mapconcat #'org-element-normalize-string
(list (plist-get info :latex-header)
- (plist-get info :latex-header-extra)) ""))))
+ (and (not snippet?)
+ (plist-get info :latex-header-extra)))
+ ""))))
info)
info)))
```
> 1 votes
---
Tags: org-mode, latex, latex-header
---
|
thread-58854
|
https://emacs.stackexchange.com/questions/58854
|
Programmatically find-and-replace custom sequence
|
2020-06-02T09:28:56.150
|
# Question
Title: Programmatically find-and-replace custom sequence
I need to write a command which will apply to my buffer custom, predefined copy-and-replace sequence.
What I have is:
```
(defun custom-processor ()
"Formats logs to human-readable format"
((replace-in-the-buffer "\n" "\n\n\n")
(replace-in-the-buffer "\t" "\n")))
(defun replace-in-the-buffer (from to)
"Replaces in the current buffer all occurences of from to to (not interactively)"
(while (re-search-forward from nil t)
(replace-match to nil nil)))
```
It is basically working for simple characters like letters or numbers, but the case is I need to use it with new lines (`\n`) and tabs (`\t`) - the error I get is:
```
Debugger entered--Lisp error: (invalid-function (replace-in-the-buffer "\n" "\n\n\n"))
((replace-in-the-buffer "\n" "\n\n\n") (replace-in-the-buffer "\011" "\n"))
custom-processor()
eval((custom-processor) nil)
elisp--eval-last-sexp(nil)
eval-last-sexp(nil)
funcall-interactively(eval-last-sexp nil)
call-interactively(eval-last-sexp nil nil)
command-execute(eval-last-sexp)
```
I use EMACS for 10y+ but now just starting to leverage it with Lisp programming. Please help.
# Answer
Double parenthesis are the culprit.
I guess you forgot to type `progn`
```
(defun custom-processor ()
"Formats logs to human-readable format"
(progn
(replace-in-the-buffer "\n" "\n\n\n")
(replace-in-the-buffer "\t" "\n")))
```
or just remove them:
```
(defun custom-processor ()
"Formats logs to human-readable format"
(replace-in-the-buffer "\n" "\n\n\n")
(replace-in-the-buffer "\t" "\n"))
```
> 0 votes
---
Tags: regular-expressions, replace
---
|
thread-16750
|
https://emacs.stackexchange.com/questions/16750
|
Better syntax-higlighting for member variables and function calls in cpp-mode
|
2015-09-19T13:53:14.460
|
# Question
Title: Better syntax-higlighting for member variables and function calls in cpp-mode
In atom, C++ files are well colored unlike emacs cpp-mode. Emacs does not highlight references to member variables, function calls or member functions. They all are uncolored.
The left is from emacs and the other is from atom:
See, emacs does not syntax-color for variables and functions apart from their declarations.
Emacs does not utilize a semantic syntax highlighting system, neither does atom. I think such highlighting can be easily added using regexp like in atom.
Atom, for example, looks for parantheses to distinguish function calls from variables. Similarly it looks for a dot to distinguish member variables from the others.
I would like to add these coloring rules to emacs, however, I am just a beginner who does not know regexp and font-lock-mode.
Could you help me with this issue?
# Answer
> 12 votes
The Emacs one is actually better. Here's why, The purpose of syntax highlighting in text editors is not being pretty, but to make important code structures stand out.
If you look at the Emacs sample, you'll see 'MyClass' being colored in the 'type name' color and 'obj' in 'variable' color, which makes the important information that you have one variable 'obj' of type 'MyClass' in the current scope really stand out.
If you happen to have other local variables, member variables or function parameters, you'll see them colored in similar way. I personally think this helps a lot because I can easily see where are these variables declared and where are they instantiated in a glance.
The logic behind Emacs' syntax highlighting is that it doesn't highlight where you reference(use) symbols, instead, it only highlights where symbols are defined or declared. These are much more important and informative then symbols being used. Let's face it, other than declarations and keywords, almost everything else is some symbols being referenced. Coloring these only makes the screen messier and the really important things less obvious.
# Answer
> 6 votes
this seems to answer the member function bit of your question
```
(font-lock-add-keywords 'c++-mode
`((,(concat
"\\<[_a-zA-Z][_a-zA-Z0-9]*\\>" ; Object identifier
"\\s *" ; Optional white space
"\\(?:\\.\\|->\\)" ; Member access
"\\s *" ; Optional white space
"\\<\\([_a-zA-Z][_a-zA-Z0-9]*\\)\\>" ; Member identifier
"\\s *" ; Optional white space
"(") ; Paren for method invocation
1 'font-lock-function-name-face t)))
```
source: https://www.reddit.com/r/emacs/comments/27eqwm/highlighting\_c\_member\_function\_calls/
# Answer
> 1 votes
Adding this to my `init.el` gives fairly good syntax highlighting for function calls and operators, it doesn't handle members though.
This highlights:
* operators `+` `-` ... `=` `*` .. etc.
* brackets `[{()}]` (as delimiters), as well as `;:`
* `function_call()`.
Using simple regex, I find this gives nicer highlighting for C like languages.
```
;; C-Like
(dolist (mode-iter '(c-mode c++-mode glsl-mode java-mode javascript-mode rust-mode))
(font-lock-add-keywords
mode-iter
'(("\\([~^&\|!<>=,.\\+*/%-]\\)" 0 'font-lock-operator-face keep)))
(font-lock-add-keywords
mode-iter
'(("\\([\]\[}{)(:;]\\)" 0 'font-lock-delimit-face keep)))
;; functions
(font-lock-add-keywords
mode-iter
'(("\\([_a-zA-Z][_a-zA-Z0-9]*\\)\s*(" 1 'font-lock-function-name-face keep))))
```
---
Tags: syntax-highlighting, c++, c
---
|
thread-58852
|
https://emacs.stackexchange.com/questions/58852
|
Update Org Header if SRC Block has :tangle no
|
2020-06-02T03:52:40.380
|
# Question
Title: Update Org Header if SRC Block has :tangle no
I organize my `init.el` in a single org-file as many do. Often times I remove code from my config to test things out. I typically do this by changing the src-block to have a `:tangle no` setting. In many cases, I forget about it and eventually realize large portions of my config are not tangled.
I'm not quite sure if I need to craft some type of watcher or hook function.
```
* This is a heading
#+BEGIN_SRC emacs-lisp
...
#+END_SRC
would become
* TODO This is a heading
#+BEGIN_SRC emacs-lisp :tangle no
...
#+END_SRC
```
I was thinking about adding something like this to an on-save hook and then modifying the code blocks section header if :tangle no.
```
(org-element-map (org-element-parse-buffer) 'src-block #'identity nil nil 'src-block)
```
But it takes a really long time just to run this function.
# Answer
> 1 votes
On my computer, sections with todo keyword `COMMENT` are not tangled. That is, change your `TODO` example to `* COMMENT This is a heading`. It is also fairly easy to toggle the `COMMENT` keyword, with `C-;` keystroke anywhere on or within a heading.
---
Tags: org-mode, todo
---
|
thread-58861
|
https://emacs.stackexchange.com/questions/58861
|
Using org-ref to download pdfs using sci-hub as a fallback
|
2020-06-02T14:14:33.440
|
# Question
Title: Using org-ref to download pdfs using sci-hub as a fallback
I've developed a solution that allows to download pdfs from sci-hub as a fallback option to the functions provided by org-ref. I am a newbie to elisp, so please feel free to update this answer as necessary.
# Answer
**Disclaimer** Use it at your own risk.
You have to add one new function and update another. Both can be declared in your init.el file as follows
1- The `sci-hub-pdf-url` function is
```
;; Sci-hub
(defun sci-hub-pdf-url (doi)
"Get url to the pdf from SCI-HUB"
(setq *doi-utils-pdf-url* (concat "https://sci-hub.se/" doi) ;captcha
*doi-utils-waiting* t
)
;; try to find PDF url (if it exists)
(url-retrieve (concat "https://sci-hub.se/" doi)
(lambda (status)
(goto-char (point-min))
(while (search-forward-regexp "\\(https://\\|//sci-hub.se/downloads\\).+download=true'" nil t)
(let ((foundurl (match-string 0)))
(message foundurl)
(if (string-match "https:" foundurl)
(setq *doi-utils-pdf-url* foundurl)
(setq *doi-utils-pdf-url* (concat "https:" foundurl))))
(setq *doi-utils-waiting* nil))))
(while *doi-utils-waiting* (sleep-for 0.1))
*doi-utils-pdf-url*)
```
2- And update the `doi-utils-get-bibtex-entry-pdf` function by
```
(defun doi-utils-get-bibtex-entry-pdf (&optional arg)
"Download pdf for entry at point if the pdf does not already exist locally.
The entry must have a doi. The pdf will be saved to
`org-ref-pdf-directory', by the name %s.pdf where %s is the
bibtex label. Files will not be overwritten. The pdf will be
checked to make sure it is a pdf, and not some html failure
page. You must have permission to access the pdf. We open the pdf
at the end if `doi-utils-open-pdf-after-download' is non-nil.
With one prefix ARG, directly get the pdf from a file (through
`read-file-name') instead of looking up a DOI. With a double
prefix ARG, directly get the pdf from an open buffer (through
`read-buffer-to-switch') instead. These two alternative methods
work even if the entry has no DOI, and the pdf file is not
checked."
(interactive "P")
(save-excursion
(bibtex-beginning-of-entry)
(let ( ;; get doi, removing http://dx.doi.org/ if it is there.
(doi (replace-regexp-in-string
"https?://\\(dx.\\)?.doi.org/" ""
(bibtex-autokey-get-field "doi")))
(key (cdr (assoc "=key=" (bibtex-parse-entry))))
(pdf-url)
(pdf-file))
(setq pdf-file (concat
(if org-ref-pdf-directory
(file-name-as-directory org-ref-pdf-directory)
(read-directory-name "PDF directory: " "."))
key ".pdf"))
;; now get file if needed.
(unless (file-exists-p pdf-file)
(cond
((and (not arg)
doi
(if (doi-utils-get-pdf-url doi)
(setq pdf-url (doi-utils-get-pdf-url doi))
(setq pdf-url "https://www.sciencedirect.com/science/article/")))
(url-copy-file pdf-url pdf-file)
;; now check if we got a pdf
(if (org-ref-pdf-p pdf-file)
(message "%s saved" pdf-file)
(delete-file pdf-file)
;; sci-hub fallback option
(setq pdf-url (sci-hub-pdf-url doi))
(url-copy-file pdf-url pdf-file)
;; now check if we got a pdf
(if (org-ref-pdf-p pdf-file)
(message "%s saved" pdf-file)
(delete-file pdf-file)
(message "No pdf was downloaded.") ; SH captcha
(browse-url pdf-url))))
;; End of sci-hub fallback option
((equal arg '(4))
(copy-file (expand-file-name (read-file-name "Pdf file: " nil nil t))
pdf-file))
((equal arg '(16))
(with-current-buffer (read-buffer-to-switch "Pdf buffer: ")
(write-file pdf-file)))
(t
(message "We don't have a recipe for this journal.")))
(when (and doi-utils-open-pdf-after-download (file-exists-p pdf-file))
(org-open-file pdf-file))))))
```
3- Enjoy! If you have set up the `org-ref-pdf-directory` the command `crossref-add-bibtex-entry` or `doi-utils-add-bibtex-entry-from-doi` should download the pdf automatically to the specified directory. If not, it will open sci-hub in your browser (this usually happens when you have to enter a captcha). Good luck.
> 2 votes
---
Tags: pdf, org-ref
---
|
thread-58868
|
https://emacs.stackexchange.com/questions/58868
|
How to make emacs recognize a bash script that ends in .sh?
|
2020-06-02T17:24:55.990
|
# Question
Title: How to make emacs recognize a bash script that ends in .sh?
I'm trying to get Emacs to understand that my script is bash.
I tried adding `-*- bash -*-` to the first line of the file, but it still opens in `Shell-script[sh]` mode. I can rename the file to give it a bash extension (currently it's `.sh`) but this might break some existing code.
Is there some way to give Emacs this hint?
# Answer
> 2 votes
`C-h m` should tell you:
```
[...]
shell-specific features. Shell script files can use the `sh-shell' local
variable to indicate the shell variant to be used for the file.
[...]
```
so adding `-*- sh-shell: bash -*-` on the first line should do the trick.
---
Tags: bash
---
|
thread-58863
|
https://emacs.stackexchange.com/questions/58863
|
How to find information about a function?
|
2020-06-02T14:24:07.907
|
# Question
Title: How to find information about a function?
To be able to learn about functions on my own I would like to know where I can find information about them (within emacs or otherwise).
# Answer
> 1 votes
In addition to `C-h f` which gives you information about functions as you found out, the `C-h` prefix key leads to all sorts of other documentation as well: variables, keys, log messages, modes, the Info manuals and much more - type `C-h ?` to get the list.
# Answer
> 0 votes
`C-h f` lets you find information about functions. It will prompt you for the name of the function which you want to read about. Upon entering a valid function name, it will open the documentation in a split window.
# Answer
> 0 votes
C-h f (describe-function ) displays the complete documentation for and allows you to access the elisp source code. You can activate the step-by-step execution mode of this function by C-u C-M -x - see (info "'(elisp) Using Edebug") - and thus examine its dynamic operation. This is a very good way to understand how the elisp code for this function works.
---
Tags: functions, help
---
|
thread-58872
|
https://emacs.stackexchange.com/questions/58872
|
How do octave functions work in org-mode code blocks?
|
2020-06-02T22:21:21.733
|
# Question
Title: How do octave functions work in org-mode code blocks?
I tried to define and use a simple matlab/octave function within an org-mode code block as shown follows.
```
#+name: test-octave-function
#+begin_src octave
function s = my_sum(x, y)
s = x + y;
end
my_sum(1, 2)
#+end_src
```
The code works if put inside a `.m` file. However, in a code-block, it generates this error in Org-babel output:
> warning: function name 'my\_sum' does not agree with function filename ''
>
> error: 'my\_sum' undefined near line 1 column 1
I understand functions defined for use in other files need to have the same name as the .m file. But how do filenames work for a code block. Also, I called the function `my_sum` in the same code block, why is it undefined?
*Related to this, how can I define and use multiple functions in a code block?*
(This is with the stock Emacs 26 of Ubuntu 20.04)
# Answer
I get the same result as you do and I'm not sure how it is supposed to work (I suspect bugs but I have not investigated).
However, it does work better in a session:
```
#+name: test-octave-function
#+begin_src octave :session foo
function retval = mysum(x, y)
retval = x + y;
end
ans = mysum(5, 12)
#+end_src
#+RESULTS: test-octave-function
: 17
```
> 2 votes
---
Tags: org-mode, octave
---
|
thread-58757
|
https://emacs.stackexchange.com/questions/58757
|
Sum clock times by tag
|
2020-05-27T17:24:28.483
|
# Question
Title: Sum clock times by tag
I would like to sum clock intervals from tasks by tag. I found this blog post (code below). When I use it, I get the same report, regardless of the tag I request:
```
Time: 4499:28 (4499 hours and 28 minutes)
```
Furthermore, I get this warning after evaluating the code:
```
βorg-reβ is an obsolete macro (as of Org 9.0); you can safely remove it.
```
The post is from 2008 and therefore I assume that the code is incompatible with my version.
How can I sum clocked intervals for a specific tag?
**Appendix**: here is the obsolete code:
```
(defun wicked/org-calculate-tag-time (matcher &optional ts te)
"Return the total minutes clocked in headlines matching MATCHER.
MATCHER is a string or a Lisp form to be evaluated, testing if a
given set of tags qualifies a headline for inclusion. TS and TE
are time start (inclusive) and time end (exclusive). Call with a
prefix to be prompted for TS and TE.
For example, to see how much time you spent on tasks tagged as
URGENT, call M-x wicked/org-calculate-tag-time RET URGENT RET. To
see how much time you spent on tasks tagged as URGENT today, call
C-u M-x wicked/org-calculate-tag-time RET URGENT RET . RET +1 RET."
(interactive (list
(read-string "Tag query: ")
(if current-prefix-arg (org-read-date))
(if current-prefix-arg (org-read-date))))
;; Convert strings to proper arguments
(if (stringp matcher) (setq matcher (cdr (org-make-tags-matcher matcher))))
(if (stringp ts)
(setq ts (time-to-seconds (apply 'encode-time (org-parse-time-string ts)))))
(if (stringp te)
(setq te (time-to-seconds (apply 'encode-time (org-parse-time-string te)))))
(let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
(mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
(org-re
"\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:][email protected]:]+:\\)?[ \t]*$")))
(case-fold-search nil)
lspos
tags tags-list tags-alist (llast 0) rtn level category i txt p
marker entry priority (total 0))
(save-excursion
(org-clock-sum ts te)
(goto-char (point-min))
(while (re-search-forward re nil t)
(catch :skip
(setq tags (if (match-end 4) (match-string 4)))
(goto-char (setq lspos (1+ (match-beginning 0))))
(setq level (org-reduced-level (funcall outline-level))
category (org-get-category))
(setq i llast llast level)
;; remove tag lists from same and sublevels
(while (>= i level)
(when (setq entry (assoc i tags-alist))
(setq tags-alist (delete entry tags-alist)))
(setq i (1- i)))
;; add the nex tags
(when tags
(setq tags (mapcar 'downcase (org-split-string tags ":"))
tags-alist
(cons (cons level tags) tags-alist)))
;; compile tags for current headline
(setq tags-list
(if org-use-tag-inheritance
(apply 'append (mapcar 'cdr tags-alist))
tags))
(when (and (eval matcher)
(or (not org-agenda-skip-archived-trees)
(not (member org-archive-tag tags-list))))
;; Get the time for the headline at point
(goto-char (line-beginning-position))
(setq total (+ total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)))
;; if we are to skip sublevels, jump to end of subtree
(org-end-of-subtree t)))))
(if (interactive-p)
(let* ((h (/ total 60))
(m (- total (* 60 h))))
(message "Time: %d:%02d (%d hours and %d minutes)" h m h m)))
total))
```
# Answer
Following the link @Muihlinn's comment, one solution consists of a clock report:
```
#+BEGIN: clocktable :maxlevel 2 :scope file :tags "nicetag"
...
#+END:
```
I can't mark this question as a duplicate since the other solution is on a different forum.
> 0 votes
---
Tags: org-mode, org-clock
---
|
thread-58798
|
https://emacs.stackexchange.com/questions/58798
|
How to disable specific flycheck-warning messages in LaTeX-mode?
|
2020-05-29T18:47:23.900
|
# Question
Title: How to disable specific flycheck-warning messages in LaTeX-mode?
Currenty I am on LaTeX-mode-hook using `flycheck`.
```
(setq LaTeX-item-indent 0)
(add-hook 'LaTeX-mode-hook 'turn-on-auto-fill)
(add-hook 'LaTeX-mode-hook 'hl-todo-mode)
(require 'tex)
(add-hook 'LaTeX-mode-hook (lambda ()
(TeX-global-PDF-mode t)
))
(setq flyspell-issue-message-flag nil
ispell-local-dictionary "en_US"
ispell-program-name "aspell"
ispell-extra-args '("--sug-mode=ultra"))
(dolist (hook '(text-mode-hook))
(add-hook hook (lambda () (flyspell-mode 1))))
(dolist (hook '(change-log-mode-hook log-edit-mode-hook))
(add-hook hook (lambda () (flyspell-mode -1))))
```
---
For example I am getting following `flycheck-warning` message when I write `function()` into my `.tex` file:
`You should put a space in front of parenthesis. [36]`
**\[Q\]** Is there any way to ignore specific `flycheck-warning` messages?
# Answer
> 2 votes
You don't disable warning messages at the `flycheck` level; you disable them using the underlying checker, which in your case for `latex-mode` is `chktex`. One can find the underlying checker by running `M-x flycheck-describe-checker RET`.
The `chktex` manual explains how to do per line suppression by adding a case-insensitive comment to the end your line `% chktex ##` where `##` is the error number. In your case you would add `% chktex 36`.
---
Tags: latex, flycheck
---
|
thread-58886
|
https://emacs.stackexchange.com/questions/58886
|
How to disable changing the current buffer by clicking buffer name in mode line?
|
2020-06-03T13:22:48.273
|
# Question
Title: How to disable changing the current buffer by clicking buffer name in mode line?
I find myself accidentally clicking the mode line when trying to focus a buffer with the mouse. This causes the buffer to change. I don't want that behavior. I want nothing to happen.
The culprit is this guy here, the part of the mode line that says the buffer's name (e.g. `*shell*`):
How can I disable it's behavior when it clicked?
I am told it is `<down-mouse-1>` by `C-h k`. However, this corresponds to `mouse-drag-mode-line` which resizes. This is not the behavior I observe. I cannot locate the appropriate key to override.
# Answer
> 5 votes
Try using:
```
(define-key mode-line-buffer-identification-keymap [mode-line mouse-1] nil)
(define-key mode-line-buffer-identification-keymap [mode-line mouse-3] nil)
```
---
The variable `mode-line-buffer-identification-keymap` is defined within `bindings.el`.
---
Tags: buffers, mode-line, mouse
---
|
thread-58881
|
https://emacs.stackexchange.com/questions/58881
|
org-mode un-bold exported headlines
|
2020-06-03T10:45:05.563
|
# Question
Title: org-mode un-bold exported headlines
I use org-mode to translate, with source text lines on level 2 headlines and target text lines on level 3 headlines.
However, the text of any headline that is exported is bold and italicised. I can go through the exported document and manually remove this formatting but I was wondering if there was a way to remove this formatting in export? I can see org-export-filter-bold-functions, but no matter how I try to use it I can't make it un-bold etc. the exported text.
Do any of you fine souls know how to go about achieving this? I'm totally stuck!
# Answer
> 1 votes
You can remove the leading stars. This will prevent the exporter from formatting your headlines as headlines if that makes sense. In your case the easiest way of doing this is with the following advice:
```
(advice-add 'export-translation :after
(lambda (backend)
(org-map-entries
(lambda ()
(when (looking-at org-outline-regexp)
(replace-match "\n"))))))
```
# Answer
> 1 votes
There is a slightly more detailed description of what you are doing in your other question \- I provide the link here just to clarify to potential answerers what you are trying to do.
Both of your questions basically ask: how can I force Org mode to do what I want? In the first one, you want to export part of the document: Org mode has facilities to export parts of the document, but the parts that you want to export and the parts that Org mode wants to export (e.g. a subtree) do not agree. In this question, you want to export headlines without making them appear as headlines: but they are called "headlines" for a reason and Org mode exports them to *look* like headlines.
What I am trying to say is that you are trying to force Org mode to do things against its nature, by mapping what you want onto its structures without regard for what *it* wants to do. The comments in your other question hint at this: you are probably not using the "right" Org mode structures to map *your* structures onto, and the fact that you have to fight Org mode to make it do what you want is an indication of that. You can probably make it do what you want, but you'll be fighting it all the way: it would be better if you rethought your approach to make the mapping more natural.
It may also be that Org mode is just not the right fit for your problem: it solves a lot of problems but it cannot solve every problem thrown at it. You might want to take a step back and ask yourself if you should use Org mode for this problem, or if maybe another tool is more suited for the job. Or you might ask if there is a better mapping to Org mode structures to do what you want.
In the latter case, I would suggest you post a different question here: describe what you want to do and ask whether Org mode (or something else) provides the structure(s) to help do what you want.
E.g. you say you use one kind of headline for the source text and a different kind of headline for the translation, but you don't say why you want to do that. Are you doing this e.g. because you want to exercise your skills in a foreign language (using the text as flashcards)? Or because you are translating a book and you want to store common phrases so that you translate them the same way each time? Or some other reason?
I realize that this does not provide an answer to your immediate question, but I hope it helps you think about the underlying problem.
EDIT (in response to the OP's comment): There are many ways to use a tool (and Org mode in particular is a multi-tool which makes things worse - or better, depending on your point of view). What I was suggesting is that if you described what you are trying to do (at a high level, not how you are doing it in the current implementation), somebody might come up with a better mapping (to Org mode or to a different tool). This might be a discussion that's not well suited for the Emacs SE format though: you might want to post the more general question on the Org mode mailing list which is better suited to exploratory, open-ended discussion.
---
Tags: org-export, formatting
---
|
thread-58324
|
https://emacs.stackexchange.com/questions/58324
|
Multiline mode-line using dynamic generated text images
|
2020-05-06T20:01:22.843
|
# Question
Title: Multiline mode-line using dynamic generated text images
I've been doing experiments at displaying static text images in the mode-line using Imagemagick to generate the image (see below). I would like now to generate such an image in a dynamic way, providing information from within Emacs. For example, I could display the current major mode or the cursor line/column (might be slow).
My question is how to dynamically generate the image according to the provided information (e.g. how to call and pass arguments to Imagemagick). Displaying line/column using image Imagemagick might very slow but still, I would like to try.
Imagemagick command used for the screenshot:
```
convert -antialias -background none -fill white -family Roboto -weight regular -gravity southeast -size 64x42 -pointsize 20 label:"Emacs\nv26.3" label.png
```
And in the modeline (header line in my case):
```
(propertize " " 'display (create-image "~/label.png" 'png nil :ascent 90 ))
```
# Answer
> 3 votes
I've found a solution using SVG.
---
Tags: mode-line, images
---
|
thread-58866
|
https://emacs.stackexchange.com/questions/58866
|
Completion of sentences stored in a file
|
2020-06-02T16:48:29.440
|
# Question
Title: Completion of sentences stored in a file
I know this question is similar to completion of a sentence rather than word but I ask anyway since I suggest another way of storing what is supposed to be auto-completed.
Suppose I stored some sentences in a file. How could I, in the current buffer, complete the sentences from this file just by typing the beginning (or, better, any part) of them?
**Edit:** To be more explicit, here is the context: I'm in the process of grading (maths) exams and most of the positive and negative remarks I have to express (and to write down) about my students works are the sames.
Hence, suppose I have the following sentences in a `sentences.txt` file:
```
Please, don't take your dreams for reality: (a + b)Β² β aΒ² + bΒ².
Please, don't take your dreams for reality: cos(a + b) β cos a + cos b.
You should revise the derivatives.
No, β(aΒ²) β a.
This only works for a positive x.
```
I'd like to be able in my current buffer (of a file stored, say, in the same directory as `sentences.txt`) to type e.g.
> Please
and to be prompted with the first two sentences in a drop down list, just as does `autocomplete` for the (single) words of the current buffer.
# Answer
> 1 votes
Since you don't need actual `abbrev`iations, just call `completing-read` with your list of sentences. This will let you define the list of sentences however you want. Here's the simplest possible implementation:
```
(defun db48x/insert-canned-response ()
(interactive)
(let ((lines (with-temp-buffer
(insert-file-contents "~/temp/sentences.txt")
(split-string (buffer-string) "\n" t))))
(insert (ido-completing-read "Response: " lines))))
(global-set-key (kbd "C-c k") 'db48x/insert-canned-response)
```
I actually used `ido-completing-read` because it's fancier than the default `completing-read`; it shows you a preview of what you're about to select, and it lets you narrow the choices by substring match rather than just by prefix match. For example, this will let you type 'cos' to select the second response from your examples, which has the same prefix as the first response.
This implementation has obvious deficiencies, but they probably don't matter in practice. If your list of responses gets large enough or your hard drive is slow enough that it becomes a problem, you can ask a new question about it.
---
Tags: completion, abbrev, sentences
---
|
thread-58893
|
https://emacs.stackexchange.com/questions/58893
|
Is it possible to organize the capture templates selection screen?
|
2020-06-04T05:04:28.953
|
# Question
Title: Is it possible to organize the capture templates selection screen?
As it can be seen above, I have around fifteen capture templates. I think this list may grow or shrink, but in the case that it grows, is there any way to make it more segmented?
Like dividing it across some categories, just for visual organization. Something like:
Notes
* books
* web pages
* miscellaneous
* articles
* uni notes
Media
* movie
* game
* book
Actions
* goals
* tasks
* weekly review
Writing
* new post
* thesis
* journaling
Or even dividing it horizontally instead of vertically. And so forth and so on.
Yes, this degree of organization could be reached through diminishing the number of capture templates and further customizing them to make them more specific, but then I would have to stack them in the same file. And since I use Emacs mostly for writing, my org files tend to get huge very quickly and I like to spread them out to avoid making things a mess.
Is this setup somehow feasible?
# Answer
There are a couple of options for this, to me the easiest way is grouping templates using the built-in mechanism.
My way to use capture templates is based in memory muscle rather than digging a long menu, so how the menu is displayed should be concise in case I don't recall what key was for something. I do call capture using `F12`, then if I want to insert a note I'll use `n` and, let's say `b` if it's about a book.
So, to achieve this if you look for `org-capture-templates` documentation:
> <pre><code>keys The keys that will select the template, as a string, characters
> only, for example "a" for a template to be selected with a
> single key, or "bt" for selection with two keys. When using
> several keys, keys using the same prefix key must be together
> in the list and preceded by a 2-element entry explaining the
> prefix key, for example
>
> ("b" "Templates for marking stuff to buy") ```
> </code></pre>
meaning that you can use `n` to group notes as heading and using two chars keys `nb`, `nm`, `nw`, `na` for books, miscellanea, work and articles - *you should also follow the other conditions*.
So something like this in your template definition:
```
("n" "Notes")
("nb" "Notes about books" <your template definition here>)
("nm" "Misc notes" <your template definition here>)
("nw" "Work notes" <your template definition here>)
("na" "Notes about articles" <your template definition here>)
```
Will give you a `n` submenu which unfolds in a new menu once pressed. Calling capture templates will look like this:
```
... <other capture templates>
[b] Books to read
[n]... Notes
... <other capture templates>
```
and pressing `n` will lead to:
```
n [b] Notes about books
n [m] Misc notes
n [w] Work notes
n [a] Notes about articles
```
Please note, these templates could be organized as nested as you need them:
```
("n" "Notes")
("nw" "Work-related notes")
("np" "Personal notes")
("nwb" "Work-related notes about books" <your template definition here>)
("nwa" "Work-related notes about articles" <your template definition here>)
("npb" "Personal notes about books" <your template definition here>)
("npa" "Personal notes about articles" <your template definition here>)
```
You can do it in your init file or using `customize` interface. Of course, there is more about this in the documentation.
> 9 votes
---
Tags: org-mode, customize, org-capture, writing, template
---
|
thread-35392
|
https://emacs.stackexchange.com/questions/35392
|
Result of arithmetic evaluation in buffer, not echo area
|
2017-09-09T12:00:02.803
|
# Question
Title: Result of arithmetic evaluation in buffer, not echo area
Windows 10, Emacs 25.1
I want to do some arithmetic operation I do this:
The result is in the echo area, but I want the result to be in cursor place in the buffer. Something like this:
How do I do this?
# Answer
### Short version: yes
Instead of `C-x C-e` to evaluate the expression, give it a prefix argument. `C-u C-x C-e` will print the output to the buffer.
### How I found this information
You can investigate how Emacs does these things by looking in the manual, or asking Emacs itself.
To see what a particular keybinding does, you can use `C-h k` (`describe-key`). You were evaluating the expression with `C-x
C-e`, and you can figure out what that keybinding calls with `C-h
k C-x C-e`. That will display the command's docstring, the first part of which is:
> `C-x C-e` runs the command `eval-last-sexp` (found in global-map), which is an interactive compiled Lisp function in `elisp-mode.el`.
>
> It is bound to `C-x C-e`.
>
> `(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)`
>
> Evaluate sexp before point; print value in the echo area. **Interactively, with a non `-` prefix argument, print output into current buffer.**
>
> ...
I highlighted the key phrase: giving it a prefix argument (`C-u`) will print the output to the buffer, rather than the echo area.
> 24 votes
# Answer
Bind this to some key.
```
(defun foo ()
"Replace sexp before point by result of its evaluation."
(interactive)
(let ((result (pp-to-string (eval (pp-last-sexp) lexical-binding))))
(delete-region (save-excursion (backward-sexp) (point)) (point))
(insert result)))
```
> 9 votes
# Answer
If you want to do an arithmetic operation and insert the value into the buffer, but don't care where you do the operation, then you can also do `C-u M-:` and type the operation info the minibuffer.
This blog has
```
(defun eval-and-replace (value)
"Evaluate the sexp at point and replace it with its value"
(interactive (list (eval-last-sexp nil)))
(kill-sexp -1)
(insert (format "%S" value)))
```
> 5 votes
# Answer
I prefer to do (also complex) computations in Emacs' calc `C-x * *` and then copy its result in the buffer where my cursor was with `y`, `q` closes the calc buffers and I'm back at this location.
> 2 votes
# Answer
I had the same wish and hadn't used Emacs in a long while and forgot how to do it :) Very simple and touched on by some above answers with the prefix command `C-u`
Simply `C-u M-:` (Eval buffer appears for your function) such as `Eval: (- 5 2)` and the result of `3` will appear in your buffer cursor location
This is very handy for kbd-macros where you need to manipulate some arithmetic and replace values
> 0 votes
---
Tags: insert, eval-expression
---
|
thread-58899
|
https://emacs.stackexchange.com/questions/58899
|
Non regex variant of dired-do-find-regexp-and-replace
|
2020-06-04T10:41:40.883
|
# Question
Title: Non regex variant of dired-do-find-regexp-and-replace
Dired has the interactive function `dired-do-find-regexp-and-replace` which can be match based on the regexp you have passed and perform the replace.
But I'm looking for non regex variant of `dired-do-find-regexp-and-replace` where I don't have to pass the regexp. Is something like that available for dired ? I'm okay with using additional dired based packages for it, if they provide the non-regexp version of the function.
# Answer
Use `dired-do-find-regexp-and-replace` but making use of `regexp-quote` to match only the literal string of its argument. This way you'll use the quoted regexp only as search string, without touching the original.
```
(dired-do-find-regexp-and-replace (regexp-quote from) to)
```
> 2 votes
---
Tags: dired
---
|
thread-58890
|
https://emacs.stackexchange.com/questions/58890
|
Create Smart Multi-level Headings with Proper Indentation
|
2020-06-03T20:23:17.747
|
# Question
Title: Create Smart Multi-level Headings with Proper Indentation
When working with phone calls and tickets, I use Emacs in Org mode to pre-create the entry with the heading containing the current date and time. For obvious reasons, if not constantly using a new file (which would make history searches more difficult), I end up with a very long flat list of call headings and their respective contents.
I now want to change that, so that I get a top-level header with the year, a second-level header with the month and then a third-level header with the actual call entry.
In my trials, I manage to get the results when using the first entry inside the call file, but as soon as I get the second (third, fourth), the indentation is getting deeper with each entry. I also experimented with "post-editing" the automation (e.g. `(org-insert-subheading t) (beginning-of-line) (delete-char 1) (end-of-line)`), but I find that very messy to the point that items like `(org-insert-heading)` would have no meaning anymore.
The result shall look somewhat like this:
```
* <2019>
** <12>
*** call <date&time_of_call>
*** call <date&time_of_call>
* <2020>
** <01>
*** call <date&time_of_call>
*** call <date&time_of_call>
** <02>
*** call <date&time_of_call>
*** call <date&time_of_call>
...
```
My code so far looks like this (I call `eltest` with a key shortcut):
```
(defvar sFilePath "~/Documents/Emacs/"
"Path to directory.")
(defvar sTestEntryYear "<%Y>"
"Year format string for entry headings.")
(defvar sTestEntryMonth "<%m>"
"Month format string for entry headings.")
(defvar sTestEntry "<%a, %Y-%m-%d %H:%M:%S>"
"Date & time format string for entry headings.")
(defun insert_test_template ()
"Insert the test template"
(interactive)
((lambda ()
(org-insert-subheading t)
(insert (concat "Calls " sNow " Call|WalkUp: ProblemDescription\n\n"))
(insert "template goes on here\n")
(insert "RESULT\n")
(insert "-> "))))
(defun eltest ()
"Add a new call entry."
(interactive)
(switch-to-buffer (find-file (concat sFilePath "Test.org")))
(widen)
(let ((sThisYear (format-time-string sTestEntryYear)) (sThisMonth (format-time-string sTestEntryMonth)) (sNow (format-time-string sTestEntry)))
(end-of-buffer)
(unless (org-goto-local-search-headings sThisYear nil t)
((lambda ()
(org-insert-heading nil nil t)
(insert (concat sThisYear "\n")))))
(end-of-buffer)
(unless (org-goto-local-search-headings sThisMonth nil t)
((lambda ()
(org-insert-subheading t)
(insert (concat sThisMonth "\n")))))
(end-of-buffer)
(unless (org-goto-local-search-headings sNow nil t)
((lambda ()
(insert_test_template))))
(while (progn
(previous-line 1)
(not (looking-at "^- Name : $"))))
(org-show-entry)
(end-of-line)))
```
# Answer
> 2 votes
What you're asking for looks like Org Capture Templates.
```
(define-key global-map "\C-cc" 'org-capture)
(setq org-capture-templates
'(("c" "Calls arranged in a date tree" entry
(file+datetree "~/calls.org" "Calls and Meetings")
"* %^{type|Call|WalkUp|Meeting}: %^{problem} %T
+ %?
+ RESULT
+ "
:clock-in t :clock-resume t)))
```
To use the template with the given key binding, you hit `C-c c c` as soon as you get a call or a walk-up. The template prompts you for the type, then lets you enter a problem description. You are placed into a capture buffer with the text insert point at the location of the `%?` in the template - in this case I made it a list that you can add lines to with `M-RET`.
To file the event from the capture buffer, you hit `C-c C-c`, or `C-c C-k` to abort.
The result is very similar to what you asked for:
```
* Calls and Meetings
** 2020
*** 2020-06 June
**** 2020-06-04 Thursday
***** DONE Call: Stuff got broken <2020-06-04 Thu 09:08>
:LOGBOOK:
- State "DONE" from "STARTED" [2020-06-04 Thu 09:08]
- State "STARTED" from [2020-06-04 Thu 09:01]
CLOCK: [2020-06-04 Thu 09:01]--[2020-06-04 Thu 09:08] => 0:07
:END:
+ I resolved the issue by fixing the widget.
+ RESULT
+ FIXED!
```
The template additionally starts a clock which gives you time tracking, but you can eliminate that if you'd like.
Refs:
---
Tags: org-mode
---
|
thread-58901
|
https://emacs.stackexchange.com/questions/58901
|
How to output an octave array as a org-mode table?
|
2020-06-04T13:14:33.720
|
# Question
Title: How to output an octave array as a org-mode table?
I am trying to output a matlab/octave array as an org-mode table. So for an array/matrix like
```
a =[ 1 2; 3 4; 5 6];
```
I'd like to have a 3 by 2 org-mode table. I tried to just echo the array `a` as if in matlab, but it does not work. I am wondering how to make the output work.
More specifically, for an input array:
```
#+name: test-data
#+begin_src octave :session test_case :exports both
a =[ 1 2; 3 4; 5 6];
#+end_src
#+RESULTS: test-data
: org_babel_eoe
```
I can generate its `size` as a table:
```
#+NAME: test-output-size
#+BEGIN_SRC octave :session test_case :results value :colnames yes :hline yes
size(a)
#+END_SRC
#+RESULTS: test-output-size
| 3 | 2 |
```
But when I tried to print the array `a` itself as a table, I got no output:
```
#+NAME: test-output-value
#+BEGIN_SRC octave :session test_case :results value :colnames yes :hline yes
a
#+END_SRC
#+RESULTS: test-output-value
: org_babel_eoe
```
I also tried `disp()`, to no avail. So my question is:
*What is the proper way to output an array as a table?*
(This is with the Emacs 26 in Ubuntu 20.04 LTS)
# Answer
> 2 votes
Octave is peculiar (or maybe `ob-octave` is peculiar). In particular, the name `ans` seems to have special meaning. Try this:
```
#+name: test-data
#+begin_src octave :session test_case :exports both
a =[ 1 2; 3 4; 5 6];
ans = a
#+end_src
#+RESULTS: test-data
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
```
# Answer
> 1 votes
You can ask for the results to be the output (the default is `value`) and then use the `disp` option you already tried; place this
`:results output`
on the `begin_src` line.
---
Tags: org-mode, octave
---
|
thread-58909
|
https://emacs.stackexchange.com/questions/58909
|
How to export an octave/matlab array for use by python in org-mode?
|
2020-06-04T16:20:24.630
|
# Question
Title: How to export an octave/matlab array for use by python in org-mode?
I am trying to pass the value of an octave/matlab array into a python code block in org-mode. But I can't get the python-end to receive the value.
With the answers in this question, I can generate an org-mode table from a matlab array `a` as follows:
```
#+name: test-data
#+begin_src octave :session test_case :exports both
a =[ 1 2; 3 4; 5 6];
#+end_src
#+RESULTS: test-data
: org_babel_eoe
#+NAME: test-output-value
#+BEGIN_SRC octave :session test_case :results value :colnames yes :hline yes
ans = a
#+END_SRC
#+RESULTS: test-output-value
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
```
However, when I try to pass the results of the matlab-generated table to python, I get no output from python:
```
#+NAME: octave-to-python
#+BEGIN_SRC python :var a=test-output-value :results value :exports none
len(a)
#+END_SRC
#+RESULTS: octave-to-python
: None
```
Can anyone help explain how to make the chaining above work?
(This is with default Emacs 26, Python 3.8 of Ubuntu 20.04 LTS).
# Answer
`ob-python` is also peculiar. Try this:
```
#+name: test-data
#+begin_src octave :session test_case :results value
a =[ 1 2; 3 4; 5 6];
ans = a
#+END_SRC
#+RESULTS: test-data
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
#+NAME: octave-to-python
#+BEGIN_SRC python :var x=test-data :results value
return len(x)
#+END_SRC
#+RESULTS: octave-to-python
3
```
`ob-python`'s peculiarity is the different way it treats `:results value` blocks and `:results output` blocks: when you specify `:results value` (which you also get by default if you *don't* specify anything), then `ob-python` wraps the source block code in a function, calls the function, gets the result and fills in the `#+RESULTS` block. That's why you need to have a `return` in the source block: without it, nothing is returned (actually what is returned is the `None` object, so that's what you get).
The trouble is that if you decide that you want `:results output` instead, `ob-python` decides that in this case, it is *not* going to wrap the code in a function and if you try to execute it, you get a syntax error: `SyntaxError: 'return' outside function`. So the *same* code block gives *different* results, depending on whether you have specified `:results value` or `:results output` \- that in itself is perhaps not surprising, since there is no reason that that a result value should be the same as what is printed out, but depending on the code, in one case you get what you expect and in the other case you get a syntax error, because `ob-python` treats those two cases very differently. E.g.:
```
#+begin_src python :var a=3 :var b=4
sum = a + b
print("The sum is:", sum)
return sum
#+end_src
#+RESULTS:
: 7
#+begin_src python :var a=3 :var b=4 :results output
sum = a + b
print("The sum is:", sum)
return sum
#+end_src
#+RESULTS:
```
In the first case (`:results value`), the output of the `print` disappears, and the value is `7`, so that's what the `#+RESULS:` block shows. In the second case, the same code block but with `:results output` specified, gives a syntax error: you have to get rid of the `return sum` line in order for it to run without error, in which case the result is the output of the `print`: `The sum is 7`.
There are technical reasons for this inconsistency, but it *is* an inconsistency and it *is* surprising when you first encounter it.
> 0 votes
---
Tags: org-mode, python, octave
---
|
thread-58907
|
https://emacs.stackexchange.com/questions/58907
|
Get server name from a client
|
2020-06-04T15:35:44.597
|
# Question
Title: Get server name from a client
I have a few Emacs servers running on my computer, and a few clients are attached to these servers. Is there a way to get which server a client is attached to from the window?
# Answer
At a pinch, `(emacs-pid)` will give you the server's process ID.
In *typical* cases, `C-h``v` `server-name` is probably going to tell you what you need to know.
For example if you are simply using `emacs --daemon=NAME` and connecting with `emacsclient -s NAME`, then `server-name` will have the value `NAME`.
`(expand-file-name server-name server-socket-dir)` is more specific, if there's a chance of the socket directory varying.
If you're using TCP sockets instead of local sockets then things are a bit different again, with `server-auth-dir` being used.
> 1 votes
---
Tags: emacsclient
---
|
thread-58915
|
https://emacs.stackexchange.com/questions/58915
|
Org mode To Do's: completed tasks statistics cookie for items more than one level down
|
2020-06-05T00:52:28.737
|
# Question
Title: Org mode To Do's: completed tasks statistics cookie for items more than one level down
I am working on a project with several steps, each of which has sub-steps; each sub-step has sub-steps as well. The steps and sub-steps are headings; the sub-sub-steps are To Do items. I would like to have the steps' statistics cookie reflect whether the sub-steps are completed. It remains at 0/0, even if the sub-steps show the level of completion of the To-Do items in the sub-sub-steps. Minimal working example, below.
I suspect the key can be found somewhere in the documentation on sub-tasks, but I haven't been able to make this work yet.
Thank you for helping out! This is my first StackExchange question.
```
** Step 2 EDA (SQL) [0/0]
*** Number of rides 15-16 Nov [3/3]
- [X] Find number of rides for each company 15 - 16 November
- [X] Name the resulting field trips_amount and print it along with the
company_name field.
- [X] Sort the results by the trips_amount field in descending order.
*** Yellow and Blue cabs [0/3]
- [ ] Find the number of rides for every taxi company whose name contains the
words "Yellow" or "Blue" for November 1-7, 2017.
- [ ] Name the resulting variable trips_amount.
- [ ] Group the results by the company_name field.
```
# Answer
> 0 votes
You cannot have the second level statistics cookies be influenced by the fourth level checkboxes: you can only have them influenced by the TODO/DONE status of the third-level headlines. In other words, you are going to have to do something like this, adding TODO states to your third-level headlines:
```
** Step 2 EDA (SQL) [1/2]
*** DONE Number of rides 15-16 Nov [3/3]
CLOSED: [2020-06-04 Thu 23:02]
:PROPERTIES:
:VISIBILITY: folded
:END:
- [X] Find number of rides for each company 15 - 16 November
- [X] Name the resulting field trips_amount and print it along with the
company_name field.
- [X] Sort the results by the trips_amount field in descending order.
*** TODO Yellow and Blue cabs [1/3]
:PROPERTIES:
:VISIBILITY: folded
:END:
- [X] Find the number of rides for every taxi company whose name contains the
words "Yellow" or "Blue" for November 1-7, 2017.
- [ ] Name the resulting variable trips_amount.
- [ ] Group the results by the company_name field.
```
Note that the second-level headline statistics cookie does not care about the checkboxes two levels down; it only cares about the TODO states one level down.
But having to navigate to a headline in order to change its TODO state after all of its checkboxes are checked is a pain. Fortunately, there are ways to do that automatically. In fact, I wrote some code to do that a long time ago and it's still available at the Org mode Worg site \- and, miracle of miracles, I just tried it and it still works! I add it here to make the answer self-contained but you should read the linked Org Hacks entry for some caveats:
```
(eval-after-load 'org-list
'(add-hook 'org-checkbox-statistics-hook (function ndk/checkbox-list-complete)))
(defun ndk/checkbox-list-complete ()
(save-excursion
(org-back-to-heading t)
(when (re-search-forward "\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
(line-end-position) t)
(org-todo (if (if (match-end 1)
(equal (match-string 1) "100%")
(and (> (match-end 2) (match-beginning 2))
(equal (match-string 2) (match-string 3))))
;; All done - do the state change.
'done
'todo)))))
```
One thing I should point out: in order for the hook to be run, you need to change the checkbox state either by clicking on it or with `C-c C-c` from the keyboard. If you modify the state of the checkbox manually by changing the `X` to a space or vice versa will not update the state of the statistics cookies until *something* runs the hook.Other than that, just add the code to your initialization file and you should be all set.
P.S. Thanks to @Stefan for cleaning up the code.
---
Tags: org-mode, todo
---
|
thread-58918
|
https://emacs.stackexchange.com/questions/58918
|
Comment code using elisp
|
2020-06-05T03:22:03.747
|
# Question
Title: Comment code using elisp
Input and desired output
```
Original code Commented out code:
C %% MODULE %% module_name C~ CPR C ## MODULE ## module_name
lines of code C~ CPR lines of code
lines of code C~ CPR lines of code
..... C~ CPR .....
..... C~ CPR .....
..... C~ CPR ....
.... C~ CPR ....
.... C~ CPR ....
C %% END MODULE %% module_name C~ CPR C ## END MODULE ## module_name
```
Steps:
1. The cursor (point) is usually somewhere in between the `C %% MODULE %%` and `C %% END MODULE %%`
2. Select the lines between `C %% MODULE %%` and `C %% END MODULE %%` and `replace-string` `%%` with `##`
3. The `C-x C-x`to make the repeat the last selection and run `string-insert-rectangle` and insert the comment text `C~ CPR` \-
My Function (I'm new to elisp, bear with my terrible code)
```
(defun comment-pdtn()
(interactive)
(set-buffer (buffer-name))
(search-backward "C %% MODULE %%")
(set-mark (- (point) 14)) ;; 14 is the # of char in C %% MODULE %%
(search-forward "C %% END MODULE %%")
(message "begin at %s and ends at %s" ;; Want to ensure that region selection happened
(region-beginning)
(region-end))
(string-insert-rectangle "C~ CPR ")) ;; This isn't working
(comment-pdtn)
```
I'm yet to add the functionality for `replace-string` yet. How to implement `string-insert-rectangle`in Elisp? I want to write something like this,
1. With region ( string-insert-rectangle "C~ CPR ")
2. With region ( replace-string "%%" "##")
I could do this with macro and save the macro and do away with it, but I want to learn elisp that is the reason behind this question.
# Answer
> 1 votes
You usually don't need to manipulate the region with the Lisp code besides accessing the current region, that is, you seldom call `set-mark` from Lisp. Emacs commands operate on the region usually take the arguments `START` and `END`, thus when you call these commands from Lisp, you don't need the region, you need only two buffer positions, for example,
```
M-x mark-whole-buffer
M-x string-insert-rectangle prefix-
```
should be "translated" into
```
(string-insert-rectangle (point-min) (point-max) "prefix-")
```
The following takes advantage of (emacs) Narrowing, so we don't need to keep tracking the region we're working on.
```
(save-excursion ; restore point (optional)
(save-restriction ; undo narrow
;; Step 1. Narrow to the region, so we won't change other area by accident
(narrow-to-region
(progn (search-backward "C %% MODULE %%")
(line-beginning-position))
(progn (search-forward "C %% END MODULE %%")
(line-end-position)))
;; Step 2. Replace %% with ##, we don't use `replace-string' because its docstring suggests so
(goto-char (point-min))
(while (search-forward "%%" nil t)
(replace-match "##" nil t))
;; Step 3. Insert the prefix to each line of the (narrowed) buffer
(string-insert-rectangle (point-min) (point-max) "C~ CPR ")))
```
---
Tags: comment
---
|
thread-58913
|
https://emacs.stackexchange.com/questions/58913
|
Why does ivy 1.13.0 from GNU ELPA have counsel included?
|
2020-06-04T22:27:44.600
|
# Question
Title: Why does ivy 1.13.0 from GNU ELPA have counsel included?
MELPA has a package called *counsel*. Most guides on the *ivy* package recommend installing *counsel* as well. GNU ELPA doesn't have *counsel*. Why doesn't it?
I've installed *ivy 0.13.0* from GNU ELPA. I don't have *counsel* listed among installed packages and I don't have a directory called *counsel* in *~/.emacs.d/elpa*. However, I have commands *counsel-mode*, *counsel-find-file*, and other commands which start with *counsel-*, and they work. Why do I have them?
Why does MELPA have a separate package called *counsel*?
---
Edit: Comparing the `ivy` package from GNU ELPA and MELPA:
* Filenames in common:
```
colir.el
dir
ivy-autoloads.el
ivy-overlay.el
ivy-pkg.el
ivy.el
ivy.info
```
* Only in GNU ELPA ivy-0.13.0:
```
ChangeLog
counsel.el
ivy-hydra.el
swiper.el
```
* Only in MELPA ivy-20200601.1105:
```
elpa.el
ivy-avy.el
ivy-faces.el
ivy-help.org
```
# Answer
> 1 votes
I've asked a similar question some years ago, it appears to be the byproduct of a rename: https://github.com/abo-abo/swiper/issues/915#issuecomment-286198927. To quote the relevant part:
> Oh yea. By popular demand, swiper 0.7.0 -\> ivy 0.8.0. On ELPA, ivy 0.8.0 bundles ivy, swiper and counsel. On MELPA, they are separate.
---
Tags: ivy, counsel
---
|
thread-33928
|
https://emacs.stackexchange.com/questions/33928
|
File error: Cannot open load file, no such file or directory, multi-web-mode
|
2017-07-03T10:32:38.283
|
# Question
Title: File error: Cannot open load file, no such file or directory, multi-web-mode
I want to load the `multi-web-mode` package and have put it in `~/.emacs.d/` or `~/` or `~/.emacs.d/lisp/`(so far).
My `.emacs` contains the standard from the multi-web-mode distribution:
```
(require 'multi-web-mode)
(setq mweb-default-major-mode 'html-mode)
(setq mweb-tags
'((php-mode "<\\?php\\|<\\? \\|<\\?=" "\\?>")
(js-mode "<script[^>]*>" "</script>")
(css-mode "<style[^>]*>" "</style>")))
(setq mweb-filename-extensions '("php" "htm" "html" "ctp" "phtml" "php4" "php5"))
(multi-web-global-mode 1)
```
I get:
```
File error: Cannot open load file, no such file or directory, multi-web-mode
```
I was expecting that emacs would search in some of my directories and automatically discover it.
When I add
```
(load-file "~/.emacs.d/lisp/multi-web-mode.el")
```
or
```
(add-to-list 'load-path "~/.emacs.d/lisp/")
```
to the `.emacs` file the emacs lisp file is loaded alright.
Is there really no user directory where the .el files are automatically loaded from? Would I always need to do `(add-to-list 'load-path "~/.emacs.d/lisp/")` everytime I setup emacs?
# Answer
> 6 votes
You can type `M-x ielm`
Then in the REPL type `load-path` to see what the default is. I know package manager appends to it but I'm not sure what else (if anything) does. You can add `(add-to-list 'load-path "~/.emacs.d/lisp/")` to your `init.el` file. It is good to get used to modifying your `init.el` file. I actually have multiple \*.el files for my configuration that I modify. The more you use emacs the more you will want to customize it to your needs. If you search the web for emacs configuration you will find many examples on github.
I setup my `.emacs.d` directory with a small 'init.el' that contains `load-path` adjustments and a few other small things. Then I have an `emacs-config` directory that contains more .el files including but not limited to:
```
.emacs.d/home/emacs-config:
dired-setup.el
emacs-config.el
hydra-binding.el
ibuffer-setup.el
init.el
key-binding.el
org-setup.el
util-functions.el
window-setup.el
```
# Answer
> 0 votes
A simple explanation for this issue is that in your init file, `require` appears before `package-initialize`.
---
Tags: config
---
|
thread-58925
|
https://emacs.stackexchange.com/questions/58925
|
Capture org-agenda and show-some-entry-text into dynamic block
|
2020-05-31T09:52:24.920
|
# Question
Title: Capture org-agenda and show-some-entry-text into dynamic block
In summary I want to capture `org-agenda` into a dynamic block with some entry text.
At the end of the week I provide a report as to what I've been doing and a list of what I intend to work on in the coming week. For listing what I have been doing I use a `clocktable` to show me time spent. And for what's still to do, I use a custom agenda view which captures specific tags and sorts the list by priority. For both of these tasks I have been manually copying items from the `clocktable` and agenda into my report.
So how might I create the `org-agenda` block in my report buffer automatically?
# Answer
For the second part (inserting org-agenda) this is what I came up with, I wonder if there is another way?
*Using org-version 9.3.6.* (updated slightly) *for org-version 9.4.4*
```
#+begin_src emacs-lisp
(defun org-dblock-write:sjm/org-insert-agenda (params)
"Writes agenda items with some some text from the entry as context
to dynamic block.
Parameters are:
:key
If key is a string of length 1, it is used as a key in
`org-agenda-custom-commands` and triggers that command. If it
is a longer string it is used as a tags/todo match string.
:leaders
String to insert before context text. Defaults to two spaces \" \".
Do not use asterisk \"* \".
:count
Maximum number of lines to include, defaults to
org-agenda-entry-text-maxlines
:replace-what
Regex to replace. Defaults to heading asterisk characters and
first uppercase word (TODO label): \"^\\* [A-Z-]* \"
:replace-with
String to replace the org-heading star with.
Defaults to \"- \" such that headings become list items.
Somewhat adapted from org-batch-agenda.
"
(let ((data)
(cmd-key (or (plist-get params :key) "b"))
(org-agenda-entry-text-leaders (or (plist-get params :leaders) " "))
(org-agenda-entry-text-maxlines (or (plist-get params :count)
org-agenda-entry-text-maxlines))
(replace-this (or (plist-get params :repalce-this) "^\\* [A-Z-]* "))
(replace-with (or (plist-get params :replace-with) "- "))
(org-agenda-sticky))
(save-window-excursion ; Return to current buffer and window when done.
(if (> (length cmd-key) 1) ; If key is more than one character, THEN
(org-tags-view nil cmd-key) ; Invoke tags view, ELSE
(org-agenda nil cmd-key)) ; Invoke agenda view using key provided.
(setq data (buffer-string)) ; copy agenda buffer contents to data
(with-temp-buffer ; Using a temporary buffer to manipulate text.
(insert data) ; place agenda data into buffer.
(goto-char (point-max)) ; end-of-buffer
(beginning-of-line 1) ; beggining of last line.
(while (not (bobp)) ; while not begging of buffer
(when (org-get-at-bol 'org-hd-marker) ; get text property.
(sjm/org-agenda-entry-text)) ; Insert item context underneath.
(beginning-of-line 0)) ; Go to previous line
(setq data (buffer-string)))) ; Copy buffer, close tmp buf & excursion.
;; Paste data, replacing asterisk as per replace-this with replace-with.
(insert (replace-regexp-in-string replace-this replace-with data))))
;
(defun sjm/org-agenda-entry-text ()
"Insert some text from the current agenda item as context.
Adapted from `org-agenda-entry-text-show-here', relies upon
`org-agenda-get-some-entry-text' for the bulk of the work."
(save-excursion ; return to current place in buffer.
(let (m txt o) ; declare some local variables.
(setq m (org-get-at-bol 'org-hd-marker)) ; get text property
(unless (marker-buffer m) ; get buffer that marker points into.
(error "No marker points to an entry here"))
;; get some entry text, remove any properties and append a new-line.
(setq txt (concat "\n" (org-no-properties
(org-agenda-get-some-entry-text
m org-agenda-entry-text-maxlines
org-agenda-entry-text-leaders))))
(when (string-match "\\S-" txt)
(forward-line 1)
(insert txt "\n\n")))))
#+end_src
```
The `org-agenda` is then applied using `C-c -C-x C-u` while within the following block
```
#+BEGIN: sjm/org-insert-agenda :key "b"
#+END:
```
I've not really looked at the first part yet.
> 0 votes
---
Tags: org-mode
---
|
thread-58928
|
https://emacs.stackexchange.com/questions/58928
|
How do you handle a key sequence inside a function?
|
2020-06-05T13:34:21.977
|
# Question
Title: How do you handle a key sequence inside a function?
I want to run a function and do different actions based on the next key sequence.
I have this.
```
(defun ask-for-C-b-or-M-b (key-sequence)
(interactive "KPress Key")
(cond
((seq-set-equal-p key-sequence
[?\C-b]) "C-b pressed")
((seq-set-equal-p key-sequence
[?\M-b]) "M-b pressed")))
(call-interactively 'ask-for-C-b-or-M-b)
```
This works for `C-b` but not for `M-b` and I would like to use the kbd function
```
(kbd "C-b") instead of [?\C-b]
(kbd "M-b") instead of [?\M-b]
```
I'm trying to get extra keys in a hydra without making a new hydra
```
(defhydra hydra-test
nil
"test hydra"
("SPC" ask-for-C-b-or-M-b "Do complicated thing"))
```
# Answer
> 2 votes
I believe the missing link you're looking for is `listify-key-sequence`, which will "convert a key sequence to a list of events". Luckily, this works for both key sequences and for the values returned by `kbd`, so the following should return true:
```
(equal (listify-key-sequence [?\C-b])
(listify-key-sequence (kbd "C-b")))
```
So your function would be:
```
(defun ask-for-C-b-or-M-b (key-sequence)
(interactive "KPress Key")
(cond
((seq-set-equal-p (listify-key-sequence key-sequence)
(listify-key-sequence (kbd "C-b")))
"C-b pressed")
((seq-set-equal-p (listify-key-sequence key-sequence)
(listify-key-sequence (kbd "M-b")))
"M-b pressed")))
```
---
Tags: key-bindings, hydra
---
|
thread-58927
|
https://emacs.stackexchange.com/questions/58927
|
How can I make Emacs use the first available font from a list I specify?
|
2020-06-05T13:02:23.357
|
# Question
Title: How can I make Emacs use the first available font from a list I specify?
I share my Emacs config across several machines, and I can't necessarily guarantee that they will all have the same fonts installed. For this reason, I would like to be able to give Emacs a list of acceptable fonts to use and have it select the first available font from that list at startup and set the default face to use that font. This should give me a reasonable-looking Emacs on any system. Is there a way to do this by default, or a package that implements it, or will I have to write my own code for this?
# Answer
> 2 votes
You could just set the `face-font-family-alternatives` variable:
```
-- User Option: face-font-family-alternatives
If a given family is specified but does not exist, this variable
specifies alternative font families to try. Each element should
have this form:
(FAMILY ALTERNATE-FAMILIES...)
If FAMILY is specified but not available, Emacs will try the other
families given in ALTERNATE-FAMILIES, one by one, until it finds a
family that does exist.
```
Use `C-h v` to see its current value; it's probably already got some alternatives for certain family names. Here's the value my Emacs currently has:
```
(("Monospace" "courier" "fixed")
("Monospace Serif" "Courier 10 Pitch" "Consolas" "Courier Std" "FreeMono" "Nimbus Mono L" "courier" "fixed")
("courier" "CMU Typewriter Text" "fixed")
("Sans Serif" "helv" "helvetica" "arial" "fixed")
("helv" "helvetica" "arial" "fixed"))
```
---
Tags: fonts
---
|
thread-13254
|
https://emacs.stackexchange.com/questions/13254
|
Find external definition with gtags or ggtags
|
2015-06-18T07:30:47.373
|
# Question
Title: Find external definition with gtags or ggtags
Using gtags.el or ggtags.el.
I have a project A depending on project B. While in a buffer belonging to A, I want to jump to a definition in B. How do I do this with `ggtags-mode` ? `M-.` simply lists the occurences in project A.
# Answer
I would create a symbolic link to project B in one of the directories on project A and run `gtags` in both the projects (as you might also need to use tags for Project B only).
There's also another way to solve this problem; here's more info from `global` documentation:
> If you want to locate symbols that are not defined in the source tree, then you can specify library directories with GTAGSLIBPATH environment variable.
>
> You should execute gtags(1) at each directory in the GTAGSLIBPATH. If βGTAGSβ is not found there, global ignores such directories.
```
$ pwd
/develop/src/mh # this is a source project
$ gtags
$ ls
G*TAGS GRTAGS GTAGS
$ global mhl
uip/mhlsbr.c # mhl() is found
$ global strlen # strlen() is not found
$ (cd /usr/src/lib; gtags) # library source
$ (cd /usr/src/sys; gtags) # kernel source
$ export GTAGSLIBPATH=/usr/src/lib:/usr/src/sys
$ global strlen ../../../usr/src/lib/libc/string/strlen.c # found in library $ global access ../../../usr/src/sys/kern/vfs_syscalls.c # found in kernel
```
> Or, you can take a more straightforward way to do the same thing. In the following example, we treat as if the system library and the kernel are part of our project.
```
$ ln -s /usr/src/lib .
$ ln -s /usr/src/sys .
$ gtags
$ global strlen
lib/libc/string/strlen.c
$ global access
sys/kern/vfs_syscalls.c
```
\[Source\]
> 6 votes
# Answer
kaushalmodi's answer is almost perfect, but it doesn't solve the problem at hand. I suggest you to run gtags on each project directory say ~/projects/{a,b}
```
cd ~/projects/a
gtags
cd ../b
gtags
```
Now the trick is t use the GTAGSLIBPATH variable as shown in Global documentation so you can use global -T
```
global -T <function_symbol>
```
You should see global references to both repositories, if so you can proceed to set this variable in emacs.
Unfortunately the GTAGSLIBPATH variable is not enough for ggtags to show the definition in both modules; you need to force the '-T' option in global.
To force the '-T' option you have to set the environment variable GTAGSTHROUGH to any value (such as true) directly in emacs or as part of the environment when you launch it
```
;; You can set this in your .emacs
(setenv "GTAGSTHROUGH" "true")
```
Now you should be able to see the definitions from both projects using ggtags
> 3 votes
# Answer
The `GTAGSLIBPATH` solution here requires that project B has a `GTAGS` file, when you may only want tags from project A always. You may then temporarily set the current directory to be in project A
```
(defun ggtags-find-definition-projectA ()
"Find global tags in project A from anywhere"
(interactive)
(let ((default-directory "/path/to/project/A"))
(call-interactively 'ggtags-find-definition)))
```
and assign a shortcut to it.
> 0 votes
---
Tags: gtags
---
|
thread-58938
|
https://emacs.stackexchange.com/questions/58938
|
How do I open an sqlite database from elisp?
|
2020-06-06T07:07:14.233
|
# Question
Title: How do I open an sqlite database from elisp?
I have a filepath for a sqlite database. I want to open an sql client buffer. I would like to know the best way to open that database from elisp. So far I can see that `sql-sqlite` will open it but it requires an interaction.
I'm calling `(sql-sqlite "/path/to/some/database")` and it then prompts me in the minibuffer to confirm the path before opening the database. I can see from the docs that this is an interactive function. Is there a non-interactive way to do this?
# Answer
> 1 votes
It depends on what you're trying to implement. `sql-sqlite` is a function that you would use if you want to interactively send commands to a sqlite process. This is what you want if you're writing some code that uses SQL and you want a REPL where you can test your queries.
On the other hand if you're writing an emacs mode that stores data in a database then this isn't what you want. You want the `emacsql` package, or possibly `closql`. `emacsql` lets you execute arbitrary queries using an s-expression syntax. Some examples from the documentation:
```
(emacsql db [:create-table people ([name (id integer :unique) salary])])
(emacsql db [:insert :into people
:values (["Jeff" 1000 60000.0] ["Susan" 1001 64000.0])])
```
`closql` is a higher-level ORM that stores class instances in database tables for you.
Since you didn't say what you're actually doing, we can only guess which is more appropriate.
Edit:
Ah, since you do want a REPL, `sql-sqlite` is what you want. You may already know that you can tell it which database to open by setting the `sql-database` variable before calling it (or by adding a dynamic binding):
```
(let ((sql-database "~/temp/test.sql"))
(sql-sqlite))
```
However, I've just checked and it still prompts for the database file name. It uses the value you set as the default value for the prompt, which will save you time, but a quick look through the code shows that there's no easy way to disable the prompt. If it were a different kind of database it would also prompt you for other details such as username and password. You could add advice to the function `sql-get-login-ext` so that it skips the prompt if there already is a value, but that might not be a good idea.
---
Tags: sql, sql-mode, sqlite
---
|
thread-58921
|
https://emacs.stackexchange.com/questions/58921
|
How to hide/fold parts of messages in notmuch
|
2020-06-05T10:47:12.463
|
# Question
Title: How to hide/fold parts of messages in notmuch
I've been trying various combinations of folding modes for Emacs, trying to get them to work with `notmuch-show-mode`, but to no avail:
Given two messages like this:
```
Summary: Some Guy <someguy@example.com> (May 27) (replied)
Subject: About this
To: Some Other Guy <someotherguy@example.com>
Date: Wed, 27 May 2020 13:45:51 +0200
[ multipart/related ]
[ text/html ]
Dear some guy
This is a reply to your mail.
------------------------------------------------
HEADERS_HERE
This is my original mail.
Summary: Some Guy <someguy@example.com> (May 27) (replied)
Subject: About this
To: Some Other Guy <someotherguy@example.com>
Date: Wed, 27 May 2020 13:45:51 +0200
[ multipart/related ]
[ text/html ]
This is my original mail.
```
I want to collapse the part from "-----------." and until the next "Summary: ".
I spend the most time trying to get hs-minor-mode working with this in my init.el:
```
(with-eval-after-load 'hideshow
(add-to-list 'hs-special-modes-alist
'(notmuch-show-mode
"---------" ; START
"Summary:" ;END
"" ; COMMENT-START
nil ; FORWARD-SEXP-FUNC
nil ; ADJUST-BEG-FUNC
)))
```
But calling `M-x hs-minor-mode` gives this error:
```
hs-grok-mode-type: notmuch-show Mode doesnβt support Hideshow Minor Mode
```
# Answer
> 0 votes
The "hs-grok-mode-type: notmuch-show Mode doesnβt support Hideshow Minor Mode" error was solved by setting `comment-start` to a fake value. After that I needed to provide custom `FORWARD-SEXP-FUNC` and `ADJUST-BEG-FUNC` values to `hs-special-modes-alist`. I ended up with the following in my init.el:
```
(defun my-notmuch-show-hs-forward-sexp (a)
(re-search-forward "Summary:")
(beginning-of-line)
(backward-char 1))
(defun my-notmuch-show-hs-adjust-block-beginning (pos)
(save-excursion (goto-char pos) (previous-line) (previous-line) (end-of-line)
(point)))
(setq hs-special-modes-alist
'((notmuch-show-mode "----------\n" "Summary:" "///IDONTNEEDTHIS"
my-notmuch-show-hs-forward-sexp my-notmuch-show-hs-adjust-block-beginning)))
(add-hook 'notmuch-show-mode-hook
(lambda ()
(setq-local comment-start "///IDONTNEEDTHIS")
(hs-minor-mode)))
(setq hs-set-up-overlay
(defun my-display-code-line-counts (ov)
(when (eq 'code (overlay-get ov 'hs))
(overlay-put ov 'display
(propertize
(format "\n... <%d>"
(count-lines (overlay-start ov)
(overlay-end ov)))
'face 'font-lock-type-face)))))
```
---
Tags: outline, hideshow, notmuch
---
|
thread-58937
|
https://emacs.stackexchange.com/questions/58937
|
Info manuals not listed in Termux
|
2020-06-06T02:27:36.687
|
# Question
Title: Info manuals not listed in Termux
I have Emacs installed through Termux. The Emacs manuals (`emacs.info.gz`, etc.) are located at `/data/data/com.termux/files/usr/share/info/`. I can open them with `find-file`. I don't see them with `C-h i`.
The INFOPATH is set in `~/.bashrc`:
```
# .bashrc
export INFOPATH=$INFOPATH:/data/data/com.termux/files/usr/share/info/
```
A new Termux session shows the correct INFOPATH. The path above is the `Info-default-directory-list` and is the last entry in `Info-directory-list`.
The texinfo, gzip, and zlib packages are installed in Termux.
I can see the manuals for Magit, use-package, etc. listed in `*info*`.
How can I access the Emacs manuals through Info?
# Answer
> 3 votes
There are two components to the Info system: the info files themselves and a `dir` file which acts as the top level index. When Info sees more than one directory in `INFOPATH`, it merges all the `dir` files that it finds into one index. The corollary however is that the `dir` file must exist.
You can create the `dir` file by hand if you want: there is information about that in the Texinfo manual, but in most cases, it is built when the info file for the package is installed.
In any case, since these are the standard emacs info files, you can reinstall them using the appropriate `make` invocation and get everything. GNU Makefiles make use of the `prefix` variable (`/usr/local` by default) to construct all the directories for the software installation. So all you have to do is override that destination:
```
sudo make install-info prefix=/data/data/com.termux/files/usr
```
That in turn uses the `install-info` program appropriately to add the various info files to the `dir` file in the info directory corresponding to the prefix (`$prefix/share/info`).
In fact, since the info files were already installed in that directory, the OP found it expedient to just run a small script to create the `dir` file from the existing info files instead of rerunning the `make`:
```
for file in /data/data/com.termux/files/usr/share/info/*
do
install-info --info-file="$file" --dir-file=/data/data/com.termux/files/usr/share/info/dir
done
```
---
Tags: info, manual, termux
---
|
thread-58930
|
https://emacs.stackexchange.com/questions/58930
|
Org-habit how to track number over time
|
2020-06-05T16:03:33.750
|
# Question
Title: Org-habit how to track number over time
(still a complete beginner to org in general)
I managed to setup `org-habit`, that also feeds into `org-agenda` to neatly see habits. I would like to track a few variables that go along with my habits (e.g. track my weight).
I see 2 options:
1. add notes via the :LOGGING: property
2. create a custom property (?)
How can I track variable values over time?
# Answer
I have an Org capture template that tracks weight. It is a sub-capture under "health". The relevant snippet for the capture template is:
```
("h" "Health")
("hW" "Weight"
table-line (id "ID-TBL-WEIGHT") "|%?|%u|" :unnarrowed t)
```
And then I have a table that collects the data:
```
:PROPERTIES:
:ID: ID-TBL-WEIGHT
:END:
#+NAME: weights
| Weight (lbs) | Date | Note | Offset |
|--------------+------------------+--------------------------+--------|
| 142 | [2013-03-25 Mon] | | |
| 144 | [2020-06-06 Sat] | | |
```
The idea being it is easy to log weight on any given date, take notes (e.g. "pre/post some travel, sickness, exercise, diet, etc.") and even offsets if you switch scales and need to adjust for something.
Elsewhere, graph it with Org babel blocks. I use `jupyter-python` but Gnuplot or the built-in Org graphing should all work roughly the same. In all cases, in the `#+BEGIN_SRC` header you'll want to have `:var w=weights` (from the `#+NAME: weights` line).
> 4 votes
---
Tags: org-mode, logging, org-habit
---
|
thread-58943
|
https://emacs.stackexchange.com/questions/58943
|
Emacs segfaults after I run M-x package-install
|
2020-06-06T17:14:29.863
|
# Question
Title: Emacs segfaults after I run M-x package-install
I'm a Emacs newbie. I've gone through the guided tutorial and I got excited by what Emacs promises. I want to learn Emacs and use it as my primary development editor, and specifically at the moment for Clojure development with Cider.
When I type `M-x package-install` and hit enter to try and install Cider my Emacs just closes unexpectedly. I've tried several suggestions I found on this site and other but no luck so far.
Here's what I get on the terminal using `--debug-init` as a post I read suggested:
```
Backtrace:
/snap/emacs/296/usr/bin/emacs[0x58f0c7]
/snap/emacs/296/usr/bin/emacs[0x567cbc]
/snap/emacs/296/usr/bin/emacs[0x58e802]
/snap/emacs/296/usr/bin/emacs[0x58e7d3]
/snap/emacs/296/usr/bin/emacs[0x58e83d]
/snap/emacs/296/usr/bin/emacs[0x58e9f9]
/snap/core18/current/lib/x86_64-linux-gnu/libpthread.so.0(+0x12890)[0x7fe670900890]
/snap/core18/current/lib64/ld-linux-x86-64.so.2(+0xcac8)[0x7fe677759ac8]
/snap/core18/current/lib64/ld-linux-x86-64.so.2(+0x150bd)[0x7fe6777620bd]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(_dl_catch_exception+0x6f)[0x7fe66fd642df]
/snap/core18/current/lib64/ld-linux-x86-64.so.2(+0x147ca)[0x7fe6777617ca]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(+0x1663ad)[0x7fe66fd633ad]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(_dl_catch_exception+0x6f)[0x7fe66fd642df]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(_dl_catch_error+0x2f)[0x7fe66fd6436f]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(__libc_dlopen_mode+0x89)[0x7fe66fd634d9]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(+0x148886)[0x7fe66fd45886]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(__nss_lookup_function+0x128)[0x7fe66fd46088]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(+0x105cf3)[0x7fe66fd02cf3]
/snap/core18/current/lib/x86_64-linux-gnu/libc.so.6(getaddrinfo+0x124)[0x7fe66fd04ce4]
/snap/emacs/296/usr/bin/emacs[0x671b31]
/snap/emacs/296/usr/bin/emacs[0x619809]
/snap/emacs/296/usr/bin/emacs[0x6194e5]
/snap/emacs/296/usr/bin/emacs[0x664a8f]
/snap/emacs/296/usr/bin/emacs[0x619fa0]
/snap/emacs/296/usr/bin/emacs[0x619529]
/snap/emacs/296/usr/bin/emacs[0x664a8f]
/snap/emacs/296/usr/bin/emacs[0x61a30a]
/snap/emacs/296/usr/bin/emacs[0x619529]
/snap/emacs/296/usr/bin/emacs[0x664a8f]
/snap/emacs/296/usr/bin/emacs[0x619fa0]
/snap/emacs/296/usr/bin/emacs[0x619529]
/snap/emacs/296/usr/bin/emacs[0x664a8f]
/snap/emacs/296/usr/bin/emacs[0x619fa0]
/snap/emacs/296/usr/bin/emacs[0x619529]
/snap/emacs/296/usr/bin/emacs[0x664a8f]
/snap/emacs/296/usr/bin/emacs[0x61a30a]
/snap/emacs/296/usr/bin/emacs[0x619529]
/snap/emacs/296/usr/bin/emacs[0x664a8f]
/snap/emacs/296/usr/bin/emacs[0x619fa0]
/snap/emacs/296/usr/bin/emacs[0x619529]
/snap/emacs/296/usr/bin/emacs[0x664a8f]
```
How can I fix this? I've tried:
* removing and re-installing Emacs,
* changing the Emacs init file
but none of that has worked.
Do you have any suggestions? What can I do to fix this?
As an aside note, I see a quick message `Contacting host: melpa.org:443` before the crash happens so I changed my Emacs init file to see if it would fix the error, but no luck.
```
(setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")
;(setq package-check-signature nil)
; Set up melpa package repository
(require 'package)
(setq package-enable-at-startup nil)
(package-initialize)
(add-to-list 'package-archives
'("gnu", "https://elpa.gnu.org/packages/")
'("melpa", "https://melpa.org/packages/"))
```
Ideas and suggestions welcome and appreciated. Thank you.
# Answer
The crash turned out to be caused by an improperly packaged snap version of Emacs. The solution was either to upgrade to one that is properly packaged, or to install the apt package rather than the snap.
> 1 votes
---
Tags: package, crash, snap
---
|
thread-58941
|
https://emacs.stackexchange.com/questions/58941
|
Removing alignment in LaTeX align environment
|
2020-06-06T16:14:34.220
|
# Question
Title: Removing alignment in LaTeX align environment
I want to write a very long equation (3-4 lines) in LaTeX. For this equation I want to use `align` environment. What I don't like is how Emacs formats the LaTeX code: it adds a lot of unnecessary space, something like
```
\begin{align*}
\|a+b+c\|^4 & = \left(\|a\|^2 + \|b\|^2 + \|c\|^2 + 2 \langle a, b
\rangle + 2\langle b,c \rangle + 2 \langle a, c\rangle
\right)^2\\ &= \left(\|a\|^2 + \|b\|^2 + \|c\|^2 +
2\langle a, b\rangle +2\langle
b,c\rangle +2\langle a, c\rangle\right)^2
\end{align*}
```
And it becomes even worse if I edit it. Obviously, it is very inconvenient to edit such a mess in the future. How to force `align` not to use any automatic formatting and behave like `multline`, for example?
```
\begin{multline*}
\|a+b+c\|^4 = \left(\|a\|^2 + \|b\|^2 + \|c\|^2 +2 \langle a, b
\rangle + 2\langle b, c \rangle +2 \langle a,c\rangle\right)^2\\
= \left(\|a\|^2 + \|b\|^2 + \|c\|^2 +2 \langle a, b \rangle +
2\langle b, c \rangle +2 \langle a,c\rangle\right)^2
\end{multline*}
```
I use Emacs 26.3 and AuCTeX 12.2.0.
# Answer
> 1 votes
You can remove `("align*" LaTeX-indent-tabular)` from `LaTeX-indent-environment-list` and get the standard indent behaviour like multilines environment.
You can get more information about this variable with
```
(describe-variable 'LaTeX-indent-environment-list)
```
You can also compose your own `align*` environment formatting function...
# Answer
> 2 votes
I think you can get rid of any extra space that `auctex` adds, if you write it like this:
```
\begin{align*}
\|a+b+c\|^4
&= \left(\|a\|^2 + \|b\|^2 + \|c\|^2 + 2 \langle a, b
\rangle + 2\langle b,c \rangle + 2 \langle
a, c\rangle\right)^2 \\
&= \left(\|a\|^2 + \|b\|^2 + \|c\|^2 + 2\langle a,
b\rangle +2\langle b
,c\rangle +2\langle a, c\rangle\right)^2
\end{align*}
```
putting each `&=` on a new line. That has the additional advantage that the text in your emacs buffer has the two `&=` aligned, just as the `=` signs will be in the final output.
I would advise you not to split the `\langle ... \rangle` construct over multiple lines: find better places to split it where it makes mathematical sense. E.g.
```
\begin{align*}
\|a+b+c\|^4
&= \left(\|a\|^2 + \|b\|^2 + \|c\|^2
+ 2\langle a, b \rangle + 2\langle b,c \rangle + 2\langle a, c\rangle\right)^2 \\
&= \left(\|a\|^2 + \|b\|^2 + \|c\|^2
+ 2\langle a, b\rangle +2\langle b ,c\rangle +2\langle a, c\rangle \right)^2
\end{align*}
```
I actually find it *more* readable if I go back to the plentiful initial space that you don't like:
```
\begin{align*}
\|a+b+c\|^4 &= \left(\|a\|^2 + \|b\|^2 + \|c\|^2
+ 2\langle a, b \rangle + 2\langle b,c \rangle + 2\langle a, c\rangle\right)^2 \\
&= \left(\|a\|^2 + \|b\|^2 + \|c\|^2
+ 2\langle a, b\rangle +2\langle b ,c\rangle +2\langle a, c\rangle \right)^2
\end{align*}
```
That corresponds much more closely to what the final output will look like.
Finally, I would define a new command with two arguments to shorten the oft-occurring \`\langle .., .. \rangle' and use it, like this:
```
\documentclass{article}
\usepackage{amsmath}
\newcommand{\pair}[2]{\ensuremath{\langle #1, #2 \rangle}}
\begin{document}
...
\begin{align*}
\|a+b+c\|^4 & = \left(\|a\|^2 + \|b\|^2 + \|c\|^2
+ 2\pair{a}{b} + 2\pair{b}{c} + 2\pair{a}{c}\right)^2\\
& = \left(\|a\|^2 + \|b\|^2 + \|c\|^2
+ 2\pair{a}{b} + 2\pair{b}{c} + 2\pair{a}{c}\right)^2
\end{align*}
...
```
That's easy to parse by eye and even six months later, you should be able to see what it does.
Apart from the first example, the rest have nothing to do with emacs, just with how to format math in TeX/Latex. IOW, that's how I would write them even if I did not use emacs and auctex.
---
Tags: latex, auctex, align
---
|
thread-58953
|
https://emacs.stackexchange.com/questions/58953
|
Is there a version of lisp-interaction, Γ la *scratch* buffer, with asynchronous processing of evaluation?
|
2020-06-07T11:19:44.127
|
# Question
Title: Is there a version of lisp-interaction, Γ la *scratch* buffer, with asynchronous processing of evaluation?
While I develop some Emacs-Lisp code, I often test it in the \*scratch\* buffer, just to make sure that what I just wrote behaves like I believe it does.
But sometimes evaluating an expression takes several minutes and it is too bad that Emacs is frozen during this time. I'd love it if \*scratch\* behaved like the \*shell\* buffer with an interactive sub-shell. From the manual:
> While the subshell is waiting or running a command, you can switch windows or buffers and perform other editing in Emacs. Emacs inserts the output from the subshell into the Shell buffer whenever it has time to process it (e.g., while waiting for keyboard input).
Is there a package that provides such an interactive Emacs-Lisp eval-loop running asynchronously?
I understand that there are technical difficulties. E.g., I always assume that the environment Emacs is maintaining (defined functions, global variable values, ..) is the same for editing and for Lisp-interaction. If the evaluation of my code in \*scratch\* reveals a bug, I'll amend the code, `eval-defun` it, and try it again. So I expect that the eval-loop with which I am communicating in the \*scratch\* buffer is aware of the new definition.
# Answer
Try the `async` package (`M-x package-install`, if you don't already have it).
See the functions `async-start` and `async-inject-variables`. The given example is:
```
(async-start
`(lambda ()
(require 'smtpmail)
(with-temp-buffer
(insert ,(buffer-substring-no-properties (point-min) (point-max)))
;; Pass in the variable environment for smtpmail
,(async-inject-variables \"\\`\\(smtpmail\\|\\(user-\\)?mail\\)-\")
(smtpmail-send-it)))
'ignore)
```
Aside from that helper for variables, the code being evaluated would probably need to load any necessary libraries or otherwise include function definitions, as `async` is handing off to a completely independent emacs process.
---
With recent GNU Emacs versions you could also consider whether your code might be able to use threads to avoid blocking for so long in the first place. See `C-h``i``g` `(elisp)Threads`
> 3 votes
---
Tags: async, scratch-buffer
---
|
thread-58940
|
https://emacs.stackexchange.com/questions/58940
|
Misaligned chart in the habits agenda mode in orgmode
|
2020-06-06T09:20:31.477
|
# Question
Title: Misaligned chart in the habits agenda mode in orgmode
After upgrade from Ubuntu 18 to 20 my agenda habits chart now is broken. Any ideas in how to fix that?
# Answer
> 2 votes
Thanks to @NickD commentary I was able to figure out the issue.
**TL;DL:** the problem was with the variable `org-habit-graph-column` that was set to **80** and I just changed to **default** (removed the line). I tested with **40** and it worked fine as well. That was the first suspicion of @NickD in his first commentary.
Fortunately I keep track of my `.emacs` changes in my personal repo. So, I used the `git bisect` tool to find the bad commit. The bad commit was this one: **Improving params of habits** introduced in Oct 24, 2018. Maybe this wasn't an issue before because now I have scaled my screen to 150% in the new Ubuntu installation.
The first thing I did was to remove the line with `org-habit-graph-column` and everything just went fine. Then, I changed others parameters too, just to fit better in the screen, in this commit: **Fixing chart in agenda to 150% scale screens (HDPI)**.
---
Tags: org-mode, org-agenda, org-habit
---
|
thread-58963
|
https://emacs.stackexchange.com/questions/58963
|
How to "remove" a remapping so that I can access the underlying (remapped) command?
|
2020-06-08T10:01:10.907
|
# Question
Title: How to "remove" a remapping so that I can access the underlying (remapped) command?
I use `projectile` and `helm-projectile`. Sometimes I like to use `helm-projectile-grep` to explore the code dynamically, and sometimes I know what I am looking for and I want the speed, and persistence of `projectile-grep`.
However, when I map `projectile-grep` to a key, when I use that key it seems to call `helm-projectile-grep`. This is my current config:
```
(use-package projectile
:ensure t
:demand t
:config
(projectile-mode +1)
(define-key projectile-mode-map (kbd "s-p") 'projectile-command-map)
(setq projectile-switch-project-action 'projectile-dired)
(define-key projectile-command-map (kbd "g") 'projectile-grep))
(use-package helm-projectile
:ensure t
:demand t
:after (projectile)
:bind ("s-f" . helm-projectile-find-file)
:config
(helm-projectile-on))
```
How can I use separate key bindings for `helm-projectile-grep` and `projectile-grep`?
# Answer
Assuming that `helm-projectile` is doing this:
```
(define-key projectile-mode-map [remap projectile-grep] #'helm-projectile-grep)
```
You would disable that with:
```
(define-key projectile-mode-map [remap projectile-grep] nil)
```
> 3 votes
---
Tags: key-bindings
---
|
thread-47662
|
https://emacs.stackexchange.com/questions/47662
|
Perl script to fetch mail folders, for use with mbsync or offlineimap
|
2019-02-07T09:47:19.793
|
# Question
Title: Perl script to fetch mail folders, for use with mbsync or offlineimap
I have been looking at various email setups using different tools within Emacs for the last few months. I looked at various email setups using Gnus, mew, mu4e, wanderlust etc.
While reading one of the setups on some blog, I was trying to setup `offlineimap/mbsync`. And it requires the name of folders to fetch. On one such blog there was a Perl script to fetch all these folder names automatically. and output them to a file. These folder names can then be used with other configuration scripts to specify which particular folders to fetch.
Now I have finally got a setup which I am staying with and it is working for me. It uses `mbsync + mu4e` . I have a lot of folders in my mail box as I used to use filters. I was only able to use INBOX and Sent Mails in that configuration, as other folders are a lot. And now I am again looking to find that Perl script.
Does any of you have came across such setup which uses some Perl magic to fetch folders for the configuration?
# Answer
You can use `Net::IMAP::Simple` perl module/package.
Below please find "version zero" based on the man page.
```
#!/usr/bin/perl
use strict;
use warnings;
use Net::IMAP::Simple;
# Create the object
my $imap = Net::IMAP::Simple->new('imap.example.com', use_ssl => 1) ||
die "Unable to connect to IMAP: $Net::IMAP::Simple::errstr\n";
# Log on
if(!$imap->login('user','pass')){
print STDERR "Login failed: " . $imap->errstr . "\n";
exit(64);
}
# List folders
my @folders = $imap->mailboxes_subscribed;
foreach my $folder (@folders) {
print $folder,"\n";
}
```
> 0 votes
# Answer
Perl? Seriously?
```
#!/usr/bin/emacs --script
(require 'imap)
(defun imap-get-subscribed-folders (server port user pass)
(let ((buffer (imap-open server port)))
(unwind-protect
(with-current-buffer buffer
(imap-authenticate user pass)
(imap-mailbox-lsub))
(imap-close buffer))))
(mapc #'(lambda (f) (princ f) (terpri))
(imap-get-subscribed-folders "imap.example.com" nil "user" "password"))
```
> 0 votes
---
Tags: gnus, email, mu4e, wanderlust, perl
---
|
thread-2774
|
https://emacs.stackexchange.com/questions/2774
|
Using both fixed-width and variable-width font in org-mode
|
2014-10-28T21:37:39.457
|
# Question
Title: Using both fixed-width and variable-width font in org-mode
I would like to have an org-mode file with the following content:
```
#+TITLE: My awesome Emacs file
* My Header
Here's some information under the header
#+BEGIN_SRC sh
echo "this is some code"
#+END_SRC
More text and =verbatim= things
```
Is it possible to have Emacs display the header and text in a variable-width font and only the `#+BEGIN_SRC`, `#+END_SRC`, `=verbatim=` and source code in a fixed-width font?
# Answer
This is all-but-a-dupe of this question on SO. As of this writing, the accepted answer over there is (mutatis mutandis):
`(set-face-attribute 'org-verbatim nil :inherit 'fixed-pitch)`
EDIT: Actually read your question. Since you want to change multiple faces, this is a more complete answer:
```
(dolist (face '(org-block-begin-line
org-block-end-line
org-verbatim
org-block-background))
(set-face-attribute face nil :inherit 'fixed-pitch)
```
Note that this will overwrite any existing `:inherit` parameters on the faces. If that's a problem, another answer to the same SO question provides code to work around the issue.
> 7 votes
# Answer
There is a package for precisely that: mixed-pitch mode.
> 3 votes
# Answer
I'm not very familiar with how `org-mode` delimits blocks, so I can only give a general answer.
There is a standard face called `variable-pitch`, which you can apply to a given region like this:
```
(set-text-properties (region-beginning) (region-end) '(face (variable-pitch))))
```
This only works when automatic fontification is inhibited, though. You may be able to hook into `org-mode`'s fontification code and override the face of selected regions with `variable-pitch`.
> 1 votes
---
Tags: org-mode, fonts
---
|
thread-58973
|
https://emacs.stackexchange.com/questions/58973
|
Silence <location> <wheel-direction> is undefined
|
2020-06-08T20:48:27.663
|
# Question
Title: Silence <location> <wheel-direction> is undefined
How to silence GNU Emacs on MacOS with magic mouse? Forever getting the bell and messages telling me certain mouse wheel features are undefined when hovering in certain places. For example
```
<vertical-scroll-bar> <wheel-left> is undefined
<vertical-scroll-bar> <double-wheel-left> is undefined
<vertical-scroll-bar> <triple-wheel-left> is undefined [30 times]
```
# Answer
> 1 votes
The answer is similar as for any other key, assign it to a function that does nothing. Except one assigns the location and direction combination, for example:
```
(global-set-key (kbd "<vertical-scroll-bar> <wheel-left>") #'ignore)
```
As there are a number of locations and direction combinations a nested while loop helps.
```
(let ((areas '("mode-line" "left-fringe" "right-fringe" "header-line" "vertical-scroll-bar"))
(directions '("up" "down" "left" "right"))
(counts '("" "double-" "tripple-"))
loc direction count)
(while areas
(setq loc (pop areas))
(setq direction directions)
(while direction
(setq dir (pop direction))
(setq count counts)
(while count
(global-set-key
(kbd (concat "<" loc "> <" (pop count) "wheel-" dir ">")) #'ignore)))))
```
---
Tags: osx, mouse
---
|
thread-58970
|
https://emacs.stackexchange.com/questions/58970
|
Filter the content read from file
|
2020-06-08T17:32:11.987
|
# Question
Title: Filter the content read from file
(This follows the answer to the question: Completion of sentences stored in a file.)
Suppose I have a file, the content of which being organized thanks to `org-mode`:
```
* Dreams β reality
Please, don't take your dreams for reality: (a + b)Β² β aΒ² + bΒ².
Please, don't take your dreams for reality: cos(a + b) β cos a + cos b.
No, β(aΒ²) β a.
* Derivatives
You should revise the derivatives.
* General remarks
This only works for a positive x.
```
**Edit after @NickD comments:**
~~AFAICS, the function used for reading this file, `insert-file-contents`, filters (I mean ignores) empty lines. Is it possible to ask it to filter lines starting with a `*` as well~~?
Is it possible to ask the function used for reading this file, `insert-file-contents`, or a consequent one, to filter some lines, e.g. those starting with a `*`
# Answer
The answer to any "Is it possible" question is almost always yes (there is a theorem by Turing which tells us the limit of what is computable, but in practice people rarely come up against that limit). It is better to rephrase this type of question to ask *how* to do something, rather than merely if it is possible, since that's usually what most people mean by it. It's also a good idea to list what you've already tried, and possibly why that didn't work.
You want to use the `seq-remove` function. You can read the documentation for it by typing `C-h f seq-remove <RET>`. You'll see that it takes a predicate function and a sequence, and returns a new sequence comprised of those elements for which the predicate function returns nil.
For the predicate, I recommend writing a lambda that calls `string-match-p`. This returns true when a string matches a regular expression. Again, you can see the documentation for functions with `C-h f`.
Putting those together, something like this ought to work:
```
(seq-remove (lambda (line)
(string-match-p "^\\*+ " line))
your-list-of-strings)
```
The elisp manual includes additional documentation about these topics that you might want to read, along with documentation about similar functions that you may soon need. You can open the info browser with `C-h i`. You may have many info manuals installed on your computer, but you should specifically take a look at the Emacs manual and the Elisp manual. Chapters 6.1 Sequences and 34.4 Regular Expression Searching would be good places to start.
> 2 votes
---
Tags: filtering, read
---
|
thread-58977
|
https://emacs.stackexchange.com/questions/58977
|
How to change a variable value in the current buffer?
|
2020-06-08T22:10:05.937
|
# Question
Title: How to change a variable value in the current buffer?
I spent a long time looking for this and kept getting reference to `M-x customize`. But, that didn't give me access to certain variables like `comment-start`. I couldn't access `comment-start` with `M-x customize-option` either.
I decided to look for a way to use `setq` in the current buffer, but couldn't find that so I figured I'd document it here.
# Answer
> 1 votes
`M-: (setq comment-start "/**")`.
Documented in the emacs manual.
Found via this comment.
---
Tags: customize, variables, local-variables
---
|
thread-58979
|
https://emacs.stackexchange.com/questions/58979
|
How could I disable all python shell interaction in emacs
|
2020-06-08T22:48:08.507
|
# Question
Title: How could I disable all python shell interaction in emacs
How could I disable all python shell interaction in emacs on `python-mode`?
Such as:
```
C-c C-z open a python shell
C-c C-c run the content of the buffer in the opened python shell
C-c C-r run the selected region in the python shell
C-c C-c python-shell-send-buffer
C-c C-p run-python
```
`python-shell-send-buffer` locks the emacs and I am unable to use it, hence I want to disalbe it.
I have set those keybindings to `nil` but still they are working.
```
(global-set-key (kbd "C-c C-p") 'nil)
(global-set-key (kbd "C-c C-c") 'nil)
```
# Answer
You have to undefine the bindings in the mode local map, not in the global map.
Something like this if you are using `python mode`:
```
(define-key python-mode-map (kbd "C-c C-p") 'undefined)
```
or if you use `elpy-mode` then try:
```
(define-key elpy-mode-map (kbd "C-c C-p") 'undefined)
```
and similarly for the other keys you want to undefine.
I always use `'undefined` in this situation, I don't know if nil should work as well.
> 1 votes
---
Tags: python
---
|
thread-58882
|
https://emacs.stackexchange.com/questions/58882
|
How to use a classical development setup (file explorer + code + terminal) in Emacs
|
2020-06-03T11:04:43.180
|
# Question
Title: How to use a classical development setup (file explorer + code + terminal) in Emacs
I like using the following setup for development:
```
+--------+---------------------------------+
| . | |
| | Python or JS |
| Dired+ | buffer |
| | (with centaur-tabs) |
| | |
| +---------------------------------+
| . | Shell, Eshell, or iPython |
+------------------------------------------+
```
I'm looking for ways to make this setup more "static" and intuitive. By "static", I mean that, for instance, I'd like the Shell and the Dired buffer not to be replaced nor resized by any action.
Here are examples of problematic use cases that I'm trying to solve:
* when I open a file from the Dired+ buffer, with `o`, I want it opened on the top right window. By default, one time out of two, it gets opened in the "Shell" window, sometimes resizing it at the same time. I don't want that. I found a hack at the post Controlling window locations fo files visited by Dired, but it only works as long as the file in question is above the frame separation on the left (e.g. it works for the first point on the picture above, not for the second)
* When I do `C-h m`, I'd like the \*Help\* buffer to always open in the largest window;
* When using Magit, I'd like the Magit buffer to alway appear in the largest window.
Can anyone suggest a way to solve these problems, or, in a broader sense, an efficient way to use this configuration on Emacs?
# Answer
I achieve something similar by letting tmux handle the window splitting, and telling emacs to only split windows for certain transitory functions like undo tree. Note that this means switching to the terminal version of emacs.
To stop emacs from splitting windows I originally used
```
(setq pop-up-windows nil)
```
and
```
(setq split-window-preferred-function 'no-split-window)
```
and popwin to allow certain windows to appear in the same frame. However not everything plays nicely with popwin and I found that setting a fairly wide window limit achieved the same effect but allowed more things to work.
```
(setq split-window-preferred-function 'split-window-sensibly)
(setq split-width-threshold 100)
```
treemacs can be used in place of dired to give the behaviour you desire. I don't currently use it so I'm not sure of precisely how it interacts with popwin and the split-window functions but it looks ok in my (fairly wide) default emacs window with the above settings.
> 1 votes
---
Tags: dired, window
---
|
thread-58967
|
https://emacs.stackexchange.com/questions/58967
|
How to replace a letter with its numerical alphabetic position?
|
2020-06-08T16:13:08.160
|
# Question
Title: How to replace a letter with its numerical alphabetic position?
I have this code:
```
\author[p]{...}
\author[bc]{...}
\author[p]{...}
\author[l,o]{...}
\author[t,q]{...}
\author[at]{...}
\author[z]{...}
\author[ak]{...}
\author[az]{...}
\author[ah,bq]{...}
...
```
I want to replace all letters in square brackets with their corresponding numeric positions in alphabet, i.e.
```
a --> 1
...
z --> 26
aa --> 27
...
az --> 52
ba --> 53
...
bz --> 78
...
```
How can I do this replacement?
# Answer
> 1 votes
I have solved my problem using vectors. I have written two functions:
* `convert-letter-to-digit`: it takes a letter as argument and give a numnber as output;
* `authors-letters-to-digits`: call `convert-letter-to-digit` and replace letters with corresponding numbers.
To write `convert-letter-to-digit` I was inspiered to vectors in `C` language, so I have defined a vector with my letters in lexicographic order, i.e.
```
(setq v [a b c d e f g h i j k l m n o p q r s t u v w x y z
aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az
ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz
ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz
da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz
ea eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu ev ew ex ey ez])
```
My idea is to check if a given letter is equal to `(aref v j)`, where `j` is from `0` to `(length v)`. If it is true, `j+1` is the position of my letter in `v`.
```
(defun convert-letter-to-digit (letter)
(interactive "p")
;; define vector
(setq v [a b c d e f g h i j k l m n o p q r s t u v w x y z
aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az
ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz
ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz
da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz
ea eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu ev ew ex ey ez])
;; define cell-vector index
(setq j 0)
(while (< j (length v))
;; if letter is equal to j-th element in v, take j+1 as index
(if (string= letter
(aref v j))
(progn
(setq index j)
(setq index (+ index 1)))
nil)
(setq j (+ j 1)))
index)
(defun authors-letters-to-digits ()
(interactive)
;; search "\author[...]{"
(goto-char (point-min))
(while (re-search-forward "\\\\author\\[\\([^]]+\\)\\]{" nil t)
(save-excursion
;; bind replacement inside "[...]"
(setq pos1 (make-marker))
(set-marker pos1 (+ (match-beginning 0) 8))
(setq pos2 (make-marker))
(set-marker pos2 (- (match-end 0) 2))
;; search and replace all letters with their corresponding indices
(goto-char pos1)
(while (re-search-forward "\\<\\([a-z]+\\)\\>" pos2 t)
(replace-match (format "%s" (convert-letter-to-digit (match-string 0))))))))
```
---
Tags: replace, characters, numbers
---
|
thread-52441
|
https://emacs.stackexchange.com/questions/52441
|
How to modify `org-structure-template-alist` after org-mode 9.2?
|
2019-08-31T16:10:18.690
|
# Question
Title: How to modify `org-structure-template-alist` after org-mode 9.2?
I want to append `\n` to specific easy-template
before 9.2 I could:
```
(setq org-structure-template-alist
'(("s" "#+BEGIN_SRC ?\n\n#+END_SRC\n")
("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE\n")
("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE\n")
("v" "#+BEGIN_VERSE\n?\n#+END_VERSE\n")
("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM\n")))
```
the new value looks like this
```
Value: (("a" . "export ascii")
("c" . "center")
("C" . "comment")
("e" . "example")
("E" . "export")
("h" . "export html")
("l" . "export latex")
("q" . "quote")
("s" . "src")
("v" . "verse"))
```
more abstract but I can no longer do what I used to do.
any solution?
# Answer
I also prefer a new line between the begin and end markers, you can customize `org-structure-template-alist` to add a new line between the begin and end markers, such as:
```
(setq org-structure-template-alist
'(("a" . "export ascii\n")
("c" . "center\n")
("C" . "comment\n")
("e" . "example\n")
("E" . "export")
("h" . "export html\n")
("l" . "export latex\n")
("q" . "quote\n")
("s" . "src")
("v" . "verse\n")))
```
after this, when the `C-c C-,` will have a `\n` line between the begin and end markers:
```
#+BEGIN_QUOTE
#+END_QUOTE
```
> 3 votes
---
Tags: org-mode
---
|
thread-45135
|
https://emacs.stackexchange.com/questions/45135
|
Change permanently font size in Aquamacs
|
2018-10-03T14:23:36.087
|
# Question
Title: Change permanently font size in Aquamacs
I have been looking on the web to the existing answers to this question, but non of them works for me.
I would like to change the default font size for all frames in Aquamacs 3.3 GNU Emacs 25.1.1 (x86\_64-apple-darwin14.1.0, NS appkit-1344.72 Version 10.10.2 (Build 14C109)), and I am on OS X 10.11.2. I have tried to insert
```
(set-default-font βTerminus-9β)
```
in the `.emacs` file, but it does not work. Do you guys know how to do this?
Here is what I get if I follow the suggestion by lawlist below, i.e., put `(add-to-list 'default-frame-alist '(font . "Terminus-9"))` in the .emacs file, save the .emacs file and restart Aquamacs. Then, switch to the *Messages* buffer and type: `M-x eval-expression RET (message "%s" (frame-parameters)) RET`:
```
16 environment variables imported from login shell (/bin/bash).
[..]
((tool-bar-position . top) (parent-id) (explicit-name) (display . MacBook-Pro.local) (icon-name) (window-id . 1) (bottom-divider-width . 0) (right-divider-width . 0) (top . 23) (left . 0) (buried-buffer-list) (buffer-list *Messages* *Minibuf-1* *scratch*) (unsplittable) (minibuffer . #<window 4 on *Minibuf-0*>) (width . 201) (height . 48) (name . *Minibuf-1*) (modeline . t) (fringe) (border-color . white) (mouse-color . white) (environment) (visibility . t) (cursor-color . black) (background-mode . light) (display-type . color) (window-system . ns) (fullscreen . maximized) (alpha) (scroll-bar-height . 0) (scroll-bar-width . 15) (cursor-type . box) (auto-lower) (auto-raise) (icon-type) (title) (buffer-predicate) (tool-bar-lines . 1) (menu-bar-lines . 1) (right-fringe . 11) (left-fringe . 3) (line-spacing) (background-color . #ffffff) (foreground-color . #000000) (horizontal-scroll-bars) (vertical-scroll-bars . right) (internal-border-width . 0) (border-width . 0) (font . -*-Monaco-normal-normal-normal-*-12-*-*-*-m-0-iso10646-1) (fontsize . 0) (font-backend mac-ct))
"((tool-bar-position . top) (parent-id) (explicit-name) (display . MacBook-Pro.local) (icon-name) (window-id . 1) (bottom-divider-width . 0) (right-divider-width . 0) (top . 23) (left . 0) (buried-buffer-list) (buffer-list *Messages* *Minibuf-1* *scratch*) (unsplittable) (minibuffer . #<window 4 on *Minibuf-0*>) (width . 201) (height . 48) (name . *Minibuf-1*) (modeline . t) (fringe) (border-color . white) (mouse-color . white) (environment) (visibility . t) (cursor-color . black) (background-mode . light) (display-type . color) (window-system . ns) (fullscreen . maximized) (alpha) (scroll-bar-height . 0) (scroll-bar-width . 15) (cursor-type . box) (auto-lower) (auto-raise) (icon-type) (title) (buffer-predicate) (tool-bar-lines . 1) (menu-bar-lines . 1) (right-fringe . 11) (left-fringe . 3) (line-spacing) (background-color . #ffffff) (foreground-color . #000000) (horizontal-scroll-bars) (vertical-scroll-bars . right) (internal-border-width . 0) (border-width . 0) (font . -*-Monaco-normal-normal-normal-*-12-*-*-*-m-0-iso10646-1) (fontsize . 0) (font-backend mac-ct))"
You can run the command βeval-expressionβ with β₯:
"((tool-bar-position . top) (parent-id) (explicit-name) (display . MacBook-Pro.local) (icon-name) (window-id . 1) (bottom-divider-width . 0) (right-divider-width . 0) (top . 23) (left . 0) (buried-buffer-list) (buffer-list *Messages* *Minibuf-1* *scratch*) (unsplittable) (minibuffer . #<window 4 on *Minibuf-0*>) (width . 201) (height . 48) (name . *Minibuf-1*) (modeline . t) (fringe) (border-color . white) (mouse-color . white) (environment) (visibility . t) (cursor-color . black) (background-mode . light) (display-type . color) (window-system . ns) (fullscreen . maximized) (alpha) (scroll-bar-height . 0) (scroll-bar-width . 15) (cursor-type . box) (auto-lower) (auto-raise) (icon-type) (title) (buffer-predicate) (tool-bar-lines . 1) (menu-bar-lines . 1) (right-fringe . 11) (left-fringe . 3) (line-spacing) (background-color . #ffffff) (foreground-color . #000000) (horizontal-scroll-bars) (vertical-scroll-bars . right) (internal-border-width . 0) (border-width . 0) (font . -*-Monaco-normal-normal-normal-*-12-*-*-*-m-0-iso10646-1) (fontsize . 0) (font-backend mac-ct))"
Making completion list... [2 times]
You can run the command βmake-frameβ with s-N
```
The suggestion does not work, and I have the same font as before.
# Answer
> 3 votes
Personally, I want all Menlo all the time. I achieve this in Aquamacs with:
```
(when window-system
(setq initial-frame-alist nil) ;; Undo Aquamacs forced defaults
(setq default-frame-alist nil) ;; Undo Aquamacs forced defaults
(aquamacs-autoface-mode -1) ;; Use one face (font) everywhere
(set-frame-font "Menlo-12") ;; Set the default font to Menlo size 12
;;(set-default-font "Menlo-12") ;; This would do the same.
)
```
Aquamacs sets some hard defaults that need to be undone before you can be successful changing faces. Setting `initial-frame-alist` and `default-frame-alist` to `nil`, also eliminate problems with themes, Γ la
```
(when window-system
(setq initial-frame-alist nil)
(setq default-frame-alist nil)
(when (featurep 'aquamacs)
(load-theme 'sanityinc-tomorrow-bright t))
[...]
)
```
If you're still having font/face/theme issues, ensure that you don't have settings in a `custom.el` file, or in `~/Library/Preferences/Aquamacs Emacs/Preferences.el` file, that could be conflicting with your `init.el`.
# Answer
> 0 votes
I used James hint (`M-x describe-char`) to get the specs of my preferred font, then I used the value to customize `default-frame-alist` with it `M-x customize-variable`. No need to change anything in `.emacs`.
---
Tags: init-file, fonts, default
---
|
thread-58989
|
https://emacs.stackexchange.com/questions/58989
|
How to type a^b in org-mode?
|
2020-06-09T13:35:39.917
|
# Question
Title: How to type a^b in org-mode?
In an org-mode table, I want to write 2^3, but exporting to html turns it into 2<sup>3</sup>.
I prefer not to use inline verbatim, and I would like to not have a space between the `^` and the other text.
Is there a keyword I can use or some inline pseudo-latex like `\vert`? Finally, if there is a keyword I can use, where are these keywords listed so I can look up the next one?
# Answer
As @rpluim mentions in a comment, setting `org-export-with-sub-superscripts` to nil would disable the special handling of `^` and `_` for subscripts and superscripts. There is one more variable that is relevant (when `org-export-with-sub-superscripts` is `t`) and that is `org-use-sub-superscripts` which can be set to `t` or nil - or it can be set to the value `{}`.
I find the most flexible way to deal with this is to leave `org-export-with-sub-superscripts` to its default `t` value and instead of fiddling with the value of `org-use-sub-superscripts` using lisp in the init file or with file local variables, I use the in-file `#+OPTIONS:` settings. If I write text in a file that uses underscores or carets that I don't want interpreted as subscripts or superscripts, I add this at the top of the file:
```
#+OPTIONS: ^:{}
```
(don't forget to hit `C-c C-c` on that line after you add it: that will make sure it will take effect in this session - otherwise, you'll have to close and reopen the file). That allows me to write
```
#+OPTIONS: ^:{}
* foo
a^b a_b a^{b} a_{b}
```
and have the first two exported literally and the last two exported in super/sub-script form. The expectation here is that I would not want to export `a^{b}` literally because it is not something that would occur at all commonly. That has been my experience: I have never had any need for any other setting (and if I had, I would change the `#+OPTIONS:` setting *in that file only* to read `#+OPTIONS: ^:nil` and forget about it).
There are many settings that you can add to an `#+OPTIONS:` line: it's a fairly flexible way to treat a particular file differently depending on its peculiar needs.
> 3 votes
---
Tags: org-mode, org-export, org-table, formatting
---
|
thread-58993
|
https://emacs.stackexchange.com/questions/58993
|
How color ~code~ on export from org-mode to latex (pdf)?
|
2020-06-09T15:20:03.667
|
# Question
Title: How color ~code~ on export from org-mode to latex (pdf)?
I am trying to export an org file to latex (to pdf via latex) and to make latex color the inline ~code~ parts.
According to the manual (see \[1\] "Defining filters for individual files") this should be possible with the following:
```
#+BIND: org-export-filter-code-functions (tmp-latex-code-filter)
#+BEGIN_SRC emacs-lisp :exports results :results none
(defun tmp-latex-code-filter (text backend info)
"red inline code"
(when (org-export-derived-backend-p backend 'latex)
(format "{\color{red} %s }" text)))
#+END_SRC
#+latex_header: \usepackage{xcolor}
~this is a test~
```
However, it does not work at all and I cannot seem to pin down the problem.
I have tried to c/p the example from the manual (again see \[1\]) but this does not work either (it should remove the striked out text).
```
#+BIND: org-export-filter-strike-through-functions (tmp-f-strike-through)
#+BEGIN_SRC emacs-lisp :exports results :results none
(defun tmp-f-strike-through (s backend info) "")
#+END_SRC
~this is a test~
+this is a test+
```
Does anyone have an idea of how to achieve coloring ~code~ when exporting to latex?
Thank you
Edit: Using the fixed example from your answer, the produced .tex file (minus personal information):
```
% Created 2020-06-10 Wed 00:27
% Intended LaTeX compiler: pdflatex
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{hyperref}
\usepackage{xcolor}
\hypersetup{
pdftitle={},
pdfkeywords={},
pdfsubject={},
pdfcreator={Emacs 26.3 (Org mode 9.1.9)},
pdflang={English}}
\begin{document}
\tableofcontents
\texttt{this is a test}
\sout{this is a test}
\end{document}
```
It is interesting to me, that it simply works for you. I have tried reinstalling emacs. My emacs was at version 25 before, however, there was no change in the output.
I have also tried it with a clean `init.el` and just org mode enabled and it still does not work for me.
Edit2: Here the Emacs and Org mode version outputs
```
GNU Emacs 26.3 (build 2, x86_64-pc-linux-gnu, GTK+ Version 3.22.30) of 2019-09-16
Org mode version 9.1.9 (release_9.1.9-65-g5e4542 @ /usr/share/emacs/26.3/lisp/org/)
```
Edit3: That did the trick, Thank you very much. I added
```
# -*- org-export-allow-bind-keywords: t -*-
```
as first line in my org file (allowing the `#+BIND` keyword for this file only) and now it works perfectly.
\[1\] https://orgmode.org/manual/Advanced-Export-Configuration.html
# Answer
> 2 votes
EDIT/ The `#+BIND:` keyword needs to be turned on as well:
```
(setq org-export-allow-bind-keywords t)
```
I had set that variable and forgotten about it, but the default is nil I think (primarily to protect you from yourself I guess).
The doc string for the variable says:
> Non-nil means BIND keywords can define local variable values. This is a potential security risk, which is why the default value is nil. You can also allow them through local buffer variables.
The last sentence refers to the File local variables mechanism in Emacs. /EDIT
There is one bug in that backslashes in elisp strings have to be escaped:
```
(defun tmp-latex-code-filter (text backend info)
"red inline code"
(when (org-export-derived-backend-p backend 'latex)
(format "{\\color{red} %s }" text))
```
but other than that, both of the examples work fine for me - when I export the following to PDF:
```
#+BIND: org-export-filter-strike-through-functions (tmp-f-strike-through)
#+BIND: org-export-filter-code-functions (tmp-latex-code-filter)
#+BEGIN_SRC emacs-lisp :exports results :results none
(defun tmp-latex-code-filter (text backend info)
"red inline code"
(when (org-export-derived-backend-p backend 'latex)
(format "{\\color{red} %s }" text)))
#+END_SRC
#+latex_header: \usepackage{xcolor}
#+BEGIN_SRC emacs-lisp :exports results :results none
(defun tmp-f-strike-through (s backend info) "")
#+END_SRC
~this is a test~
+this is a test+
```
I get
and the (slightly sanitized) tex file looks like this:
```
% Created 2020-06-09 Tue 12:54
% Intended LaTeX compiler: pdflatex
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{xcolor}
\date{\today}
\title{}
\begin{document}
{\color{red} \texttt{this is a test} }
\end{document}
```
---
Tags: org-mode, org-export, latex
---
|
thread-48324
|
https://emacs.stackexchange.com/questions/48324
|
Regexps: 2 strings without a character in between; 2 chars w/o a string in between - Stack overflow in regexp mapper
|
2019-03-14T04:33:41.067
|
# Question
Title: Regexps: 2 strings without a character in between; 2 chars w/o a string in between - Stack overflow in regexp mapper
I am trying to search through some babyl files for errors. The files are email messages that appear between `^L` and `^_` (Control-L and Control-\_), with a special string `"\*\*\* EOOH \*\*\*"` in between, marking the end of the header. I want to use regexps to find:
```
EOOH[^^L]*EOOH
```
ie two `EOOH`'s with no Control-L in between, but when I use that syntax I get the stack overflow. (Thatβs with `search-forward-regexp` or `isearch-forward-regexp`. And by `^L` in the brackets I do mean Control-q Control-l.)
I would also like to find two Control-L's with no `EOOH` in between, sort of like this, though it's wrong syntax:
```
^L[^"EOOH"]*^L
```
Can anyone help?
# Answer
You're victim of Emacs's use of a backtracking matcher for the regular expression. You can try and reduce the use of stack in the backtracking with the following:
```
EOOH\([^^LE]*E\)+OOH
```
This will reduce the stack use from "one push per char" to "one push per E" and may be sufficient to stay within the limit of the available stack space. The way this works is that the backtracking matcher has ad-hoc optimization for the case where a `*` or `+` repetition is followed by a character that can't match the beginning of that repetition (i.e. the first char matched by the body of the loop is mutually exclusive with the first char matched after the loop) in which case we know there's no point pushing a backtracking point onto the stack.
The limits of this kind of hacking become obvious when you get to the second part of your question: it's possible to define a regexp that matches "the negation of "EOOH" but it's a real pain in the rear. You're better off writing Elisp code for that. E.g.
```
(let ((last-was-EOOH nil))
(while (re-search-forward "\^L\\|EOOH\\(\\)" nil t)
(let ((is-EOOH (match-beginning 1)))
(cond
((and is-EOOH last-was-EOOH)
(message "Found two EOOH in a row"))
((not (or is-EOOH last-was-EOOH))
(message "Found two ^L in a row")))
(setq last-was-EOOH is-EOOH))))
```
> 4 votes
# Answer
Just because I was interested after reading Stefan's answer, I was able to create a regexp for:
`^L<some-characters-but-not-EOOH>^_`
This works:
`^L\([^E^L]*E\([^O^L]\|O[^O^L]\|OO[^H^L]\)\)+[^E^L]*.\{0,3\}^_`
> 1 votes
---
Tags: regular-expressions
---
|
thread-59001
|
https://emacs.stackexchange.com/questions/59001
|
Unable to load my CSS during org-publish-project
|
2020-06-09T18:18:09.180
|
# Question
Title: Unable to load my CSS during org-publish-project
I want to write an static website using `org-mode` and publish it from `emacs`. For this, I followed the tutorial I found in `org-mode` site.
My site directory tree is as follows:
```
~/org
css/
stylesheet.css
index.org
```
My `org-publish-project-alist` looks as follows:
```
(setq org-publish-project-alist
'(
("org-notes"
:base-directory "~/org"
:base-extension "org"
:publishing-directory "~/public_html"
:recursive t
:publishing-function org-html-publish-to-html
:headline-levels 4 ; Just the default for this project.
:auto-preamble t
)
("org-static"
:base-directory "~/org"
:base-extension "css\\|js\\|png\\|jpg\\|gif\\|pdf\\|mp3\\|ogg\\|swf"
:publishing-directory "~/public_html"
:recursive t
:publishing-function org-publish-attachment
)
("org" :components ("org-notes" "org-static"))
))
```
I have not been able to link my `stylesheet.css` in the `index.html` generated. This is how I tried to set the local variable `org-export-html-style` at the bottom of `index.org`
```
# Local Variables:
# org-export-html-style: "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/stylesheet.css\" />"
# End:
```
What am I missing?
# Answer
Try adding this line to the top of the org file:
```
#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="./css/stylesheet.css" />
```
Reference: https://orgmode.org/manual/CSS-support.html
> 2 votes
---
Tags: org-mode, org-publish
---
|
thread-59007
|
https://emacs.stackexchange.com/questions/59007
|
Export resume.org to both pdf and html
|
2020-06-10T00:58:40.040
|
# Question
Title: Export resume.org to both pdf and html
I've been maintaining my resume in orgmode for some time now, with export to pdf. I just decided it would be nice to also export to html which has uncovered a problem.
I'm using headings to list my previous jobs, with a macro that puts a date range on the same line, but right aligned. The macro uses latex to do the magic, which you can see below. I've also looked at replacing the macro with a tag, but tags don't seem to allow spaces or dashes.
Wanted to see if anyone here has any smart tricks for the org file so that it will export to both pdf and html nicely.
Here's a MWE of my resume org file:
```
#+OPTIONS: toc:nil num:nil
#+MACRO: date \hfill\normalfont{\small $1}
* Job 1 {{{date(July 2019 -- Dec 2019)}}}
/Description of job/
- This is the macro solution I am currently using. It doesn't export to html very nicely...
* Job 2 :Jul2019Dec2019:
/Description of second job/
- Here I am using a tag for the date
- Problem is that I can't put spaces or dashes in the tag...
```
Here's the pdf output: https://i.stack.imgur.com/kP9zb.jpg
Here's the html output: https://i.stack.imgur.com/zfrxx.jpg
# Answer
> 2 votes
I would continue using the macro. You can use markup inside the macro that expands differently for HTML export than it does for PDF export. For example, as a first approximation, this will allow you to get the dates in the HTML output, although they are not nicely formatted - but it's a beginning:
```
#+MACRO: date @@latex: \hfill\normalfont{\small $1} @@ @@html: $1 @@
```
As the next approximation, I would (as a naive HTML/CSS simpleton) add a span around the date and then try to apply some CSS to it, perhaps something like this:
```
#+MACRO: date @@latex: \hfill\normalfont{\small $1} @@ @@html: <span class="dates">$1</span> @@
```
but you should take that last suggestion with a large grain of salt and maybe ask another question to this or possible a different SE where they can guide you through the HTML/CSS thickets.
*EDIT*: Here is a complete Org mode file that should do what you want:
```
#+OPTIONS: toc:nil num:nil
#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="./foo12.css" />
#+MACRO: date @@latex: \hfill\normalfont{\small $1} @@ @@html: <span class="right">$1</span> @@
* Job 1 {{{date(July 2019 -- Dec 2019)}}}
/Description of job/
- This is the macro solution I am currently using.
* CSS :noexport:
#+begin_src css :tangle yes
.right{
float:right;
}
.left{
float:left;
}
#+end_src
```
The underlying assumption is that this file is called `foo12.org`. It uses a CSS style file which can be generated from the source block in the CSS section by tangling it: `C-c C-v t` while you are in the code block. That then produces a CSS file, called `foo12.css` which in turn is used as a style file when you export to HTML, because it is mentioned in the `#+HTML_HEAD:` line. If you use a different name for the Org mode file, you will need to adjust the file name in the `#+HTML_HEAD:` line. Note that the CSS section is tagged `:noexport` so it will not appear in the exported file at all.
---
Tags: org-mode, org-export, html, pdf
---
|
thread-58985
|
https://emacs.stackexchange.com/questions/58985
|
Current week in org agenda (starting today and ending next Sunday)
|
2020-06-09T08:19:25.410
|
# Question
Title: Current week in org agenda (starting today and ending next Sunday)
I want my agenda to show the current week starting from today until the end of the week, Sunday. How do I go about achieving this?
The code
```
(setq org-agenda-custom-commands '(("w" "Current week"
(agenda "" ((org-agenda-span 'week)
(org-agenda-start-day "-0d")
(org-agenda-start-on-weekday 1))))))
```
Shows the current week starting from Monday rather than the current day, if I set `org-agenda-start-on-weekday` to `nil` then the agenda shows until next Tuesday (if today is Tuesday for example).
NOTE: I can compute the number of days from today until next Monday (though I am not 100% sure how to do it in elisp) and set `org-agenda-span` accordingly, but I don't think I can do it as part of `org-agenda-custom-commands`.
# Answer
> 1 votes
That can be done easily if you can compute the days between today and next sunday, something you said you already achieved, which can be done in several ways and I find to be the trickiest part.
Adding this to your custom agenda definitions (and re-evaluating it) will do it:
```
(setq org-agenda-custom-commands
'(("s" "From today to next sunday"
((agenda ""
((org-agenda-start-on-weekday nil)
(org-agenda-span (my/days-to-next-sunday))))))
)
;; ... other commands here
)
```
`my/days-to-next-sunday` should return the number of days between today and next Sunday you want to include in the agenda, I do assume that you want today included, so there is no need to look back 1 day in custom command definition.
Key `s` to call it from the agenda menu can be changed to anything you like.
---
As an aside example, taking the bare-bones, lazy (*and not* the better/proper) lane, given that `(format-time-string "%u")` will return the current day of week, and those run from 0 (Sunday) to 6 (Saturday) this will return the number of days in between today and Sunday, today included. Please, spare any possible dumb bug, it's untested code just to show the idea.
```
(defun my/days-to-next-sunday()
(let ((dayspan 0)
(today (string-to-number (format-time-string "%u"))))
(cond
((> today 0)
; from today till sunday, today included
(setq dayspan (- 8 today)))
((= today 0)
; sunday to sunday
(setq dayspan 8)))))
```
Probably I'd rely on calc or system `date` to find the dayspan if I were to write a more reusable way to find intervals, but it'll make the example harder to understand.
---
Tags: org-agenda
---
|
thread-59014
|
https://emacs.stackexchange.com/questions/59014
|
clocktable report - not display file without clocked time
|
2020-06-10T09:03:52.437
|
# Question
Title: clocktable report - not display file without clocked time
is-it possible thath clocktable report not display file without clocked time ?
For example I have :
```
#+CAPTION: Clock summary at [2020-06-10 mer. 10:53], for mercredi, juin 10, 2020.
| File | Headline | Time |
|---------------------------------------------+-----------------------+--------|
| | ALL *Total time* | *4:03* |
|---------------------------------------------+-----------------------+--------|
| 20.04-forecast.org | *File time* | *0:00* |
|---------------------------------------------+-----------------------+--------|
| 2006-systeme.org | *File time* | *0:00* |
|---------------------------------------------+-----------------------+--------|
| 2020-05-12.org | *File time* | *0:00* |
|---------------------------------------------+-----------------------+--------|
And i don't want to display line with 0.00 that don't have value for today.
Thanks for your feedback.
Best regards.
```
# Answer
> 1 votes
That work with `:fileskip0 t`
```
#+BEGIN: clocktable :scope agenda :fileskip0 t :maxlevel 1 :block today
#+CAPTION: Clock summary at [2020-06-10 mer. 11:15], for mercredi, juin 10, 2020.
| File | Headline | Time |
|--------------+-----------------------+--------|
| | ALL *Total time* | *4:03* |
|--------------+-----------------------+--------|
| test1.org | *File time* | *0:01* |
| | Analyse | 0:01 |
|--------------+-----------------------+--------|
| test2.org | *File time* | *4:02* |
| | Tache en cours [6/16] | 4:02 |
```
---
Tags: org-mode, org-clock, org-clock-table
---
|
thread-59017
|
https://emacs.stackexchange.com/questions/59017
|
Non integer powers of 10 in algebraic mode in calc
|
2020-06-10T10:44:03.470
|
# Question
Title: Non integer powers of 10 in algebraic mode in calc
How should one type numbers like 10^(-2.5) using the 1e... notation in calc using algebraic-mode ? ATM, `1e-2.5` is parsed as (1e-2)\*0.5 and indeed evaluates to 5e-3 instead of 3.16e-3.
# Answer
> 1 votes
Use algebraic entry: `'1*10^-2.5`. This is also necessary when using an entry radix of 15 or higher (such as hexadecimal), where `e` is a valid digit.
---
Tags: calc
---
|
thread-58878
|
https://emacs.stackexchange.com/questions/58878
|
Mysterious highlight in emacs
|
2020-06-03T07:28:50.703
|
# Question
Title: Mysterious highlight in emacs
Recently, I change my laptop from old Thinkpad to newer laptop with much larger touchpad. I've found that I frequently touch the sensitive touchpad while I'm using emacs. And with some mysterious combination, very often there will be a highlight appear on the emacs buffer. The highlight is persist. Cannot be removed by navigating cursor or mouse click. It's not emacs selection mark. The only way I can remove it is to close the buffer and reload the file.
This is very annoying. Anybody know what is it, how to remove it, and best if I can prevent it from occur in the first place.
# Answer
It's the secondary selection. Clicking and dragging sets the primary selection, and middle click pastes from that selection. Holding alt while clicking and dragging sets the secondary selection, and `M-mouse-2` pastes from it. Very few applications use the secondary selection any more, but it's quite handy when you have two things to copy and paste. See section 12.3.3 Secondary Selection in the Emacs manual for more information.
There's no command to cancel the secondary selection, but if you left-click with `Alt` (`M-mouse-1`), it'll make the secondary selection empty.
> 10 votes
# Answer
I use package `disable-mouse`:
```
(package-install "use-package") ; once, if not already installed
(require 'use-package)
(use-package disable-mouse
:ensure t
:diminish disable-mouse-global-mode
:commands global-disable-mouse-mode
:init (global-disable-mouse-mode))
```
> 1 votes
---
Tags: highlighting, mark
---
|
thread-57484
|
https://emacs.stackexchange.com/questions/57484
|
List all empty checkboxes in files
|
2020-03-31T09:13:47.403
|
# Question
Title: List all empty checkboxes in files
Is there any easy way, including installing a package, to list all waiting checkboxes in all the files in the directory?
So far I do the following for the checkboxes in a file:
```
M-x occur - \[ \]
```
This is for the checkboxes in the whole directory and all files:
```
M-x rgrep \- \[ \]
```
**rgrep** works, but it includes a whole bunch of arguments and it's slow.
Is there any nonobvious and easy solution?
# Answer
> 1 votes
You can try `M-x helm-do-grep-ag`, and if you're looking for speed, I'd suggest using it with the `rg` command:
```
(require 'helm-grep)
(setq helm-grep-ag-command
"rg --color=always --smart-case --no-heading --line-number %s %s %s")
```
```
1. M-x helm-do-grep-ag
2. - \[\ ]
3. TAB
4. Select "Save results in grep buffer" and press RET
```
---
Tags: org-mode, grep
---
|
thread-59024
|
https://emacs.stackexchange.com/questions/59024
|
quote vs ' in customization file
|
2020-06-10T19:58:06.780
|
# Question
Title: quote vs ' in customization file
I sync my config between several different machines using git. Setting options via the `customize-variable` interface, some of my computers use `quote`, while others use `'`. As a consequence, my git commits include lots of bouncing back and forth like this:
```
'(ess-r-prettify-symbols
- (quote
- (("<-" 129032)
+ '(("<-" 129032)
("->" 32
```
I'm not editing these values by hand, so something in Emacs is deciding whether or not to use the word or symbol for quote. It's driving me batty - how do I tell Emacs to always use one or the other?
# Answer
\[Just expanding the comment into an answer, so I can get some internet points from Tyler :-) \]
I guessed that different versions of emacs might have different implementations of `customize`: some using `quote` explicitly and others using `'`, so the resulting custom files would be at war with each other. I guess I guessed right :-) (well, not really as @rpluim points out in a comment).
> 3 votes
---
Tags: customize
---
|
thread-59025
|
https://emacs.stackexchange.com/questions/59025
|
How can I add my own key-bindings to magit transient state?
|
2020-06-10T20:31:53.877
|
# Question
Title: How can I add my own key-bindings to magit transient state?
Magit defines a transient state
```
(transient-define-prefix magit-dispatch ()
"Invoke a Magit command from a list of available commands."
["Transient and dwim commands"
[("A" "Apply" magit-cherry-pick)
...
["Essential commands"
:if-derived magit-mode
...
("C-h m" " show all key bindings" describe-mode)])
```
I would like to add `<escape>` and `<q>` as key-bindings to exit the transient state.
If I edit `magit.el` directly, I can achieve what I want:
```
(transient-define-prefix magit-dispatch ()
"Invoke a Magit command from a list of available commands."
["Transient and dwim commands"
[("A" "Apply" magit-cherry-pick)
...
["Essential commands"
:if-derived magit-mode
...
("<escape>" "quit transient state" transient-quit-one) ; <--- I added
("q" " quit transient state" transient-quit-one) ; <--- these
("C-h m" " show all key bindings" describe-mode)])
```
However, unless I can upstream my changes, this won't persist if I reload my packages from elpa, etc.
How can I add these key-bindings in my own `init.el` so they augment the transient state magit defines?
# Answer
> 2 votes
I've never actually used the transient package before (which is what magit uses to create these cool menus), so instead of giving you the answer, I'll describe how to find it.
First, take a look at the definition of the the `transient-define-prefix` macro. There's no direct way to go to a macro definition, so start by visiting the source for `magit-dispatch`; type `C-h f magit-dispatch <RET>` to visit the documentation for the function, then click the source link. Then type `M-.` on the call to the macro to jump to its definition.
This macro defines the name you give it to be a function which implements the menu the other arguments define. The macro parses those objects and then stores them alongside the function definition under a different property name. You can retrieve the menu definition with `(get 'magit-dispatch 'transient--layout)`. The double-dash in the name is a naming convention meaning that this data is considered private to the transient package, so there is some risk to modifying this data. The exact format is not explicitly defined, and there may or may not be useful functions for adding things to it. It looks like a set of nested vectors, so you might end up just appending some new vectors to the end of it.
With that knowledge you may be able to find functions that retrieve the value stored in this property, and hopefully one will modify it. I recommend starting with `transient-insert-suffix`.
As an aside, I note that the transient package has an info manual, and chapter 4 is titled "Modifying Existing Transients", which sounds relevant to your interests.
---
Tags: key-bindings, magit
---
|
thread-58992
|
https://emacs.stackexchange.com/questions/58992
|
Apply settings in .dir-locals.el to both c and c++ major modes
|
2020-06-09T15:03:42.970
|
# Question
Title: Apply settings in .dir-locals.el to both c and c++ major modes
Is there a way to specify the same settings for `c-mode` and `c++-mode` without repeating the alist? I have:
```
((c-mode . ((comment-start . "/* ")
(comment-end . " */")
(comment-padding . 0))))
```
and would like to avoid:
```
((c-mode . ((comment-start . "/* ")
(comment-end . " */")
(comment-padding . 0)))
(c++-mode . ((comment-start . "/* ")
(comment-end . " */")
(comment-padding . 0))))
```
# Answer
Not as such (AFAIK).
However, both those modes derive from `prog-mode` which *might* be fine to target for this directory.
```
((prog-mode . ((comment-start . "/* ")
(comment-end . " */")
(comment-padding . 0))))
```
Or you could even use `nil`, which applies to *every* mode (again, *maybe* that's ok in practice).
```
((nil . ((comment-start . "/* ")
(comment-end . " */")
(comment-padding . 0))))
```
Otherwise, I think you just have to live with the duplication.
Unless it's just for you, in which case you might be happy with
```
((c-mode . ((eval . (my-comment-settings))))
(c++-mode . ((eval . (my-comment-settings)))))
```
calling some `my-comment-settings` function defined in your init file.
```
(defun my-comment-settings ()
"My comment settings."
(setq-local comment-start "/* ")
(setq-local comment-end " */")
(setq-local comment-padding 0))
```
> 3 votes
---
Tags: major-mode, directory-local-variables, alists
---
|
thread-59030
|
https://emacs.stackexchange.com/questions/59030
|
How can I save files in Emacs on OSX and preserve the file creation date?
|
2020-06-11T10:01:32.570
|
# Question
Title: How can I save files in Emacs on OSX and preserve the file creation date?
Let's say I create a file called foo.txt in emacs. The time is 12:00. It's currently empty.
At 12:10, I use emacs to add text to the file. I save it. The new timestamp given with `getfileinfo` is
```
created: 06/11/2020 12:10:00
modified: 06/11/2020 12:10:00
```
Obviously this isn't correct, and the created time should be 12:00 and the modified time should be 12:10. How can this problem be solved? As mentioned in the title I'm using a mac, specifically Mojave version 10.14, and emacs version 26.3.
# Answer
> 1 votes
Found the solution here.
You need `(setq backup-by-copying t)` in your emacs configuration file.
This only applies to OSX and Windows.
---
Tags: osx, saving
---
|
thread-41521
|
https://emacs.stackexchange.com/questions/41521
|
Magit error during commit on Windows
|
2018-05-18T00:18:20.773
|
# Question
Title: Magit error during commit on Windows
I have been getting an error when trying to commit using magit. I stage my change with `a`, then on commit `cc` I get the message:
```
Opening output file: No such file or directory, c:/Users/myuname/.emacs.d/server/server
```
If I ignore the message and attempt the commit `cc` again I get the message:
```
There was a problem with the editor '"c:/ProgramData/chocolately/lib/emacs64/tools/emacs/bin/emacsclient.exe"'. ... [Hit $ to see buffer magit-process: .emacs.d for details]
```
After pressing `$` I see the magit process buffer containing:
```
1 C:/ProgramData/chocolately/lib/emacs64/tools/emacs/bin/emacsclient.exe ... "commit" "--"
error: There was a problem with the editor '"c:/ProgramData/chocolately/lib/emacs64/tools/emacs/bin/emacsclient.exe"'. Please suply the message using either -m or -F option.
```
I've found similar problems around the web (such as this one) but they usually state that it is a bug which has been fixed in more recent versions of emacs/magit. I'm running versions that are more recent than when these answers were posted, so they haven't been helpful to me.
My current system is:
* Windows 10
* GNU Emacs 25.3.1 (x86\_64-mingw32) of 2017-09-13 (emacs64 package from chocolatey)
* Magit 20180517.1345, Git 2.17.0.windows.1, Emacs 25.2.1, windows-nt
Please let me know if there is any other useful information that I can provide. I'm not very experienced with debugging in emacs, so please excuse anything basic that I've overlooked.
---
EDIT
Here is the with-editor-debug buffer:
```
with-editor: c:/Users/jrm978/.emacs.d/elpa/with-editor-20180414.757/with-editor.el
emacs: c:/ProgramData/chocolatey/lib/emacs64/tools/emacs/bin/emacs (25.3.1)
system:
system-type: windows-nt
system-configuration: x86_64-w64-mingw32
system-configuration-options: --prefix=/tmp/emacs --without-imagemagick --without-dbus --with-modules 'CFLAGS=-O2 -g0'
server:
server-running-p: nil
server-process: #<process server>
server-use-tcp: t
server-name: server
server-socket-dir: nil
WARNING: not an accessible directory
server-auth-dir: ~\.emacs.d\server\
ERROR: not an accessible directory
with-editor-emacsclient-executable:
value: c:/ProgramData/chocolatey/lib/emacs64/tools/emacs/bin/emacsclient.exe (25.3)
default: c:/ProgramData/chocolatey/lib/emacs64/tools/emacs/bin/emacsclient.exe (25.3)
funcall: c:/ProgramData/chocolatey/lib/emacs64/tools/emacs/bin/emacsclient.exe (25.3)
path:
$PATH: "C:\\Program Files\\ImageMagick-7.0.7-Q16;C:\\Program Files\\Microsoft HPC Pack 2008 R2\\Bin\\;C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;;C:\\Program Files\\Tcl\\bin;C:\\ProgramData\\Oracle\\Java\\javapath;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files\\MiKTeX 2.9\\miktex\\bin\\x64\\;C:\\ProgramData\\chocolatey\\bin;C:\\Program Files (x86)\\vim\\vim80;C:\\tools\\miniconda3;C:\\tools\\miniconda3\\Scripts;C:\\Program Files\\OpenSees;C:\\ProgramData\\chocolatey\\lib\\mpv.install\\tools;C:\\Program Files\\Git\\cmd;C:\\SIMULIA\\Abaqus\\Commands;C:\\Strawberry\\c\\bin;C:\\Strawberry\\perl\\site\\bin;C:\\Strawberry\\perl\\bin;C:\\Users\\jrm978\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\jrm978\\AppData\\Local\\Pandoc\\;C:\\Users\\jrm978\\hunspell\\bin;C:\\Program Files\\Oracle\\VirtualBox;;C:\\Program Files (x86)\\clisp-2.49"
exec-path: (c:/Program Files/ImageMagick-7.0.7-Q16 C:/Program Files/Microsoft HPC Pack 2008 R2/Bin/ C:/Program Files (x86)/Common Files/Oracle/Java/javapath . C:/Program Files/Tcl/bin C:/ProgramData/Oracle/Java/javapath C:/WINDOWS/system32 C:/WINDOWS C:/WINDOWS/System32/Wbem C:/WINDOWS/System32/WindowsPowerShell/v1.0/ C:/Program Files/MiKTeX 2.9/miktex/bin/x64/ C:/ProgramData/chocolatey/bin C:/Program Files (x86)/vim/vim80 C:/tools/miniconda3 C:/tools/miniconda3/Scripts C:/Program Files/OpenSees C:/ProgramData/chocolatey/lib/mpv.install/tools C:/Program Files/Git/cmd C:/SIMULIA/Abaqus/Commands C:/Strawberry/c/bin C:/Strawberry/perl/site/bin C:/Strawberry/perl/bin C:/Users/jrm978/AppData/Local/Microsoft/WindowsApps C:/Users/jrm978/AppData/Local/Pandoc/ C:/Users/jrm978/hunspell/bin C:/Program Files/Oracle/VirtualBox . C:/Program Files (x86)/clisp-2.49 c:/ProgramData/chocolatey/lib/emacs64/tools/emacs/libexec/emacs/25.3/x86_64-w64-mingw32)
with-editor-emacsclient-path:
c:/ProgramData/chocolatey/lib/emacs64/tools/emacs/bin (t)
c:/ProgramData/chocolatey/lib/emacs64/tools/emacs/bin/emacsclient.exe (25.3)
c:/Program Files/ImageMagick-7.0.7-Q16 (t)
C:/Program Files/Microsoft HPC Pack 2008 R2/Bin/ (t)
C:/Program Files (x86)/Common Files/Oracle/Java/javapath (t)
C:/Program Files/Tcl/bin (t)
C:/ProgramData/Oracle/Java/javapath (t)
C:/WINDOWS/system32 (t)
C:/WINDOWS (t)
C:/WINDOWS/System32/Wbem (t)
C:/WINDOWS/System32/WindowsPowerShell/v1.0/ (t)
C:/Program Files/MiKTeX 2.9/miktex/bin/x64/ (t)
C:/ProgramData/chocolatey/bin (t)
C:/ProgramData/chocolatey/bin/emacsclient.exe (25.3)
C:/Program Files (x86)/vim/vim80 (t)
C:/tools/miniconda3 (t)
C:/tools/miniconda3/Scripts (t)
C:/Program Files/OpenSees (t)
C:/ProgramData/chocolatey/lib/mpv.install/tools (t)
C:/Program Files/Git/cmd (t)
C:/SIMULIA/Abaqus/Commands (t)
C:/Strawberry/c/bin (t)
C:/Strawberry/perl/site/bin (t)
C:/Strawberry/perl/bin (t)
C:/Users/jrm978/AppData/Local/Microsoft/WindowsApps (t)
C:/Users/jrm978/AppData/Local/Pandoc/ (t)
C:/Users/jrm978/hunspell/bin (t)
C:/Program Files/Oracle/VirtualBox (t)
. (t)
C:/Program Files (x86)/clisp-2.49 (t)
c:/ProgramData/chocolatey/lib/emacs64/tools/emacs/libexec/emacs/25.3/x86_64-w64-mingw32 (t)
```
With `M-x toggle-debug-on-error` nothing happens.
Regarding the different versions, I added the magit package when using 25.2.1, but after hitting this problem updated first emacs and then the magit package. I just removed and reinstalled magit. `M-x magit-version` now gives:
* Magit 20180517.1345, Git 2.17.0.windows.1, Emacs 25.3.1, windows-nt
But the problem persists.
# Answer
After checking the results of `M-x with-editor-debug` it is evident that emacs could not access `~\.emacs.d\server`
The problem was that this directory didn't exist. After creating this as an empty directory the problem is solved.
> 3 votes
# Answer
I had the same issue on macOS 10.15.5 Catalina. From a quick debug session I discovered that the `server` directory was also missing on my machine, like the other answer mentions.
I created it by hand, but this didnβt fix the issue.
In my case I had a Git project setup with submodules, and the submodule had `.git/gitdir` & `.git/gitfile` configurations with relative paths that were no longer present (due to a refactoring which also moved directories around). The path configured there was the same one as in the Magit error message, so I deleted the files and now I can commit again.
Youβll eventually have to check your Git submodule configuration afterwards.
> 0 votes
---
Tags: magit
---
|
thread-59036
|
https://emacs.stackexchange.com/questions/59036
|
split-string: splitting on backslash character
|
2020-06-11T18:52:56.353
|
# Question
Title: split-string: splitting on backslash character
I intend to apply the `split-string` function to the following string
```
"\ghjky\dfsgi\45fdj\854f"
```
using the character `"\"` as a separator in order to get the list `("ghjky" "dfsgi" "45fdj" "854f")`.
I could use the following function
```
(split-string "\ghjky\dfsgi\45fdj\854f" "\" t)
;; return: forward-sexp: Scan error: "Unbalanced parentheses"
```
but it does not work, as the separator is not recognized
Then I try
```
(split-string "\ghjky\dfsgi\45fdj\854f" "\\" t)
;; return: split-string: Invalid regexp: "Trailing backslash"
```
but it still doesn't work
```
(split-string "\ghjky\dfsgi\45fdj\854f" "\\\\" t)
;; ("Ghjky^?fsgi%fdj854f")
```
Other attempts:
```
(defun split-now (astr)
(interactive "sEnter a string: ")
(split-string astr "\\\\" t))
(split-now "th\jki\fgt\y")
;; return: ("thjki^Lgty")
```
What is the correct procedure?
# Answer
Backslash is special in elisp strings, and even more special in regexes. You need to double it in double quoted strings (otherwise e.g. `\4` is interpreted as `C-d`), and quadruple it in regexes to match literally:
```
(split-string "\\ghjky\\dfsgi\\45fdj\\854f" "\\\\" t)
; or
(split-string "\\ghjky\\dfsgi\\45fdj\\854f" (regexp-quote "\\") t)
```
The double backslashes are only needed when entering the string in double quotes literally in the code. After running this:
```
(call-interactively
(lambda (string) "No doubling of backslashes needed"
(interactive "s")
(split-string string "\\\\" t)))
```
you can enter the string as is with single backslashes.
> 2 votes
---
Tags: string, backslash
---
|
thread-59023
|
https://emacs.stackexchange.com/questions/59023
|
Problem with Flycheck and Python
|
2020-06-10T19:04:37.683
|
# Question
Title: Problem with Flycheck and Python
I think that this is a newbie question, but here it goes:
I have installed Flycheck just as in the official page. Therefore, in my `.emacs` file I added the following lines (after installing):
```
(package-install 'flycheck)
(global-flycheck-mode)
(package-install 'exec-path-from-shell)
(exec-path-from-shell-initialize)
```
However, when I open a `.py` file, I get this error message:
> Warning \[flymake seila.py\]: Disabling backend python-flymake because (error Cannot find a suitable checker)
>
> Warning \[flymake seila.py\]: Disabling backend flymake-proc-legacy-flymake because (error Canβt find a suitable init function)
How would I fix these errors? Seems to me that some file/configuration is missing. I've found this (partial) solution that makes the second error disappear, but It does not seem to be an effective solution.
Thanks in advance.
# Answer
> 0 votes
Your warning messages (notice that they say "warning" rather than "error") come from `flymake` which is a package similar to `flycheck` except it comes bundled with Emacs. So those messages are not directly related to your `flycheck` config.
---
Tags: python, flycheck
---
|
thread-59039
|
https://emacs.stackexchange.com/questions/59039
|
Is it possible to disable flycheckspell for specific file names in text-mode?
|
2020-06-11T21:31:28.900
|
# Question
Title: Is it possible to disable flycheckspell for specific file names in text-mode?
I am actively using `flyspell` on all text files under `text-mode`.
For example: Under `requirements.txt` text file I am keeping my python packages where I do not need to enable `flyspell`. But since it is a text file flyspell keep does its checks. So I want to disable flyspell for specific file names like: `requirements.txt` and so on. It also enable in `yaml-mode` even I did not enable it.
My setup:
```
(flyspell-mode 1)
(setq flyspell-issue-message-flag nil
ispell-local-dictionary "en_US"
ispell-program-name "aspell"
ispell-extra-args '("--sug-mode=ultra"))
(dolist (hook '(text-mode-hook))
(add-hook hook (lambda () (flyspell-mode 1))))
(dolist (hook '(change-log-mode-hook log-edit-mode-hook))
(add-hook hook (lambda () (flyspell-mode -1))))
```
# Answer
You can write a function that turns off the mode if the filename matches a list and add the function to the `find-file-hook`. Something like this:
```
(defvar no-flyspell-list '("requirements.txt"))
(defun turn-off-flyspell-if-match ()
(if (member (file-name-nondirectory (buffer-file-name)) no-flyspell-list)
(flyspell-mode -1)))
(add-hook 'find-file-hook #'turn-off-flyspell-if-match)
```
As I mentioned in a comment, `yaml-mode` is derived from `text-mode` so the `text-mode-hook` is run and it turns on `flyspell-mode`. But the derived mode hook, `yaml-mode-hook` is run *after* the parent mode hook, so you can add a turn-off function to it:
```
(add-hook `yaml-mode-hook (lambda () (flyspell-mode -1)))
```
Or add it to your list of other modes (`change-log-mode-hook`, `log-edit-mode-hook`) where you turn off `flyspell-mode`.
> 1 votes
---
Tags: flyspell
---
|
thread-58167
|
https://emacs.stackexchange.com/questions/58167
|
org-sort expands all subtrees and drawers
|
2020-04-29T18:09:37.987
|
# Question
Title: org-sort expands all subtrees and drawers
When I use `org-sort` (`Ctrl-^`) all the to-be-sorted subtrees are expanded including their properties. I kind of lose orientation. I have to collapse them manually again or use overview (`Shift-Tab`) and expand manually from there.
* Is this a standard behavior?
I tried a fresh emacs install on a new machine and this behaves the same. So I assume the answer here is "yes".
* Can I change this behavior somehow? The focus on a subtree should not change when sorting or archiving.
# Answer
I have not found a way to disable that behaviour, but I found a way to not loose orientation while sorting.
I modified this answer and added a hook to run after every sorting of headings. This basically automates the folding I had to do manually every time after sorting.
```
(defun ess/org-show-just-me (&rest _)
"Fold all other trees, then show direct children of current org-heading."
(interactive)
(org-overview)
(org-reveal)
(org-show-children))
(add-hook 'org-after-sorting-entries-or-items-hook 'ess/org-show-just-me)
```
I don't understand the code fully ( eg. &rest\_), but for now it works.
> 0 votes
---
Tags: org-mode
---
|
thread-59048
|
https://emacs.stackexchange.com/questions/59048
|
Can I set a timer to run at 7am tomorrow?
|
2020-06-12T14:52:47.657
|
# Question
Title: Can I set a timer to run at 7am tomorrow?
It seems to me I can either set a time for today or some relative time in the future.
But can I combine the two somehow to set a timer for 7am tomorrow, for example?
# Answer
Yes - call `run-at-time` using the `encode-time` method to pass the time argument as mentioned in its doc string:
```
(run-at-time TIME REPEAT FUNCTION &rest ARGS)
Probably introduced at or before Emacs version 19.26.
Perform an action at time TIME.
Repeat the action every REPEAT seconds, if REPEAT is non-nil.
REPEAT may be an integer or floating point number.
TIME should be one of:
- a string giving today's time like "11:23pm"
(the acceptable formats are HHMM, H:MM, HH:MM, HHam, HHAM,
HHpm, HHPM, HH:MMam, HH:MMAM, HH:MMpm, or HH:MMPM;
a period `.' can be used instead of a colon `:' to separate
the hour and minute parts);
- a string giving a relative time like "90" or "2 hours 35 minutes"
(the acceptable forms are a number of seconds without units
or some combination of values using units in `timer-duration-words');
- nil, meaning now;
- a number of seconds from now;
- a value from `encode-time';
- or t (with non-nil REPEAT) meaning the next integral
multiple of REPEAT.
The action is to call FUNCTION with arguments ARGS.
This function returns a timer object which you can use in
`cancel-timer'.
```
So you can say
```
(run-at-time (encode-time '(0 0 7 13 6 2020 nil t nil)) nil #+my-func)
```
to run `my-func` once at 7am EDT (local time) on 2020-06-13.
N.B. For versions of emacs \< 27 (?), `encode-time` had a different signature, so the above needs to be modified like this:
```
(run-at-time (apply #'encode-time '(0 0 7 13 6 2020 nil t nil)) nil #+my-func)
```
Calculating tomorrow from today is not difficult (there may be better ways to do that than the one I use below which was thrown together in a hurry):
```
(defun tomorrow ()
;;; the `(nthcdr 3 ...)' gets rid of the SECOND, MINUTE, HOUR values
(let ((now-plus-1-day (nthcdr 3 (decode-time (+ (* 24 60 60)
(time-to-seconds (current-time)))))))
;;; now keep three entries and get rid of the DST,TIMEZONE entries
(setf (nthcdr 3 now-plus-1-day) nil)
;;; return (MONTH DAY YEAR)
now-plus-1-day))
```
This returns a three-element list `(MONTH DAY YEAR)`.
So now you can combine the two and say
```
(run-at-time (encode-time `(0 0 7 ,@(tomorrow) nil t nil)) nil #+my-func)
```
using the backquote mechanism to splice in the list that `tomorrow` returns.
N.B. For versions of emacs \< 27 (?), `encode-time` had a different signature, so the above needs to be modified like this:
```
(run-at-time (apply #'encode-time '(0 0 7 ,@(tomorrow) nil t nil)) nil #+my-func)
```
You should check the doc string of encode-time as well (the following is from bleeding-edge emacs 28.0.50 - as noted above, for emacs versions \< 27(?), the signature of `encode-time` was different, so check the doc string locally):
```
encode-time is a built-in function in `C source code'.
(encode-time TIME &rest OBSOLESCENT-ARGUMENTS)
Probably introduced at or before Emacs version 19.29.
This function does not change global state, including the match data.
Convert TIME to a timestamp.
TIME is a list (SECOND MINUTE HOUR DAY MONTH YEAR IGNORED DST ZONE).
in the style of `decode-time', so that (encode-time (decode-time ...)) works.
In this list, ZONE can be nil for Emacs local time, t for Universal
Time, `wall' for system wall clock time, or a string as in the TZ
environment variable. It can also be a list (as from
`current-time-zone') or an integer (as from `decode-time') applied
without consideration for daylight saving time. If ZONE specifies a
time zone with daylight-saving transitions, DST is t for daylight
saving time, nil for standard time, and -1 to cause the daylight
saving flag to be guessed.
As an obsolescent calling convention, if this function is called with
6 or more arguments, the first 6 arguments are SECOND, MINUTE, HOUR,
DAY, MONTH, and YEAR, and specify the components of a decoded time,
where DST assumed to be -1 and FORM is omitted. If there are more
than 6 arguments the *last* argument is used as ZONE and any other
extra arguments are ignored, so that (apply #'encode-time
(decode-time ...)) works. In this obsolescent convention, DST and
ZONE default to -1 and nil respectively.
Years before 1970 are not guaranteed to work. On some systems,
year values as low as 1901 do work.
```
EDIT: added some backward-compatibiity notes for `encode-time`. I'm not sure when the signature changed but a comment indicates that 26.2 uses the old implementation and my experiments with 26.3 indicate the same thing. I have not tested emacs-27, hence the question marks.
Thanks to @Tom for pointing the problem out.
> 4 votes
---
Tags: timers
---
|
thread-51279
|
https://emacs.stackexchange.com/questions/51279
|
Async Rsync Dired error on tramp file not found
|
2019-06-27T15:58:03.580
|
# Question
Title: Async Rsync Dired error on tramp file not found
I am trying to copy files from one directory on a remote computer to another directory on the same remote computer.
Using Dired I can open up the two directories, mark the files I want to copy and press C. This works but is very slow and holds up the computer.
So I found https://truongtx.me/tmtxt-dired-async.html however this only seems to work for copying files on my local computer. If I try and mark and copy a file on a remote computer I get :
`rsync change dir "/sourcepath/file1" failed: No such file or directory (2)
rsync: change_dir#3 "/destpath/" failed: No such file or directory (2)
rsync error: errors selecting input/output files, dirs (code 3) at main.c(695) [Receiver=3.1.2]`
The window only displays for a few seconds before disappearing.
How can I fix this?
# Answer
I would consider looking at dired-rsync which is available from MELPA.
DISCLAIMER: I am the author.
> 1 votes
---
Tags: dired, tramp, async
---
|
thread-59051
|
https://emacs.stackexchange.com/questions/59051
|
How to properly specify defcustom default list of non-trivial data types?
|
2020-06-12T17:15:31.803
|
# Question
Title: How to properly specify defcustom default list of non-trivial data types?
How to properly write the default value for a non-trivial `defcustom` form in `standard` for something like I have below: a list of 3-element lists, with choices of the types?
The `defcustom` form is: `defcustom option standard doc [keyword value]...`
The following `defcustom` works fine as long as it's default is nil.
As soon as I add a non-empty list of values in `standard` for the default value, Emacs `*Customize*` buffer UI fails (see below).
**#1: My defcustom form:** (with a `nil` value for the default, Emacs `*Customize*` buffer UI works fine):
```
(defcustom pel-key-chords nil
"..."
:group 'pel-pkg-for-key-chord
:type '(repeat
(choice
(list
:tag "expansion-keys"
(symbol :tag "mode " :value global)
(string :tag "the 2 keys ")
(repeat
(key-sequence :tag "key")))
(list
:tag "command"
(symbol :tag "mode " :value global)
(string :tag "the 2 keys ")
(function :tag "command "))
(list
:tag "lambda"
(symbol :tag "mode " :value global)
(string :tag "the 2 keys ")
(function :tag "elisp code "
:value (lambda () (interactive) <YOUR CODE HERE>))))))
```
The problem occurs when I specify a list of elements, or just one for default, as shown below:
**#2: My defcustom form:** (same code, but with an explicit default of one element):
```
(defcustom pel-key-chords
'((global "<>" "<>\C-b"))
"..."
...
```
With the default, Emacs `*Customize*` buffer UI fails: the `INS` and `DEL` buttons are not available and it is impossible to add or delete elements.
I read Emacs Lisp Customization Settings section and some code like the `dump-jump.el` code that defines some complex data with initialization. I assume I must identify some keywords in my declaration of the default, but for some reason I can't find the proper syntax for initializing the data I defined above.
# Answer
Well, murphy's law strikes again...
I just realized that the Customize buffer was showing **mismatch** beside the data structure...
The problem I had tied to the fact that the last element of my inner list is itself a list, and the default declaration identified just 1 string.
So instead of writing
```
(defcustom pel-key-chords
'((global "<>" "<>\C-b"))
"..."
...
```
What I need to do is to write it like this:
```
(defcustom pel-key-chords
'((global "<>" ("<>\C-b")))
"..."
...
```
and all goes well.
I wish checkdoc was able to catch these types of errors.
> 1 votes
---
Tags: customization, defcustom
---
|
thread-59043
|
https://emacs.stackexchange.com/questions/59043
|
How to create agenda mode that will list all entries with time against them that have no tag?
|
2020-06-12T07:08:38.837
|
# Question
Title: How to create agenda mode that will list all entries with time against them that have no tag?
As the title, trying to make an agenda item that will list all entries that have at least one minute clocked against them, but no tag.
I can get it to list entries with no tag easy, but I can't get it to list items with time clocked against them.
Looking at special properties on this page, it seems like `CLOCKSUM` should be exactly what I am looking for.
This is what I've got, but I can't make it work:
```
(setq org-agenda-custom-commands
(quote
(("t" "All items with time logged, but no tag" tags "+CLOCKSUM>=\"0:01\"" nil))))
```
The page says to run `org-clock-sum` first, but this doesn't seem to have helped. I tried org-super-agenda, but that wouldn't do it either.
I've been bashing my head against this for hours, couldn't find anything on the internet. Can anyone help?
Using Emacs 26.3 and Orgmode 9.4.
# Answer
You can add your conditions to the `org-agenda-skip-function` variable.
> Documentation: Function to be called at each match during agenda construction. If this function returns nil, the current match should not be skipped. Otherwise, the function must return a position from where the search should be continued.
```
(setq org-agenda-custom-commands
'(("t" "All items with time logged, but no tag"
((alltodo "" ((org-agenda-skip-function
(lambda ()
(if (and (null (org-get-tags))
(>= (org-clock-sum-current-item) 1))
nil
(or (outline-next-heading)
(point-max)))))))))))
```
> 2 votes
---
Tags: org-mode
---
|
thread-59052
|
https://emacs.stackexchange.com/questions/59052
|
Magit forge: is it possible to have "upstream/master" as default when dwim diffing on a pull request?
|
2020-06-12T17:47:59.740
|
# Question
Title: Magit forge: is it possible to have "upstream/master" as default when dwim diffing on a pull request?
When my cursor is at a pull request in status buffer, and I press "d d", then I get the diff of `master...refs/pullreqs/XXX`. This works as intended, if my master branch is up-to-date. However, sometimes my master branch doesn't have upstream changes merged, so this diff generates a bad output.
Is it possible to have "d d" make the diff of `upstream/master...refs/pullreqs/XXX`?
I know that I can press "d r" (diff-range), then "M-n" (copy the dwim-default to mini-buffer), and then prepend "upstream/". But still, having "upstream/master" as the default would be more convenient when reviewing PRs.
Note, in my `.git/config`, I have forge/remote set as:
```
[forge]
remote = upstream
```
# Answer
> 1 votes
I have to admit that I saw `upstream/master`, though "not *again*" and then did not read your question properly. You can still learn something from the things I have said below, but you actually put the finger on a bug.
---
I have fixed the bug by using `remote/branch...pr` instead of `branch...pr`. `remote/branch` is much more likely to be up-to-date because pulling the pr also updates remote tracking refs but not local branches.
---
It would be better if upstream were named `origin`. That's the convention and if you don't diverge from it then a lot of things will just work and you won't have to configure them explicitly. Setting `forge.remote` for example won't be necessary anymore.
I could say a few things about you the upstream and the push-remote and how they are not the same thing but both useful. But I have done that so many times I just link to my article about that instead -\> The Two Remotes.
I am guessing that the reason why you don't name the upstream `origin` is that that name is already used for your fork. You can easily prevent that from happening in the future:
1. Stop cloning your fork and then adding a remote for the upstream.
2. Instead clone upstream and then add a remote for your fork. You can add your remote using the `forge-fork`. If your fork does not exist yet, then it creates it. Then it adds the fork as a remote.
If you are not in the habit of keeping `master` up-to-date, then it is better to use `origin/master` as the upstream of your feature branches instead of `master`. That way `d u` shows the changes on your feature branch without having to first check out `master`, pull and then check out `some-feature` again.
You can change the upstream using `b u`. You probably also want to set `magit-prefer-remote-upstream` (which see).
---
Tags: magit
---
|
thread-44641
|
https://emacs.stackexchange.com/questions/44641
|
Is it possible to have shared #+PROPERTY: between multiple org files?
|
2018-09-10T12:27:29.537
|
# Question
Title: Is it possible to have shared #+PROPERTY: between multiple org files?
I'm working with `org-mode` and `org-babel` to query a PostgreSQL database. It's pretty cool setup and I love it.
At the moment, I have multiple org files with the same database property configuration like the following.
```
#+PROPERTY: header-args:sql :dbhost myhost
#+PROPERTY: header-args:sql+ :dbuser username :database secretdb :engine postgresql :exports result
```
This is duplicated in each org file now. I'm wondering if there's a way to configure this in one place and `org-babel` pick it up from.
I also have database configuration for multiple environments. So configuration for each database is also duplicated in the respective org files. It was fine in the beginning, now I have too many files with same `+#PROPERTY:` value in them, and it kind of getting confusing and tedious.
I'm looking for a way to have the configuration in one place and `org-babel` have them pickup.
Here's is what I tried so far.
1. `#+INCLUDE: "./connection-properties.org"`
You get the idea. This includes the org file, and also says `Local setup has been refreshed` when I do `Ctrl-C-Ctrl-C`. But when I execute the sql block, it fails with `org-babel-execute:sql: Wrong type argument: stringp, nil`
Looking for clues! Thanks!
# Answer
> 7 votes
I did it! Yaay!
I learned about `org-global-properties` here https://orgmode.org/manual/Property-syntax.html and gave a shot by setting in it in `.dir-locals.el` file. It works exactly as I wanted!
I have a `.dir-locals.el` file in each directory that represents and environment.
`βββ prod
β βββ .dir-locals.el
β βββ database
β βββ 01-queries.org
β βββ 02-queries.org
βββ staging
β βββ .dir-locals.el
β βββ database
β βββ 01-queries.org
β βββ 02-queries.org
βββ uat
β βββ .dir-locals.el
β βββ database
β βββ 01-queries.org
β βββ 02-queries.org
βββ localhost
β βββ .dir-locals.el
β βββ database
β βββ 01-queries.org
β βββ 02-queries.org`
`.dir-locals.el` file works like magic!
And here is the content of `.dir-locals.el` file.
```
((org-mode . (
(org-global-properties . (
(header-args:sql . ":dbhost host :database dbname :engine postgresql :exports result")
)))))
```
Instead of using `:dbpassword` in `org-global-properties`, I set it in `~/.pgpass` file.
This serves my purpose, but if you have any suggestions for improvements please comment or give a separate answer. Thank you :)
# Answer
> 5 votes
If you want to configure it in `.org` format instead of Lisp, so that you can keep your property declarations the between files as in a specific file, then you can use the `#+SETUPFILE` setting:
> The setup file or a URL pointing to such file is for additional in-buffer settings. Org loads this file and parses it for any settings in it only when Org opens the main file. If URL is specified, the contents are downloaded and stored in a temporary file cache. C-c C-c on the settings line parses and loads the file, and also resets the temporary file cache. Org also parses and loads the document during normal exporting process. Org parses the contents of this document as if it was included in the buffer. It can be another Org file. To visit the fileβnot a URLβuse C-c ' while point is on the line with the file name.
If `.dir-locals.el` works for you, then at one level I can't argue with that. But I prefer this approach to `.dir-locals.el` because
1. Even though I know Emacs Lisp, the code in `.dir-locals.el` to set properties, particularly if I am setting very many, is not as simple as Org's native syntax for it.
2. The pure Org solution is more fluid, allowing you to extract properties (and other settings) without having to reformat them into S-expressions. There is something more aesthetically pleasing to me about it as well, to let Org configure Org.
---
Tags: org-mode, org-babel, sql-mode
---
|
thread-59057
|
https://emacs.stackexchange.com/questions/59057
|
How to properly specify defcustom default list of heterogeneous types?
|
2020-06-12T21:18:25.577
|
# Question
Title: How to properly specify defcustom default list of heterogeneous types?
How to properly write the default value for a non-trivial `defcustom` form for something like I have below: a list of 3-element lists, with choices of the types?
The `defcustom` form is: `defcustom option standard doc [keyword value]...`
The following `defcustom` works fine as long as:
* it's default is nil
* it's a list of one or several elements of the first type
It fails with a "mismatch" warning in the customize buffer as soon as the default is a list of heterogeneous types (e.g. one element is from the second or third choice).
**#1: My defcustom form:** (with a `nil` default, it works fine)
```
(defcustom pel-key-chords nil
"..."
:group 'pel-pkg-for-key-chord
:type '(repeat
(choice
(list
:tag "expansion-keys"
(symbol :tag "mode " :value global)
(string :tag "the 2 keys ")
(repeat
(key-sequence :tag "key")))
(list
:tag "command"
(symbol :tag "mode " :value global)
(string :tag "the 2 keys ")
(function :tag "command "))
(list
:tag "lambda"
(symbol :tag "mode " :value global)
(string :tag "the 2 keys ")
(function :tag "elisp code "
:value (lambda () (interactive) <YOUR CODE HERE>))))))
```
If, instead of `nil` as the default I write a list with several items of different types, the customization menu fails with a mismatch and does not to properly show the widgets to enter new entries. If the list contains elements of the first type, it's fine.
**#2: My defcustom form:** (same code, but with an explicit default that works fine: a list of elements of the first choice:
```
(defcustom pel-key-chords
'((global "<>" ("<>\C-b"))
(global "[]" ("[]\C-b"))
(c++-mode "{}" ("{\n\n}\C-p")))
"..."
...
```
**#3: My defcustom form:** (same code, but with an explicit default that **fails** with a **mismatch**: a list of 3 elements of the first choice, then 1 element of the second choice:
```
(defcustom pel-key-chords
'((global "<>" ("<>\C-b"))
(global "[]" ("[]\C-b"))
(c++-mode "{}" ("{\n\n}\C-p"))
(global ".;" pel-search-word-from-top))
"..."
...
```
**Interesting note**: Additions of second and/or third type elements via the customize buffer while the default has accepted data (as in #2 above), are accepted, saved to the custom-set-variables form properly and restored properly back in the customize buffer!
This is a copy/paste of the content of the relevant portion of my custom-set-variables form after manually adding the last list element `(global ".;" pel-search-word-from-top)` via the customize buffer and then saved it gives:
```
'(pel-key-chords
(quote
((global "<>"
("<>^B"))
(global "[]"
("[]^B"))
(c-mode "{}"
("{
}^P"))
(c++-mode "{}"
("{
}^P"))
(global ".;" pel-search-word-from-top))))
```
I can then read it back without any mismatch. If I try to put this inside the default I get the mismatch warning...
I read Emacs Lisp Customization Settings section and some code like the `dump-jump.el` code that defines some complex data with initialization. I assume I must identify some keywords in my declaration of the default, but for some reason I can't find the proper syntax for initializing the data I defined above.
*Note*: this question evolved from my previous question How to properly specify defcustom default value for non-trivial data type?
# Answer
Although I did report a bug for the problem I ran into and described above in bug #41831 I found a **work-around** by declaring a similar data structure differently. The new layout is handled properly by `*customize*` buffer UI and I can identify a default with heterogeneous types in it.
**Work-around defcustom declaration:**
```
(defcustom pel-key-chords2
'((global ",." "<<<<<>>>>>\\C-b\\C-b\\C-p\\C-b\\C-b")
(global "<>" "<>\\C-b")
(global " q" pel-indent-rigidly)
(global "yu"
(lambda nil
(interactive)
(message "Hello You"))))
"Another way to implement the data structure, placing the choice
deeper inside the leaf data element.
This is handled properly by customize UI."
:group 'pel-pkg-for-key-chord
:type
'(repeat
(list
(symbol :tag "mode" :value global)
(string :tag "2-keys")
(choice (string :tag "expansion")
(function :tag "function")
(function :tag "lambda" :value (lambda () (interactive) <YOUR CODE HERE>))))))
```
In this new defcustom declaration, this is a list of 3 elements where the 3rd list element is a choice of 3 types, as opposed to a top-level choice of 3 lists of different *'sub-types'* as I did originally and described in the question.
With the new declaration I can identify defaults, save the values and restore them as one would expect with Emacs customization mechanism.
So, at least, this works around the problem described in my original question, and it might help looking into the cause of the original Emacs defcustom UI implementation issue.
**Important Note: another cause of the problem: unbound symbols at edit time**
I also noticed that the customize UI will reject the data structure if a symbol identified in the data structure is not bound at the time the customize UI buffer is opened to edit the data structure.
So if something like pel-indent-rigidly is not bound when the customize buffer is opened and that symbol is part of the default quoted data structure, then the UI will fail and show the mismatch message again.
So in the end, it is important to ensure that the symbols will be bound when the defcustom default form will be shown for editing. That is what the defcustom :load keyword is for: to ensure that all symbols are known when the form is loaded for editing.
> 0 votes
---
Tags: customize, defcustom
---
|
thread-59063
|
https://emacs.stackexchange.com/questions/59063
|
How to efficiently merge 2 buffers which are partially overlapping?
|
2020-06-13T17:30:27.840
|
# Question
Title: How to efficiently merge 2 buffers which are partially overlapping?
## Problem summary
Imagine, you have 2 shopping lists:
* 1 huge one with hundreds of entries - list A, copied into buffer A
* 1 containing dozens of entries - list B, copied into buffer B
Then:
* 75% of the entries of list B are already part of list A, but the other rest of list B notβand you don't have a clue or overview which specific entries of list B are the new ones compared to list A.
* You want to extend list A by list B, so that the "new list A" contains all entries of list A and B without any dopplerβso, each entry just 1 time.
To make a simple example:
```
List A: List B: What you wantβ"new list A":
* Tomato * Garlic * Tomato
* Leek * Tomato * Leek
* Garlic * Cherries * Garlic
* Lentils * Leek * Lentils
* Banana * Banana
* Almond milk * Almond milk
* Cherries
```
## Question
How can that be done as efficient as possible?
## Info:
* I'm not able to program.
* I'm very new to the emacs command "ediff", yet.
* I'm relatively new to emacs, using it just for 1 year on a daily basis so far.
* I'm getting familiar with using keyboard macros, and keyboard marcos built of a series of keyboard macrosβlike keyboard macro D(A + 7xB + 3xC)
## Details on research:
I've already researched on it using web search engines and starting to turn to the emacs command "ediff".
## What I've tried:
I tried `M-x ediff-buffers`, but the outcome wasn't very useful: Both buffers were compared automatically, but not in a smart way; comparison wasn't content sensitive, but line by line, so it said "line 1, 2, 3,... are not the same", when I needed it to say "Cherries is different".
Next thing I've tried was `M-x ediff-buffers3` for merging, but it had the same problem:
It just let me choose, if for example line 2 of buffer A or buffer B will be used for the merge version, when I wanted emacs to automatically figure out what entries of list B are the new ones for list A and then merging list A only with these new entries.
I see the possibility of taking list B and manually take each entry of itβone by oneβand search for it in list A. This way I would figure out by what entries of list B the list A needs to be extended, but that's an arse full of work.
There gotta has to be a more efficient way with any emacs commands.
# Answer
You don't need to do anything fancy with ediff or keyboard macros. Just concatenate the two files together, then remove any duplicates.
You can do that at the command line: `cat a b | sort | uniq > c`
Or you can do it in emacs: paste both lists into a single buffer, then select everything with `C-x h`. Run `M-x sort-lines` to sort them, then `M-x delete-duplicate-lines` to remove the duplicates. Save it to a new file.
> 2 votes
---
Tags: sorting, ediff, diff, emerge
---
|
thread-58033
|
https://emacs.stackexchange.com/questions/58033
|
How to use underscores as word boundary for moving cursor?
|
2020-04-24T14:13:33.917
|
# Question
Title: How to use underscores as word boundary for moving cursor?
Python mode annoyingly sets underscore (`_`) to be part of a word, making editing very tedious.
How can one reset this to Emacs's original behaviour?
# Answer
Simply call the function `py-underscore-word-syntax-p-off` in your config file:
```
(use-package python-mode
:ensure t
:config
(py-underscore-word-syntax-p-off))
```
*Edited: use helper function instead of setting `py-underscore-word-syntax-p-off` programmatically.*
> 1 votes
# Answer
Change the syntax of character `_` to *symbol* syntax (`"_"`):
```
(modify-syntax-entry ?_ "_" python-mode-syntax-table) ; "_" means symbol syntax
```
Or change it to some other syntax class (other than word syntax: `"w"`). For example, change it to punctuation syntax:
```
(modify-syntax-entry ?_ "." python-mode-syntax-table) ; "." means punctuation syntax
```
See the Elisp manual, node Syntax Table Functions.
> 0 votes
---
Tags: syntax-table
---
|
thread-59068
|
https://emacs.stackexchange.com/questions/59068
|
Tramp `find-dired`: wrong type argument error
|
2020-06-14T08:30:31.740
|
# Question
Title: Tramp `find-dired`: wrong type argument error
If i use `find-dired` in a remote directory (from Tramp) then I get a `wrong type argument: processp, nil` error.
It works on a local dir.
All I pass to `find` is '-iname "*blah*"'.
```
/sftp:andreaz@10.0.0.99:/home/andreaz/files/:
find . \( -name "*blah*" \) -exec ls -ld \{\} \;
```
# Answer
`sftp` is implemented in Tramp by GVFS, so it doesn't support remote processes. You must use a Tramp method like `ssh` or `scp`.
> 2 votes
---
Tags: tramp, find-dired
---
|
thread-59070
|
https://emacs.stackexchange.com/questions/59070
|
Dired doesn't open non-text files with external applications in a Tramp directory listing
|
2020-06-14T10:02:30.330
|
# Question
Title: Dired doesn't open non-text files with external applications in a Tramp directory listing
In Dired I'm in a Tramp directory opened with `/sftp:...` (so using the `gvfs` backend).
If I use `&` to open a non-text file with a local external application (ex. `evince` for PDF) it doesn't do anything (no errors).
It works in a local directory (and it works when I open a text file in the same remote directory).
# Answer
> 2 votes
`sftp` is implemented in Tramp by GVFS, so it doesn't support remote processes. You must use a Tramp method like `ssh` or `scp`.
---
Tags: dired, tramp
---
|
thread-52192
|
https://emacs.stackexchange.com/questions/52192
|
How to efficiently include a repository relative path in the mode-line?
|
2019-08-17T14:52:00.697
|
# Question
Title: How to efficiently include a repository relative path in the mode-line?
Currently in the mode-line the filename `%f`, is absolute.
I would like to have the path relative to the version-control root, without having to find this every redraw.
How could this be cached, allowing for changes to the buffers filename to be refreshed?
# Answer
> 1 votes
I've come up with an alternative to this solution which is more efficient.
Instead of showing a longer name in the mode-line, the buffer it's self can be renamed, using the path to the vc-root when available.
This can be done using the following code:
```
(defun create-file-buffer--with-name-from-root (orig-fn filepath)
(let ((buf (funcall orig-fn filepath)))
;; Error's are very unlikely, this is to ensure even the most remote
;; chance of an error doesn't make the file fail to load.
(condition-case err
(when buf
(let ((vc-backend
(ignore-errors (vc-responsible-backend filepath))))
(when vc-backend
(let ((vc-base-path
(vc-call-backend vc-backend 'root filepath)))
(when vc-base-path
(let* ((name-base
(concat
"./"
(file-relative-name filepath vc-base-path)))
(name-unique name-base)
(name-id 0))
(while (get-buffer name-unique)
(setq name-unique
(concat name-base (format " <%d>" name-id)))
(setq name-id (1+ name-id)))
(with-current-buffer buf
(rename-buffer name-unique))))))))
(error (message "Error creating vc-backend root name: %s" err)))
buf))
(advice-add 'create-file-buffer
:around #'create-file-buffer--with-name-from-root)
```
# Answer
> 0 votes
`after-set-visited-file-name-hook` is a reliable way to detect changes to the filename.
This clears the cached value when a new filename if set.
```
;; Cache the vc-root relative name of the buffer.
(defvar-local buffer-file-name--vc-root-relative nil)
(defun buffer-file-name-vc-root-relative-fn (filepath)
;; Lazy initialize.
(when (eq buffer-file-name--vc-root-relative nil)
(let ((base-path
(let ((vc-backend (ignore-errors (vc-responsible-backend filepath))))
(when vc-backend
(vc-call-backend vc-backend 'root filepath)))))
(setq
buffer-file-name--vc-root-relative
(if base-path
(concat
"./"
;; Account for possibility of filepath containing a '%'.
(replace-regexp-in-string
"%" "%%" (file-relative-name filepath base-path)))
;; No base-path, set to 't',
;; initialized with no base (return nil).
t))))
(unless (eq buffer-file-name--vc-root-relative t)
buffer-file-name--vc-root-relative))
(add-hook 'after-set-visited-file-name-hook
(lambda () (setq buffer-file-name--vc-root-relative nil)))
```
Then in the mode-line, this can be used to show the filename.
```
(or (buffer-file-name-vc-root-relative-fn filepath) "%f")
```
---
Tags: mode-line
---
|
thread-59066
|
https://emacs.stackexchange.com/questions/59066
|
Inconsistent behavior when calling #'funcall with a macro
|
2020-06-14T03:12:20.260
|
# Question
Title: Inconsistent behavior when calling #'funcall with a macro
I would have thought that both of the `funcall`'s the follow would have yielded the same result, but they don't and I'm trying to understand why.
```
(defmacro test/z () "z")
(funcall (function test/z)) ;; => "z"
(funcall (eval `(function ,(intern "test/z")))) ;; => Invalid function: test/z
```
Looking at the arguments of each call, they evaluate to the same thing:
```
(eq (function test/z) (eval `(function ,(intern "test/z")))) ;; => t
```
What really has me scratching my head that is that if I use `defun` instead of `defmacro` `funcall` then works in both calls..
I think I'm missing something in my understanding and I'm hoping someone can straighten me out. I'm reading the elisp info manual, but haven't found anything.
What's going on here?
# Answer
> 2 votes
\`funcall' is not supposed to be called with a macro as the FUNCTION argument. The Elisp manual says:
> The argument FUNCTION must be either a Lisp function or a primitive function. Special forms and macros are not allowed, because they make sense only when given the unevaluated argument expressions. βfuncallβ cannot provide these because, as we saw above, it never knows them in the first place.
However, that does not explain why `funcall` does not complain on the first call (that may be a bug). Wrapping it in `(function ...)` seems to make a difference in whether `funcall` will get an error or not in the macro case. The more common (?) method of passing the symbol to `funcall` does the right thing according to the doc:
```
(defmacro test/z () "z")
(funcall (function test/z)) ==> "z"
(funcall 'test/z) ==> invalid function: test/z
(defun func/z () "z")
(funcall (function func/z)) ==> "z"
(funcall 'func/z) ==> "z"
```
---
Tags: functions, elisp-macros, funcall
---
|
thread-58880
|
https://emacs.stackexchange.com/questions/58880
|
Org-mode export error- Wrong type argument: org-export-backend
|
2020-06-03T07:50:00.017
|
# Question
Title: Org-mode export error- Wrong type argument: org-export-backend
I'm trying to export an `Org` document to latex, but get the following error:
```
org-export-get-all-transcoders: Wrong type argument: org-export-backend, [cl-struct-org-export-backend nil latex ((underline lambda (o c i) (format "\\underline{%s}" c))) nil nil nil nil]
```
What's the way to debug it and find the error? If I create a new `*.org` document it can be exported to latex witout problems. Therefore I think that the reason is in the document itself, but I don't know how to look for the cause of the error.
I'm using GNU Emacs 26.1 (build 2, x86\_64-pc-linux-gnu, GTK+ Version 3.24.5) and have already updated all packages with `M-x list-packages` -\> `U` -\> `x`. Exporting to other formats (e.g. html) works fine.
# Answer
Despite doing `M-x list-packages` -\> `U` -\> `x`, `org` hadn't been updated (probably because it was not installed through melpa). After upgrading org the error disappeared.
> 0 votes
---
Tags: org-mode, org-export, latex
---
|
thread-59078
|
https://emacs.stackexchange.com/questions/59078
|
reverse buffer order
|
2020-06-14T22:51:22.117
|
# Question
Title: reverse buffer order
I open Emacs from the command line to inspect 10+ files, say like this:
```
emacs *.java
```
However, all the files are listed in reverse order. This is getting kind of annoying--I'd like to start with the A files, not the Z files. Is there any way to just reverse all the buffers? Or even better, a command-line option that opens the files in reverse order, so that Emacs has them the right way around? (Without explicitly typing in every file.)
# Answer
They're "visited" in the order given, and the buffer list you see sorts them (by default) by order of "recency". But you can sort them some other way, such as alphabetically: move the cursor into the column of buffer names and press `S` to sort them by their name.
I found this solution in the following way: \- `C-h m` showed me the description of `buffer-menu-mode`. \- In that description `C-s sort` told me there's no sorting option specific to that mode, but `C-s parent` showed this mode derives from `tabulated-list-mode`, so I clicked on this name to find the doc of that parent mode. \- `C-s sort C-s` to find that `S` is bound to `tabulated-list-sort` which does the trick.
> 1 votes
---
Tags: buffers, files, command-line-arguments
---
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.