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-55474
|
https://emacs.stackexchange.com/questions/55474
|
Shell doesn't accept commands after ssh login or R or Python
|
2020-02-12T10:07:42.130
|
# Question
Title: Shell doesn't accept commands after ssh login or R or Python
This used to work just until recently, no idea what happened maybe an updated version of something is causing the problem.
In the `shell` buffer in Emacs, shell seems to stop working after SSH or launching R or Python. Say, if I launch R in shell buffer, R loads and when I enter any command and press Enter the cursor just moves to a new line, no command is sent. But the shell responds to `C-c C-c` and cancels the command and returns the prompt. I've tried issuing `comint-send-input` manually with `M-x` but that didn't work either. I've also tried this with "bare" Emacs, launching it with the `-Q` option, same.
For SSH, the problem occurs for `bash` but not for `zsh`.
I've just used `zsh` to launch R and I get "^G" inserted at the end of the command after pressing Enter. I think that is the problem. No idea how that occurs, if hadn't tried `zsh` with R never would have seen it as it doesn't print on screen with bash.
GNU Emacs 26.3 on Ubuntu 19.04
# Answer
The problem was in the `.inputrc` file (vi mode) with the following line:
`Control-j: history-search-forward`
As suggested in the jue's comment below, the following solves the problem by restoring the `C-j` to its original binding for `dumb` terminals such as the shell mode in Emacs:
```
$if term=dumb
Control-j: accept-line
$else
Control-j: history-search-forward
$endif
```
I had the same `.inputrc` file everywhere, on the remote servers and the VM.
Big thanks to @jue!
> 2 votes
---
Tags: shell
---
|
thread-55512
|
https://emacs.stackexchange.com/questions/55512
|
How to leave mark region highlighted when switching windows
|
2020-02-13T17:51:26.383
|
# Question
Title: How to leave mark region highlighted when switching windows
I usually have my Emacs frame split into windows. I'll select something in one window and then switch to another buffer. When I do this Emacs removes the active-region highlghting in the original window. I'd like to keep it highlighted so I know what I was focused on while working in the other window.
# Answer
> 5 votes
`highlight-nonselected-windows` is a variable defined in `xdisp.c`. Its default value is `nil`. A `non-nil` value means highlight region even in nonselected windows. You can customize this variable, e.g.:
```
(setq highlight-nonselected-windows t)
```
---
Tags: window, region, transient-mark-mode
---
|
thread-55506
|
https://emacs.stackexchange.com/questions/55506
|
Run current line or selection in shell then insert result in Emacs buffer (Acme workflow)
|
2020-02-13T16:20:55.880
|
# Question
Title: Run current line or selection in shell then insert result in Emacs buffer (Acme workflow)
Given lines like these:
```
pwd
echo "Hello \
World"
```
in a buffer, I would like to do the following:
1. Put the cursor to the first line, then press `C-``
2. Select lines 3-4 then press `C-``
to send the line or selection to a shell `bash` and insert the output in the following line. Ideally, the terminal should be persistent, thus setting variables then reusing them is possible.
I found in Evil mode, I could type `!!sh` to do `1.` and `!sh` when a region is selected (however this replaces the command with the returned output), but couldn't figure out how to map `C-`` to `!!sh`. `:.w !sh` seems to be closer to what I wanted.
There seems to be an Emacs package `run-stuff` that offers similar functionality, but I'd rather use ways provided by Vanilla Emacs plus common Emacs packages such as `evil-mode`, `use-package` etc.
Ultimately, I'd like to embed an acme-like workflow into Emacs, where I can put a few short commands on an anchored top line, then run them while providing a selected text as input to the said command, and if possible, some other selected text (maybe using `multiselect`) as options to the command.
# Answer
> 4 votes
`M-|` (`M-x shell-command-on-region`) runs a shell command using the region as stdin, display the output in the echo area, with a prefix arg, replace the region with the output.
Unlike your shell in a terminal, each use of `M-!` or `M-|`: start a shell such as `bash`, run the shell command, then kill the shell. And the region is data passed to the shell command, the content is arbitrary, for example,
```
ABCDE M-| wc
{"type": "JSON"} M-| jq
```
the above works because `wc` and `jq` read stdin as input, and since the executables `bash`, `ruby` and `python3` read stdin as corresponding programming code, you can run Bash/Ruby/Python code with `M-|`, e.g.,
```
echo "Bash" M-| bash
puts "Ruby" M-| ruby
print("Python") M-| python3
```
In other words, `M-|` is simple and generic, so stick with it, if you need insert the output, simply copy-and-paste, though defining your own command isn't hard at all, e.g.,
```
(defun your-shell-command-on-region ()
"Like `shell-command-on-region' but insert output after the region."
(declare (interactive-only t))
(interactive)
(let ((output-buffer (generate-new-buffer " *temp*")))
(shell-command-on-region
(region-beginning) (region-end)
(read-shell-command "Shell command on region: ")
output-buffer)
(goto-char (region-end))
(unless (bolp)
(insert ?\n))
(insert-buffer-substring output-buffer)
(kill-buffer output-buffer)))
```
> Run current line or selection in shell then insert result in buffer in Emacs
Let's assuming the current line or selection are shell code
```
(defun $ (b e)
"Run current line or selection in shell and insert output."
(interactive
(if (use-region-p)
(list (region-beginning) (region-end))
(list (line-beginning-position) (line-end-position))))
(save-excursion
(goto-char e)
(unless (bolp) (insert "\n"))
(shell-command (buffer-substring-no-properties b e) t t)))
(global-set-key (kbd "C-c C-c") #'$)
```
A cool idea is **update** the output in-place (like Org Mode Babel), that is, delete the old output then insert the new output,
```
(defun $$ (b e)
"Run current line as shell code and insert/update output."
(interactive (list (line-beginning-position)
(line-end-position)))
(save-excursion
;; delete old output
(delete-region
(progn (forward-line) (point))
(progn (while (get-text-property (point) '$$)
(forward-line))
(point)))
(unless (bolp) (insert "\n"))
(let* ((command (buffer-substring-no-properties b e))
(output (with-temp-buffer
(shell-command command t t)
(buffer-string)))
(start (point)))
(insert (propertize output '$$ t 'rear-nonsticky t))
(pulse-momentary-highlight-region start (point)))))
```
Try it with `date`.
> Ultimately, I'd like to embed an acme-like workflow into Emacs, where I can put a few short commands on an anchored top line, then run them while providing a selected text as input to the said command,
`M-|` does this, though the user interface is different, the input is from the region, the command is from the minibuffer, the output is to echo area.
To implement the similar workflow you described, get started with three buffers for input/command/output, the code should be straightforward.
---
Tags: key-bindings, evil, region, shell-command, multiple-cursors
---
|
thread-55504
|
https://emacs.stackexchange.com/questions/55504
|
Syntax highlighting in sql-mode on Emacs-24 not working?
|
2020-02-13T15:22:48.697
|
# Question
Title: Syntax highlighting in sql-mode on Emacs-24 not working?
I'm trying to get the font-lock stuff in plsql.el (https://www.emacswiki.org//emacs/plsql.el) to work in Emacs 24 (that's the version provided by my Linux distro), but it doesn't highlight automatically on entering the mode and it only highlights strings and comments, not keywords like `procedure`.
This module is working on the old computer with Emacs 21, so I assume something has changed. The docs on emacswiki seem vague to a non-elisp programmer. (I can read elisp, and have written a few macros, but not an expert by any stretch.)
So, unless somebody knows of an alternative working PL/SQL mode that works with font-lock on 24, I'd like to start by looking at the font-lock settings, but I don't see any usable functions that start with font-lock- in the autocomplete list. How do I do this?
I made the change suggested by Stefan and moved the sql-mode line and got the same thing. The image is after running `M-x font-lock-fontify-buffer`. New computer on left, old on right.
Plain SQL mode doesn't do anything different.
# Answer
> 2 votes
After reading the `sql-mode` source, I discovered what I think is the issue. Here's a workaround in case anyone else has this (or when I have the same issue 6 months from now...)
`sql-mode` apparently has different dialects of SQL that it can recognize. When it loads at startup it defaults to ANSI mode. But if you run it via `M-x sql-mode` it doesn't do that and only loads the most basic keywords into font-lock.
A second command, `M-x sql-set-product oracle` or `M-x sql-set-product ansi` is required to set the appropriate dialect, which loads the keywords. I added that to the plsql.el file after the call to sql-mode and that seems to have gotten it to work.
```
(defun plsql-mode ()
"Programming support mode for PL/SQL code."
(interactive)
;; (require 'sql)
(sql-mode)
(sql-set-product "oracle")
```
# Answer
> 0 votes
Looking at `plsql.el` I suspect the problem is in:
```
(defun plsql-mode ()
"Programming support mode for PL/SQL code."
(interactive)
(require 'sql)
[...]
(setq sql-mode-font-lock-keywords ...)
(setq font-lock-mark-block-function 'mark-visible)
(sql-mode)
[...]
```
since when we call `sql-mode`, it will re-set `sql-mode-font-lock-keywords`, so the call to `sql-mode` should come first (basically right where is the redundant `(require 'sql)`).
If you define `plsql-mode` with `define-derived-mode` this will be taken care of automatically ;-)
---
Tags: font-lock
---
|
thread-55518
|
https://emacs.stackexchange.com/questions/55518
|
Customize variable: custom-theme-load-path[no match]
|
2020-02-13T19:14:40.967
|
# Question
Title: Customize variable: custom-theme-load-path[no match]
1. I followed instruction here to erase customization. however, it returns \[no-match\]. am i doing anything wrong here?
2. The reason that I was trying to erase the custom-theme-load-path is that I failed to load color theme from .init file, in the following way. any hint on why it failed to load the **solarized** theme? Any help is appreciated!
> having the following piece in a file `general-settings.el`
```
(add-to-list 'custom-theme-load-path (make-plugin-path "color-theme-solarized"))
(load-theme 'solarized 1)
```
> and then `(require 'general-settings)` in my .init file
>
> make-plugin-path is defined as below:
```
(defun make-plugin-path (plugin)
(expand-file-name
(concat plugin-path plugin)))
```
> plugin-path is a defined variable
# Answer
> 1 votes
Exactly the question you have linked lead to the decision to demote `custom-theme-load-path` from `defcustom` to `defvar` in Emacs 25.0.90.
For that reason it is no longer customizable by `customize`.
The corresponding commit was 995b69918b with title "custom.el (custom-theme-load-path): Demote to defvar".
I cite here the comment of that commit:
> `custom-theme-load-path` was a defcustom, but it shouldn't be for the same reason that `load-path` shouldn't. Setting it via the customize interface is a trap for the user.
>
> Installed themes commonly add themselves to this variable, which means its value is not fit for being saved (it will permanently remember dirs that don't exist anymore).
>
> This is aggravated by the fact that Emacs always applies the 'user' theme on top of any theme that's loaded, since this will apply the old variable value and remove any new directories that had been recently added by themes themselves.
>
> Not to mention, we already have `custom-theme-directory`, which is safe to customize.
---
Tags: themes
---
|
thread-55490
|
https://emacs.stackexchange.com/questions/55490
|
Org mode table- make entire column to contain checkbox
|
2020-02-12T23:01:25.100
|
# Question
Title: Org mode table- make entire column to contain checkbox
I have a table like this using Org mode (by typing `|--` and then `tab` to complete
```
|-- Item-- |--Notes---|
| blah blah|blah blah |
```
Now I would like to add another column just before Item and contains checkbox. This is so that I can go down the table and check which item I have done. I know another way to do this is via a simple todo list. However, I would like to know how to do this via table.
In other words, I want:
```
|--Check-- |-- Item-- |--Notes---|
| [ ] | blah blah|blah blah |
```
And so on and so forth. I would like to be able to do `C-c-C-C` on `[ ]`, as I move down the column and it would check `X` in the box.
In contrast to the example above, my actual table is very long (around 7 columns and 15 rows)
# Answer
> 1 votes
To insert a column on the left, start with the cursor on the first column, then press `M-S-right` (followed by `M-left` depending on the version you're using).
AFAIK there's no checkbox support in tables the way you're used to, so here's a command that toggles the presence of a "checkbox" in the current cell and moves down one row.
```
(defun check-cell ()
(interactive)
(let ((cell (org-table-get-field)))
(if (string-match "[[:graph:]]" cell)
(org-table-blank-field)
(insert "X")
(org-table-align))
(org-table-next-row)))
```
---
Tags: org-mode, org-table, todo
---
|
thread-55523
|
https://emacs.stackexchange.com/questions/55523
|
Adding conditional control to function argument
|
2020-02-14T08:45:04.933
|
# Question
Title: Adding conditional control to function argument
How do we add conditional control to function arguments?
```
(defun f (x)
(let (x)
(if (eq (x (or 1 2)))
(print x)
(print "Hey!"))))
```
I would like to call:
```
(f 1)
; 1
(f 2)
; 2
(f 3)
; Hey!
```
# Answer
There are a bunch of things wrong with your code as is:
* `eq` compares two Lisp objects by their identity. This happens to work with integers due to implementation details, but is not guaranteed to work with numbers in general. For example only `(= 1 1.0)` works as intended, all other comparisons will fail. Use `=` for that reason (except when comparing floats, then you should be comparing their difference against an appropriate threshold).
* The function is passed `x` as argument, then a local variable `x` is introduced with `nil` for its value, shadowing the function argument. There is no way the comparison will ever work with that going on.
* The syntax of the predicate doesn't make terribly much sense. You're passing the `eq` a single argument (it expects two, it's a comparison function after all). That argument is the result of calling `x` as a function which will fail (there's no such function because it's been bound in a separate namespace only). Even if it would work, `x` is passed `(or 1 2)` which will evaluate to 1 as that's the first truthy value.
I guess you meant to write this instead:
```
(defun f (x)
(if (or (= x 1) (= x 2))
(print x)
(print "Hey!")))
```
The predicate passed to `if` is `(or ... ...)`, where each argument is the result of comparing `x` to the number you're interested in. An alternative way of writing this would be the `member` function which searches a list for the first matching item, using `equal` for comparison (which happens to behave almost like `=` for integers):
```
(defun f (x)
(if (member x '(1 2))
(print x)
(print "Hey!")))
```
> 1 votes
---
Tags: conditionals
---
|
thread-55529
|
https://emacs.stackexchange.com/questions/55529
|
How to rename a file with dired with the current file name as default?
|
2020-02-14T13:03:13.207
|
# Question
Title: How to rename a file with dired with the current file name as default?
In the `macOS Finder`, I can rename a file or directory by pressing `RET` and the current value becomes the default for the new file name. This helps if I make a small change, such as adding a date at the beginning of the filename.
In Emacs with dired, I can rename with `R` but I don't have the previous value as the default, so I auto-complete it. This becomes dangerous if I make a mistake in the auto-completion and overwrite another file.
Can Emacs dired rename files incrementally as in the Finder?
# Answer
Pressing `R` in dired queries the new file name in the minibuffer. There you can access the current file name by pressing the button.
Note that this is a general convention when querying text input from the minibuffer. Pressing the -button gives you the default value(s), pressing the -button gives you the input history elements.
That way multiple default values become possible.
> 18 votes
---
Tags: dired
---
|
thread-55530
|
https://emacs.stackexchange.com/questions/55530
|
How to find the next match with re-builder?
|
2020-02-14T13:04:41.280
|
# Question
Title: How to find the next match with re-builder?
I built a complicated regular expression with re-builder and see that it works with the matches I want. How can I find all the matches, as I would with `C-s` in `isearch-forward`?
# Answer
> 3 votes
Just have a look into the `Re-Builder` menu. There you find the menu item `Go to next match` bound to `C-c C-s`.
---
Tags: regular-expressions
---
|
thread-55535
|
https://emacs.stackexchange.com/questions/55535
|
*Compile-log* buffer warning
|
2020-02-14T14:28:21.507
|
# Question
Title: *Compile-log* buffer warning
I am a newbie to Emacs Lisp. started Emacs and the `*Compile-log*` buffer shows the following logs which I don't have much clue of. I was trying to install `Magit` and `Helm`.
1. should anything in this log be concerning?
2. are the installations successful?
3. if possible, what does the log mean?
```
Leaving directory ‘c:/Users/user/.emacs.d/elpa/with-editor-20200204.1828’
Compiling file c:/Users/user/.emacs.d/elpa/with-editor-20200204.1828/with-editor.el at Fri Feb 14 09:11:47 2020
Entering directory ‘c:/Users/user/.emacs.d/elpa/with-editor-20200204.1828/’
In with-editor-finish:
with-editor.el:347:51:Warning: assignment to free variable
‘git-commit-post-finish-hook’
Compiling no file at Fri Feb 14 09:12:37 2020
Leaving directory ‘c:/Users/user/.emacs.d/elpa/transient-20200125.1308’
Compiling file c:/Users/user/.emacs.d/elpa/transient-20200125.1308/transient.el at Fri Feb 14 09:12:37 2020
Entering directory ‘c:/Users/user/.emacs.d/elpa/transient-20200125.1308/’
Compiling no file at Fri Feb 14 09:13:05 2020
Leaving directory ‘c:/Users/user/.emacs.d/elpa/dash-20200119.2310’
Compiling file c:/Users/user/.emacs.d/elpa/dash-20200119.2310/dash.el at Fri Feb 14 09:13:05 2020
Entering directory ‘c:/Users/user/.emacs.d/elpa/dash-20200119.2310/’
Compiling no file at Fri Feb 14 09:13:05 2020
Leaving directory ‘c:/Users/user/.emacs.d/elpa/git-commit-20200207.1819’
Compiling file c:/Users/user/.emacs.d/elpa/git-commit-20200207.1819/git-commit.el at Fri Feb 14 09:13:05 2020
Entering directory ‘c:/Users/user/.emacs.d/elpa/git-commit-20200207.1819/’
In helm-elisp--persistent-help:
helm-lib.el:1054:40:Warning: reference to free variable
`helm--buffer-in-new-frame-p'
helm-lib.el:1056:38:Warning: reference to free variable
`helm-persistent-action-window-buffer'
In helm--prepare-completion-styles:
helm-lib.el:1385:13:Warning: reference to free variable
`helm-completion-style'
helm-lib.el:1392:42:Warning: reference to free variable
`helm-completion-styles-alist'
helm-lib.el:1412:1:Warning: Unused lexical variable `helm-completion-style'
In end of data:
helm-lib.el:1581:1:Warning: the following functions are not known to be
defined: ffap-url-p, ffap-file-remote-p, helm-log-run-hook, helm-update,
helm-get-selection, helm-set-case-fold-search
In helm-resume:
helm.el:2760:34:Warning: reference to free variable `helm-marked-buffer-name'
```
# Answer
As long as you only see warnings and not errors, the installation is successful. Compilation warnings are relevant to the author of the package, but usually not to users.
Warnings may indicate that some functionality will not work. Often they don't: the compiler can only detect suspicious coding patterns, it can't tell whether the code actually works; and if there was a bug, there's a good chance that the package author would have fixed it.
“Reference to free variable” and “the following functions are not known to be defined” both indicate that the code is missing a compile-time declaration of the package that defines a symbol (variable or function). The package will still work as intended as long as the symbols are available at run time. The warnings about variables may be a concern eventually as more and more Emacs package declare variables lexically.
> 2 votes
---
Tags: byte-compilation, install, warning
---
|
thread-55536
|
https://emacs.stackexchange.com/questions/55536
|
change the privileges of opening a file when it has already jumped to a remote host using tramp
|
2020-02-14T14:55:19.783
|
# Question
Title: change the privileges of opening a file when it has already jumped to a remote host using tramp
Good afternoon. To visit the local sudo privilege file, I use the tramp command:
```
Ctr+f //sudo::/путьКфайлу
```
Is it possible to open a remote file with sudo privileges if emacs already uses tramp, and the invitation to enter visiting the file looks like:
```
Ctr+f /ssh:remoteHost:/home/uzvr
```
It seems to me there should be a team to change the privileges of opening files when emacs is already working with deleted files. Thanks.
Thank you, Michael Albinus, you get a new jump, and you can’t use the fact that you already reached the host. I use an ssh certificate to access the host (it is written in the configuration file, thank you again for this personally), a third-party application forms the command (in this case, my command looks like this:
```
/usr/local/bin/emacs -eval '
(progn
(require (quote tramp-sh))
(let ((args (assoc (quote tramp-login-args)
(assoc "ssh" tramp-methods))))
(setcar (cdr args)
(append (quote (("-F" "/home/alamd/ПакетыДоступа/al_kuhnia/config")))
(cadr args)))))' \
"/ssh:remoteHost: ~"
```
Next, emacs opens the user folder. It turns out then how can I transfer the configuration file for ssh again to tramp
# Answer
Use Tramp's multi-hop:
```
C-x C-f /ssh:remoteHost|sudo:remotehost:/home/uzvr
```
The Tramp manual gives you more detail.
This will only work if you immediately attach my ssh configuration file for the trump, but I would like not to edit all files from root.only such a solution comes to mind
```
M-: (progn
(require (quote tramp-sh))
(let ((args (assoc (quote tramp-login-args)
(assoc "ssh" tramp-methods))))
(setcar (cdr args)
(append (quote (("-F" "/home/alamd/ПакетыДоступа/al_kuhnia/config")))
(cadr args))))
(find-file "/ssh:remoteHost|sudo:remotehost:/etc/ssh/sshd_config"))
```
> 0 votes
---
Tags: tramp, sudo
---
|
thread-55434
|
https://emacs.stackexchange.com/questions/55434
|
How to show full subtree in Org 9.3.3
|
2020-02-11T09:12:21.927
|
# Question
Title: How to show full subtree in Org 9.3.3
I want to access the first entry of a `:LOGBOOK:` drawer independently of the visibility of a subtree: folded, partially folded, or unfolded. This function worked on 9.1.9 in the first two cases (folded and partially folded):
```
(defun my-org-clock-goto-next-clock ()
(interactive)
(org-back-to-heading)
(search-forward "LOGBOOK:")
(org-cycle 3)
(forward-line)
(move-beginning-of-line nil)
)
```
I upgraded to Org mode 9.3.3 and `(org-cycle 3)` no longer unfolds a subtree. At a top-level heading, I see a message:
```
Already at the top level of the outline
```
I read the manual on local and global visibility cycling and could not find how to set a subtree to unfolded.
What is the command to unfold all contents of a subtree regardless of the initial state?
# Answer
Summarizing the comments, you are looking for `(outline-show-subtree)` in the general case:
> `(outline-show-subtree)`
>
> Show everything after this heading at deeper levels.
In case of a drawer, which most people want folded even when the tree is unfolded, use `(org-flag-drawer nil)`:
> `(org-flag-drawer FLAG &optional ELEMENT BEG END)`
>
> When `FLAG` is non-nil, hide the drawer we are at. Otherwise make it visible.
`org-cycle` delegates to `org-flag-drawer` in the case of a drawer.
You may need to call them in a different order, or when point is at the location you want unfolded.
For my case, the solution was:
```
(defun my-org-clock-goto-next-clock ()
(interactive)
(org-back-to-heading)
(search-forward "LOGBOOK:")
(outline-show-subtree)
(org-flag-drawer nil)
(forward-line)
(move-beginning-of-line nil)
)
```
It's probably an accident that `(org-cycle 3)` worked for 9.1.9, since the doc string for `org-cycle` says:
> When there is a numeric prefix, go up to a heading with level ARG, do a ‘show-subtree’ and return to the previous cursor position. If ARG is negative, go up that many levels.
That probably explains the error in 9.3.3.
> 1 votes
---
Tags: org-mode
---
|
thread-31165
|
https://emacs.stackexchange.com/questions/31165
|
Emacs 25.1 & Python 3.6.0 Integration [Newbie]
|
2017-03-01T20:03:51.340
|
# Question
Title: Emacs 25.1 & Python 3.6.0 Integration [Newbie]
**Preface**:
I've been dabbling with python programming for a mere few months now. Previously, I spent most of my programming time using C# with Visual Studio. In the Python world, I've been using PyCharm for my projects. It has excellent code-completion (much like the IntelliSense I'm used to) and a nice level of customizability. However, at the end of the day, I want something a little bit lighter and less clunky. I have seen videos of developers using Emacs with Python and I'm quite interested in learning it.
**Setup**:
* Python 3.6.0 is installed.
* I have downloaded emacs-25.1-x86\_64-w64-mingw32.zip from the Emacs website.
* I have created a folder `C:\emacs` and extracted the zip file to this location
* I have identified the Emacs home folder as `C:\Users\joshu\AppData\Roaming\.emacs.d`
* I have created an `init.el` file in this directory since one did not exist
**Python Integration**:
Now, this is where I'm struggling. I'm still extremely new to the software so it's a bit hard to piece together information from the internet. Using this tutorial I have developed a baseline `init.el` file. Due to my reputation points, I cannot include a third link here. The Gist containing my `init.el` file is commented below.
When I open Emacs and open a python file, editing works. However, I'm running into the issues outlined below:
1. `C-c C-c` returns an error. It seems to be a relatively wide-spread error upon Googling. By simply typing `C-c C-c` again, the shell will appear with the code being executed; however, it gives me the line `python.el: native completion setup failed`
**Edit**: The error is `Warning (python): Your ‘python-shell-interpreter’ doesn’t seem to support
readline, yet ‘python-shell-completion-native’ was t and "python3" is not
part of the ‘python-shell-completion-native-disabled-interpreters’ list.
Native completions have been disabled locally.`
2. Python autocomplete doesn't seem to be working properly. When using PyCharm, I get a much, much more robust offering of completions. In the case of Emacs, if I begin typing something such as `from tkint` it will not suggest `tkinter`. Similarly, if I start typing `from math import a` it will not suggest `abs`. I'm not sure at all how to configure Python autocompletion. I've read a few things about using `pip install jedi` and so on, but I haven't done any of that.
I realize this may be just as much a python question as an Emacs question in some regards. Any insight is appreciated.
# Answer
> 2 votes
This seems to be bug in emacs and its fixed in this commit.
As npostavs mentioned, you can use
```
(with-eval-after-load 'python
(defun python-shell-completion-native-try ()
"Return non-nil if can trigger native completion."
(let ((python-shell-completion-native-enable t)
(python-shell-completion-native-output-timeout
python-shell-completion-native-try-output-timeout))
(python-shell-completion-native-get-completions
(get-buffer-process (current-buffer))
nil "_"))))
```
You can read entire discussion here.
# Answer
> 1 votes
I use the following:
```
(setq
python-shell-interpreter "ipython3"
python-shell-interpreter-args "--simple-prompt --pprint")
```
For python 3.6 I found jedi with company to be the most reliable but others may have different experiences. "mypath" below are the paths to packages I've created that I want autocomplete.
```
(use-package company-jedi
:config
(setq jedi:environment-virtualenv (list (expand-file-name "~/.emacs.d/.python-environments/")))
(add-hook 'python-mode-hook 'jedi:setup)
(setq jedi:complete-on-dot t)
(setq jedi:use-shortcuts t)
(setq jedi:server-args
'("--sys-path" "mypath1"
"--sys-path" "mypath2"))
(defun config/enable-company-jedi ()
(add-to-list 'company-backends 'company-jedi))
(add-hook 'python-mode-hook 'config/enable-company-jedi))
```
# Answer
> 0 votes
In Ubuntu 16.04, I added `python-setuptools` **in addition** to `python3-setuptools`. Problem disappeared.
(I'm using Emacs 25.3.2, from the stable *kelleyk* PPA; Spacemacs user)
# Answer
> 0 votes
Regarding programming Python in emacs, be sure to check out LSP. It is a wonderful initiative that is well maintained and supported.
---
Tags: init-file, python, elpy, jedi
---
|
thread-54302
|
https://emacs.stackexchange.com/questions/54302
|
How to use ispell-word to correct a word immediately without prompting for multiple options?
|
2019-12-11T01:25:26.897
|
# Question
Title: How to use ispell-word to correct a word immediately without prompting for multiple options?
Since the first option is the right one when fixing a common misspelling. Is there a way to make `ispell-word` correct the spelling of a word to the first suggestion instead of prompting from a list of options?
# Answer
> 1 votes
This can be done by overriding the function that prompts for input.
This function runs `ispell-word`, always using the first option.
```
(defun ispell-word-immediate ()
"Run `ispell-word', using the first suggestion."
(interactive)
(cl-letf
(((symbol-function 'ispell-command-loop)
(lambda (miss _guess _word _start _end) (car miss))))
(ispell-word)))
```
In the case you want to one of the other available options, it's possible to cycle through the options. Although the code needed is more involved.
```
(defmacro ispell-word-immediate--with-messages-as-list (message-list &rest body)
"Run BODY adding any message call to the MESSAGE-LIST list."
(declare (indent 1))
`
(let ((temp-message-list (list)))
(cl-letf
(((symbol-function 'message)
(lambda (&rest args)
;; Only check if non-null because this is a signal not to log at all.
(when message-log-max
(push (apply 'format-message args) temp-message-list)))))
(unwind-protect
(progn
,@body)
;; Protected.
(setq ,message-list (append ,message-list (reverse temp-message-list)))))))
(defvar-local ispell-word-immediate--alist nil
"Internal properties for repeated `ispell-word-immediate'")
(defun ispell-word-immediate--impl (cycle-direction)
"Run `ispell-word', using the first suggestion.
Argument CYCLE-DIRECTION The offset for cycling words, 1 or -1 for forward/backward."
(let ((message-list (list))
(index 0)
(point-init (point))
(display-text nil))
;; Roll-back and cycle through corrections.
(when
(and
ispell-word-immediate--alist
(or
(eq last-command 'ispell-word-immediate-forward)
(eq last-command 'ispell-word-immediate-backward)))
;; Roll-back correction.
(let ((alist ispell-word-immediate--alist))
;; Roll back the edit.
(delete-region (alist-get 'start alist) (alist-get 'end alist))
(insert (alist-get 'word alist))
;; Update vars from previous state.
(setq point-init (alist-get 'point alist))
(setq index (+ cycle-direction (cdr (assq 'index alist))))
;; Roll back the buffer state.
(setq buffer-undo-list (alist-get 'buffer-undo-list alist))
(setq pending-undo-list (alist-get 'pending-undo-list alist))
(goto-char point-init)))
;; Clear every time, ensures stale data is never used.
(setq ispell-word-immediate--alist nil)
(cl-letf
(((symbol-function 'ispell-command-loop)
(lambda (miss _guess word start end)
;; Wrap around in either direction.
(setq index (mod index (length miss)))
(let ((word-at-index (nth index miss)))
;; Generate display text.
(setq display-text
(string-join
(mapcar
(lambda (word-iter)
(if (eq word-at-index word-iter)
(format "[%s]" (propertize word-iter 'face 'match))
(format " %s " word-iter)))
miss)
""))
;; Set the state for redoing the correction.
(setq ispell-word-immediate--alist
(list
;; Tricky! but nicer usability.
(cons 'buffer-undo-list buffer-undo-list)
(cons 'pending-undo-list pending-undo-list)
(cons 'point point-init)
(cons 'index index)
(cons 'word word)
(cons 'start (marker-position start))
(cons 'end
(+ (marker-position end)
(- (length word-at-index) (length word))))))
word-at-index))))
;; Run quietly so message output doesn't flicker.
(prog1 (ispell-word-immediate--with-messages-as-list message-list (ispell-word))
;; Log the message, only display if we don't have 'display-text'
;; This avoids flickering message output.
(let ((inhibit-message (not (null display-text))))
(dolist (message-text message-list)
(message "%s" message-text)))
;; Run last so we can ensure it's the last text in the message buffer.
;; Don't log because it's not useful to keep the selection.
(when display-text
(let ((message-log-max nil))
(message "%s" display-text)))))))
;; Public functions.
(defun ispell-word-immediate-forward ()
"Run `ispell-word', using the first suggestion, or cycle forward."
(interactive)
(ispell-word-immediate--impl 1))
(defun ispell-word-immediate-backward ()
"Run `ispell-word', using the first suggestion, or cycle backward."
(interactive)
(ispell-word-immediate--impl -1))
```
# Answer
> 1 votes
There may be other ways of achieving that, but if you use flyspell then it has `flyspell-auto-correct-previous-word` which does just that. It's bound to `C-;` by default.
flyspell will put a wavy red line under spelling errors and so pressing `C-;` will have a go at correcting the first one before the current point, so you don't even need to move the point onto the misspelled word.
Works very nicely for me when I'm writing text in Org-mode, but I assume it works in any mode.
---
Tags: ispell
---
|
thread-55549
|
https://emacs.stackexchange.com/questions/55549
|
org-mode in-buffer todo setting not working as expected
|
2020-02-15T16:34:23.313
|
# Question
Title: org-mode in-buffer todo setting not working as expected
I am using org-mode TODO tracking change (in-buffer settings) and I'm having some issues. All the info is taken from the official docs (https://orgmode.org/manual/Tracking-TODO-state-changes.html)
I have added the buffer setting line at the top:
```
#+TODO: TODO(t) BUG(b) WAIT(w@/!)| DONE(d@/!) CANCELLED(c@/!)
```
and it's working, except two features I would like to have:
1. When changing to the WAIT state, it won't ask me for a note and the timestamp is not recorded either.
2. The DONE state is not grayed out as it's the case with CANCELED, despite both being specified after the "|" pipeline character.
I have not tested the same setting in a global init.el config because I need this setting different for each file.
# Answer
By the time I posted my question I have manage to find the culprit. Posting it with an answer just in case others need to see this.
The setting line was missing a space after the WAIT state and the "|" pipeline, which caused both issues.
Correct syntax:
```
#+TODO: TODO(t) BUG(b) WAIT(w@/!) | DONE(d@/!) CANCELLED(c@/!)
```
> 1 votes
---
Tags: org-mode, todo, buffer-local
---
|
thread-55547
|
https://emacs.stackexchange.com/questions/55547
|
org-mode with variable content
|
2020-02-15T15:10:37.180
|
# Question
Title: org-mode with variable content
Is there a way in org-mode to have variable blocks of text. That is, to select between different bodies of inline text and examples, on the basis of a variable defined earlier.
I'm trying to create a tutorial for carrying out a task using two similar programs, using a single document and varying small parts of the explanation and the examples according to which program I want to export for.
I would have used `\ifthenelse{}{}{}` in LaTeX in the past, but I can't find a clean way to do this with `org-mode`.
# Answer
I think you are looking for drawers. Here is an example org-file you can use to choose the PROG-A text or the PROG-B text on export. You just change the string in the options line, then export to the format you want.
```
#+options: d:("PROG-A")
If you wrap conditional text in drawers you can specify which ones are exported.
:PROG-A:
Use this for program A
:END:
:PROG-B:
Use this for program B
:END:
:PROG-A:
Use other option for program A
:END:
:PROG-B:
Use this other option program B
:END:
```
> 3 votes
---
Tags: org-mode
---
|
thread-55546
|
https://emacs.stackexchange.com/questions/55546
|
Linux command line to launch gnuemacs
|
2020-02-15T13:56:27.180
|
# Question
Title: Linux command line to launch gnuemacs
I would like to launch Emacs by typing a command line in the terminal in Ubuntu linux. I want Emacs to open file `a.txt` in one frame and another file `b.txt` in another frame. I tried the command `*emacs a.txt -f make-frame-command b.txt*` Unfortunately this command does not work. It launches one frame with a split buffer containing `a.txt` and `b.txt` and another frame with just `a.txt`
# Answer
> 0 votes
Any valid elisp code can be executed when starting Emacs with the --eval option. For instance
```
emacs --eval "(progn(find-file \"a.txt\")(find-file-other-frame \"b.txt\"))"
```
or
```
emacs --eval "(find-file \"a.txt\")" --eval "(find-file-other-frame \"b.txt\")"
```
do the trick.
The first --eval command is unnecessary, you can just type
```
emacs a.txt --eval "(find-file-other-frame \"b.txt\")"
```
---
Tags: frames, start-up, command-line-arguments
---
|
thread-55548
|
https://emacs.stackexchange.com/questions/55548
|
TRAMP on Emacs 26 doesn't work (macOS)
|
2020-02-15T16:20:47.563
|
# Question
Title: TRAMP on Emacs 26 doesn't work (macOS)
I've just installed Emacs 26.3 on my macOS 10.10 (Yosemite) using the binary at Emacs for OSX Everything so far works fine icluding new package installations and different themes. However, when I tried to edit a file on my Linux server using this TRAMP line:
```
/myuname@myserver.com:
```
It returned:
```
File not found and directory write-protected
```
and a blank buffer appeared in the window area.
When I tried Emacs-25.3 binary from the same website, that same TRAMP line worked perfectly and I managed to edit file on the server. When I tried Emacs 26.1 and 26.2, the same problem occured again. So I think this problem is specific to Emacs 26.x.
What should I do to make TRAMP work on Emacs 26.x on macOS?
# Answer
> 2 votes
The following is an excerpt from the Quick Start Guide for Tramp, which is built-in to Emacs 26:
https://www.gnu.org/software/emacs/manual/html\_node/tramp/Quick-Start-Guide.html
```
Tramp extends the Emacs file name syntax by a remote component. A remote file
name looks always like /method:user@host:/path/to/file.
You can use remote files exactly like ordinary files, that means you could open
a file or directory by C-x C-f /method:user@host:/path/to/file <RET>, edit the
file, and save it. You can also mix local files and remote files in file
operations with two arguments, like copy-file or rename-file. And finally, you
can run even processes on a remote host, when the buffer you call the process
from has a remote default-directory.
```
The O.P. has indicated in a comment that using `/method:user@host:/path/to/file` has resolved the issue.
* Example using `ssh` and a non-standard port (2222) to connect to the root default directory:
`/ssh:user@host#2222:`
* Example using `ssh` to open a file with a non-standard port (2222):
`/ssh:user@host#2222:/path/to/file`
Here is an example to connect to the root default directory using `eshell` with a non-standard port (2222):
```
(let ((default-directory "/ssh:user@host#2222:"))
(eshell))
```
Here is an example to connect to the root default directory using `shell` with a non-standard port (2222):
```
(let ((default-directory "/ssh:user@host#2222:"))
(shell))
```
To login automatically using an `.authinfo` file, here is a sample entry in that file:
```
machine HOST login USER password PWD
```
To assist with logging in automatically with a non-standard port (2222), one can use an appropriate entry in the `~/.ssh/config` file, which can include other attributes; e.g., HostName and User. https://emacs.stackexchange.com/a/31339/2287
```
Host 12.34.567.89
Port 2222
```
# Answer
> 1 votes
As other answers have mentioned already, Tramp has strengthened its syntax. It requires a mandatory method name now.
You could use `-` as method name if you mean the default method, like in `/-:myuname@myserver.com:`. If you don't what to apply any other method name but the default one, apply `(tramp-change-syntax 'simplified)`. This changes Tramp syntax to `/myuname@myserver.com:`.
All of this is described in the Tramp manual, so you might want to read there. (Disclaimer: I'm the author of that manual).
---
Tags: osx, tramp, emacs26
---
|
thread-55553
|
https://emacs.stackexchange.com/questions/55553
|
How to insert boilerplate code in a file based on the directory in which it is created?
|
2020-02-15T20:06:32.483
|
# Question
Title: How to insert boilerplate code in a file based on the directory in which it is created?
Suppose I have a file `dir1/this_file.txt` and `dir2/this_file.txt`, and I want to insert different boilerplate code not based on the file name or extension, but based on the directory in which the file is created. How can I do that?
-- Edit --
Additionally, what if the boilerplate code depends on the filename of the file being created?
# Answer
> 1 votes
As phils said obtain the directory name
```
(file-name-directory (or buffer-file-name ""))
```
and then open a boilerplate template in that directory is maybe what you want rather than configure the template code in Emacs itself. I knocked this up and it seems to work.
```
(defun insert-boilerplate ()
(let ((boiler-plate-file (expand-file-name ".boilerplate" (file-name-directory (or buffer-file-name "")))))
(if (file-exists-p boiler-plate-file)
(insert-file-contents boiler-plate-file)))
nil)
(add-to-list 'find-file-not-found-functions #'insert-boilerplate)
```
Simply create a .boilerplate file in the directory and it should be good to go.
# Answer
> 0 votes
You can obtain the directory with:
```
(file-name-directory (or buffer-file-name ""))
```
---
Tags: files, skeleton
---
|
thread-55552
|
https://emacs.stackexchange.com/questions/55552
|
How to automatically create another file that matches a regex based on a file created?
|
2020-02-15T20:03:59.033
|
# Question
Title: How to automatically create another file that matches a regex based on a file created?
Suppose I create a file in `dir1/file1.txt`. As soon as I write the file for the first time, I want to create another file in `dir2/file1_friend.txt`. But when I create a file `dir1/file2.txt`, I want the new file created be `dir2/file2_friend.txt`.
# Answer
You can use a `before-save-hook` for this. Note this runs on every buffer save, so we have some checks to make sure we have a buffer file name, that it ends with the right string, and that your new file doesn't already exist. then, if all that is ok, we make the file.
```
(require 'f)
(require 's)
(defun custom-save ()
(let ((bf (buffer-file-name))
(bff "my_file_abc_friend.txt"))
(when (and bf
(s-ends-with? "dir1/my_file_abc.txt" bf)
(not (file-exists-p bff)))
;; I think this means you are in dir1 so we can just make the desired file
(with-temp-file bff
;; add contents here if you want
))))
(add-hook 'before-save-hook 'custom-save)
```
> 1 votes
# Answer
Here the "need a friend" suffix is \_blah.txt.You'd probably want to make it a defvar and maybe include some directory path. But .... it works.
```
(defun friend-file-root-name(f)
(string-match "\\(.*\\)\\(_blah.txt\\)" f)
(match-string 1 f)
)
(defun custom-save-create-friend-file ()
(message "in custom save")
(when (friend-file-root-name (buffer-file-name))
(let ((friend-file (concat (friend-file-root-name (buffer-file-name)) "_friend.txt")))
(message "potential friend file is: %s" friend-file)
(unless (file-exists-p friend-file)
(with-temp-file friend-file
(message "need to create %s" friend-file)
(save-buffer)
)))))
(add-hook 'after-save-hook 'custom-save-create-friend-file)
```
> 1 votes
---
Tags: files
---
|
thread-55556
|
https://emacs.stackexchange.com/questions/55556
|
ESS: display-buffer-alist reusable-frames does not work as expected
|
2020-02-15T21:42:48.047
|
# Question
Title: ESS: display-buffer-alist reusable-frames does not work as expected
I'm trying to use the `display-buffer-alist` variable to control how Emacs displays spawned inferior shells (ess-r in particular).
I'm using the `display-buffer-alist` value from ess doc:
```
(setq display-buffer-alist
'(("*R"
(display-buffer-reuse-window display-buffer-pop-up-frame)
(reusable-frames . 0))))
```
However, when I start an `R` shell from some `ess-r-mode` buffer, the `reusable-frames` option does not seem to work: after creating a new frame displaying the `R` shell, Emacs displays a second instance of the `ess-r-mode` buffer in this new frame instead of returning to the old instance. Everything works correctly when I set `reusable-frames` globally:
```
(setq display-buffer-reuse-frames 0)
```
but this should not be necessary.
How can I make `display-buffer-alist` work properly without touching global settings?
Versions:
* GNU Emacs 26.1
* Linux 5.4.0-3-amd64 #1 SMP Debian 5.4.13-1 (2020-01-19) x86\_64 GNU/Linux
* Debian bullseye
# Answer
> How can I make `display-buffer-alist` work properly without touching global settings?
The fault here lies not with `display-buffer`, but with the ESS package, specifically the code in `lisp/ess-inf.el`. You should report this as a bug on their issue tracker, quoting the information below.
---
Firstly, `"*R"` is not a valid regexp, as the asterisk is a special character. In order to match it literally, it should be quoted with a literal backslash. So the correct regexp would be:
```
(rx "*R") ; => "\\*R"
```
or better yet, to avoid false positives:
```
(rx bos "*R*") ; => "\\`\\*R\\*"
```
So the correct overall incantation would be:
```
(setq display-buffer-alist
`((,(rx bos "*R*")
(display-buffer-reuse-window display-buffer-pop-up-frame)
(reusable-frames . 0))))
```
or:
```
(setq display-buffer-alist
'(("\\`\\*R\\*"
(display-buffer-reuse-window display-buffer-pop-up-frame)
(reusable-frames . 0))))
```
---
Secondly, the erroneous behaviour you describe happens only the first time one types `C-c``C-z` (`ess-switch-to-inferior-or-script-buffer`) in an `ess-r-mode` buffer, i.e. before the corresponding inferior `*R*` process buffer has been created.
This is because `ess-force-buffer-current` calls `ess-request-a-process` with a non-`nil` `noswitch` argument when an inferior process does not already exist.
`ess-request-a-process`, in turn, does the following as its last step:
```
(if noswitch
(pop-to-buffer (current-buffer)) ;; VS: this is weird, but is necessary
(pop-to-buffer (buffer-name (process-buffer (get-process proc)))))
```
This call to `(pop-to-buffer (current-buffer))` is wrong and is what causes your `ess-r-mode` buffer to appear a second time in the new frame. It was added in the following commit from 2012: https://github.com/emacs-ess/ESS/commit/b29ea8f934f7c08a512c73f14e914bca7229b3c1
I boldly say it is wrong because popping to the current buffer is quite an intrusive operation (as indicated by the bug in question), and the original intention of the author can almost definitely be written in a better way. I don't know what issue the author originally faced, but perhaps the ESS devs can figure it out.
> 3 votes
---
Tags: buffers, frames, ess
---
|
thread-54974
|
https://emacs.stackexchange.com/questions/54974
|
Directory Variable: .dirs-local.el with regexp
|
2020-01-17T11:33:25.000
|
# Question
Title: Directory Variable: .dirs-local.el with regexp
We can specify modes :
```
(c-mode . ((c-file-style . "BSD")
(subdirs . nil)))
```
Or directories :
```
("src/imported"
. ((nil . ((change-log-default-name . "ChangeLog.local")))))
```
Is there a way to specify a regexp matching files (or even directories) ? i.e:
```
(".*_test.go" . . ((nil . ((change-log-default-name . "ChangeLog.local")))))
```
# Answer
The capabilities are documented at `C-h``i``g` `(emacs)Directory Variables`
What you've asked for isn't supported; so no, you can't have regexps matching files or directories.
> 1 votes
# Answer
Is there any reason you can't simply do the regexp yourself in a .dir-locals assignment? eg just pasted from another exercise the assignment of fname could be based on a regexp matching the buffer-file-name
```
((nil . ((eval . (progn
(setq boilerplate (with-temp-buffer
(insert-file-contents ".boilerplate")
(buffer-string)))
(setq fname (buffer-file-name)) ; <--- do something with a regexp here to match the filename for type eg *.c etc.
)))))
```
> 0 votes
---
Tags: directory-local-variables
---
|
thread-52369
|
https://emacs.stackexchange.com/questions/52369
|
helm-ag , use word at point as input conditionally
|
2019-08-27T08:16:29.167
|
# Question
Title: helm-ag , use word at point as input conditionally
I'd like to create two keybindings for `helm-do-ag-project-root` or `helm-project-ag`
where one would have `(setq helm-ag-insert-at-point nil)` and one would have `(setq helm-ag-insert-at-point 'symbol)`
So that I can selectively use word at-point for search.
Below is my attempt but not working.
```
(use-package helm-projectile
:ensure t
:config
(defun my-helm-grep-do-git-grep ()
(setq helm-ag-insert-at-point nil)
(helm-projectile-ag)
)
(global-set-key (kbd "C-c g") 'my-helm-grep-do-git-grep)
(defun my-helm-grep-do-git-grep-at-point ()
(setq helm-ag-insert-at-point 'symbol)
(helm-projectile-ag)
)
(global-set-key (kbd "C-c k") 'my-helm-grep-do-git-grep-at-point)
)
```
# Answer
This worked fine for me when I was using `helm-ag`:
```
(defun mu-helm-ag-thing-at-point ()
"Search the symbol at point with `helm-ag'."
(interactive)
(let ((helm-ag-insert-at-point 'symbol))
(helm-do-ag-project-root)))
```
> 1 votes
# Answer
You should make your functions interactive (see here).
You could also try the `helm-grep-do-git-grep` command, which I think is a lot smarter at solving this issue. For example, it *always* searches the symbol at point if it finds one, but as soon as you start typing the Helm buffer updates automatically to display the new candidates.
> 0 votes
# Answer
In Helm, `M-n` can be used to select thing at point. In most cases.
> 0 votes
---
Tags: helm, helm-projectile, helm-ag
---
|
thread-55582
|
https://emacs.stackexchange.com/questions/55582
|
Run an external program with customized environment/options in current buffer
|
2020-02-17T08:51:57.870
|
# Question
Title: Run an external program with customized environment/options in current buffer
How can I organize Emacs to run a specific external program with some specific environment/options for the mode or the buffer currently open.
My current solution is to use `setenv` before running the external program, however it seems to change the environment for all the buffers in Emacs.
# Example
To work around a bug in Groovy 3.0.0 (see below) I need to set some java option before running `groovysh`. In terminal, I can do the following:
```
JAVA_OPTS=--add-opens=java.base/jdk.internal.jrtfs=ALL-UNNAMED groovysh
```
However, Emacs run `groovysh` thanks to `run-groovy` function from the inf-groovy.el file in groovy package. So I usually run `eval-expression` with:
```
(setenv "JAVA_OPTS" "--add-opens=java.base/jdk.internal.jrtfs=ALL-UNNAMED")
```
which solves the problem, the inferior Groovy process is now working.
However, all my other buffers now use this value for this environment variable which is not desirable, since I need some other specific java options for other codes. My current solution is to invoke `setenv` every time I change buffer.
## groovysh 3.0.0 not working with jdk 11.0.6
Open a simple file in groovy mode and try to `run-groovy`
With Groovy 3.0.0 and JDK 11.0.6 installed it raises an error:
```
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:111)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:129)
Caused by: java.lang.IllegalAccessException: class org.codehaus.groovy.runtime.callsite.PlainObjectMetaMethodSite cannot access class jdk.internal.jrtfs.JrtFileSystem (in module java.base) because module java.base does not export jdk.internal.jrtfs to unnamed module @6d4e5011
```
It took me a while to figure out that it was a problem due to version incompatibility between groovy and java, see https://issues.apache.org/jira/browse/GROOVY-9390
# Answer
> 3 votes
See `C-h``v` `process-environment`
> List of overridden environment variables for subprocesses to inherit. Each element should be a string of the form ENVVARNAME=VALUE.
>
> Entries in this list take precedence to those in the frame-local environments. Therefore, let-binding `process-environment` is an easy way to temporarily change the value of an environment variable, irrespective of where it comes from. To use `process-environment` to remove an environment variable, include only its name in the list, without "=VALUE".
>
> This variable is set to nil when Emacs starts.
>
> **If multiple entries define the same variable, the first one always takes precedence.**
>
> Non-ASCII characters are encoded according to the initial value of `locale-coding-system`, i.e. the elements must normally be decoded for use.
>
> See `setenv` and `getenv`.
Therefore you can tweak your approach like so:
```
(let ((process-environment process-environment))
(push "JAVA_OPTS=--add-opens=java.base/jdk.internal.jrtfs=ALL-UNNAMED"
process-environment)
;; run groovysh here
(groovy-load-file (buffer-file-name)))
```
---
Tags: environment, prog-mode, inferior-buffer
---
|
thread-28008
|
https://emacs.stackexchange.com/questions/28008
|
How do I paste code without auto indentation
|
2016-10-22T01:04:39.190
|
# Question
Title: How do I paste code without auto indentation
I just setup the latest Spacemacs. I'm pasting python code from here https://raw.githubusercontent.com/jpmens/mosquitto-auth-plug/master/examples/http-auth-be.py into a new buffer.
When I do this it indents almost every single line relative to the last. I'm using spacemacs from iTerm2 on OSX. I'm using Evil mode. I've tried toggling the value `electric-indent-mode` but ti doesn't help. I've also tried the command `:set paste`, but it gives me the error `State paste cannot be set as initial Evil state`.
So firstly, how do I stop the auto indentation? Secondly, what does the error message mean about the initial Evil state and how do I correct it?
# Answer
Because you're using Emacs inside of a terminal emulator, it can't generally tell the difference between something that was typed in and something that is pasted in. You do have some options, though.
You could run Emacs directly, rather than running it inside of a terminal emulator. As a gui app Emacs can tell the difference and act accordingly.
If you're using Emacs 24 (or earlier), and your terminal supports the "bracketed paste" feature, then you can install the `bracketed-paste` Emacs package. If your terminal supports this feature, then it will surround your pastes with escape sequences. The `bracketed-paste` package uses these escape sequences to turn off indentation and other automatic behaviours for the duration of the paste.
If you're using Emacs 25, then you don't need to install any packages; bracketed pastes are supported out of the box. Perhaps iTerm2 doesn't support them, or perhaps you have to enable them first.
> 5 votes
# Answer
What I've done is get out of emacs.
cat \<somefile
paste the contents into the terminal
type EOF
Then read the file with emacs.
Ken
> 1 votes
# Answer
The following works for me, works with both keyboard or mouse copy-pasting:
```
- emacs in a terminal
- remember your current mode
- copy
- go to text-mode M-x text-mode
- paste
- go back to the mode you were in before
```
> -1 votes
---
Tags: evil, spacemacs
---
|
thread-55557
|
https://emacs.stackexchange.com/questions/55557
|
Elisp to get the language mode for the current ein cell?
|
2020-02-16T02:39:35.763
|
# Question
Title: Elisp to get the language mode for the current ein cell?
When I'm using ein to run a python jupyter notebook, the `major-mode` variable is just `"ein:notebook-multilang-mode"` which makes it ambiguous what the current language is. I have elisp that only activates when `major-mode` is `python-mode` so it doesn't currently work for Python inside ein notebooks. Just checking for `"ein:notebook-multilang-mode"` doesn't seem right because that could also be Julia or some other language.
What should I be checking instead?
# Answer
> 1 votes
Unfortunately, it seems like things don't quite work the way you would like them to.
`ein:notebook-multilang-mode` is simply a major mode. That means a lot of things, but here it basically defines fontification (i.e. "syntax highlighting"). You can see that from the source code, available via help (`C-h f ein:notebook-multilang-mode`). The docstring for my version of `ein` (likely outdated) also happens to state,
> A mode for fontifying multiple languages.
What this means is that each cell will receive different highlighting based on the language. This is different from each cell providing a different *environment* according to the language.
The challenge is that Emacs generally works on a *per buffer* basis. That's the most common and natural unit to work with from an implementation standpoint. The modes which dictate the behaviors for Python, R, or Markdown need a way to know when and how to apply the rules (such as indentation, identifying keywords, interaction with an interpreter, etc.) that make, say, R mode different from Python mode.
It's natural to envision an `ein` cell also being aware of the corresponding language mode. (This is what I understand your question to be about.) However, from an implementation perspective, it's not clear how that would be accomplished. It's an interesting problem. You have to answer questions like, "How will binding X work if the behavior might need to differ on line 14 versus line 355?" For example, if you have both R and Python cells, a binding might reach out to an interpreter. How would a given cell know which interpreter to contact? Are instances between Python cells associated?
All of this could be accomplished; it just doesn't seem like `ein` has done so<sup>1</sup>. There are packages such as `MmmMode` and `Mu Ma Mo` whose goals are multiple modes operating at the sub-buffer level. Maybe one of those could be used to implement such functionality.
I'd be remiss, however, if I didn't mention Org babel. It provides the ability to do literate programming, with multiple, concurrent languages and the ability to specify which interpreter (i.e. "kernel") to use for each block (i.e, "cell"), *as well as* export to HTML, PDF, Latex, etc. Each source block can be expanded to a separate buffer whose mode is automatically set to the appropriate language. You can also "tangle" (extract) the code blocks into a single .py or .r file. And so on. I understand if you're bound to Jupyter Notebooks, though.
---
<sup>1</sup> Maybe you could implement it. That would be a cool contribution!
---
Tags: python, polymode, ein, jupyter
---
|
thread-55586
|
https://emacs.stackexchange.com/questions/55586
|
Regexp for matching quoted strings that may have control characters in them
|
2020-02-17T13:35:00.660
|
# Question
Title: Regexp for matching quoted strings that may have control characters in them
I am trying to use a regexp to match strings, e.g. a pattern that matches these kinds of quoted strings:
`"test"` or `'test'` or `'test with "quote"'` or `"test with 'quote'"`
This pattern matches all those,
`"\\(\"\\|'\\)[^\\1]+?\\1"`
but, it fails on `"test\n"` (and other control characters like `\t` and `\r`). I don't understand why `\n` (a newline) is so special it doesn't match `[^\\1]` which I thought was a character that doesn't match the opening quote. Is this expected?
If I replace `[^\\1]` with `.` then it works on all the strings, including the one with `\n` in it. I guess it is ok because `+?` makes it nongreedy so it seems to not over match.
Note, this question originated from How to highlight in different colors for variables inside \`fstring\` on python-mode.
# Answer
`[^\\1]` and `[^\1]` match the same thing: any single character except `1` or `\`. The doc is clear about this. **`\` and `1` are not special inside `[`...`]`.**
Negation, other than in a character alternative, is not possible using a regular expression. Use Lisp code instead. For example, find something that might include what you don't want, test it, and exclude it if it's something you don't want.
(Suggestion: describe your *real* problem \- the problem for which you thought regexp-searching would provide a solution directly.)
> 3 votes
# Answer
You asked about regexps. But from my perspective this is rather an X-Y-problem.
This is an answer to your real question how to find strings in buffers with major mode derived from `prog-mode` assuming that its syntax table is set-up.
Instead of trying to compose a suitable regexp you can use the syntax parser built-in to Emacs. The following code shows how you can do that.
The main tools are:
* `syntax-ppss` for requesting the current state of the syntax parser
* `parse-partial-sexp` for fleeing comments and for finding the beginning of strings (and comments)
* `scan-sexp` for finding the end of the string
Note, that it should be possible to use this function as `MATCHER` for `font-lock-keywords` and related.
```
(defun my-find-next-string (&optional bound)
"Find the next string up to BOUND.
BOUND defaults to `point-max'.
If we start within a string we skip to its end
and start there with the search."
(unless bound
(setq bound (point-max)))
(let ((state (syntax-ppss))
start
end)
;; starting within string or comment:
(when (nth 8 state)
(setq state (parse-partial-sexp (point)
bound
nil nil
state
'syntax-table)))
;; searching for strings, skipping comments
(while (and
(setq state (parse-partial-sexp (point)
bound
nil nil
state
'syntax-table))
(< (point) bound)
(null (setq start (and (nth 3 state)
(nth 8 state)))))) ;; inside string
(when start
(unwind-protect
(set-match-data
(list (goto-char start)
(goto-char (scan-sexps (point) 1))
))
nil)
(point))))
```
> 4 votes
---
Tags: regular-expressions
---
|
thread-26835
|
https://emacs.stackexchange.com/questions/26835
|
Emmet-mode: Wrapping individual lines in HTML tags
|
2016-09-04T15:11:43.180
|
# Question
Title: Emmet-mode: Wrapping individual lines in HTML tags
I'm new to Emacs, new to Emmet, and new to Stack Overflow.
I'm trying to wrap a list of text in individual html tags.
Home
About
Something
is supposed to become
```
<ul>
<li>Home</li>
<li>About</li>
<li>Something</li>
</ul>
```
Apparently emmet has an abbreviation for this. (Documented here: http://docs.emmet.io/actions/wrap-with-abbreviation/)
Following these instructions, I select my 3 lines of text, hit C-c w to bring up the emmet wrap function, enter ul\>li\* and hit RET. But instead of the expected
```
<ul>
<li>Home</li>
<li>About</li>
<li>Something</li>
</ul>
```
I get
```
<ul>
<li></li>
</ul>
```
I've tried experimenting with the $# placeholder but that didn't help.
Wraping a selected text in a single tag works fine (select text -\> C-c w -\> p -\> RET to create a p-tag with the selected text in it). Creating multiple tags, each with the same text in it also works fine (select text -\> C-c w -\> ul\>li\*3 will create a ul with 3 items, each one has the selected text in it).
Supposedly the * operator (without a number) repeats something for each line highlighted, but that doesn't seem to work. Is this feature not available in Emacs' emmet-mode or am I doing something wrong?
# Answer
> 0 votes
It's not `emmet-mode`, but `web-mode-surround` from `web-mode` performs the desired function for any tag (it asks for a tag name in the minibuffer)
---
Tags: html, emmet
---
|
thread-55593
|
https://emacs.stackexchange.com/questions/55593
|
Matching pairs for character bound to a keystroke
|
2020-02-17T18:30:06.153
|
# Question
Title: Matching pairs for character bound to a keystroke
I am using `smartparens` with AucTeX and it works great. I wanted to map a keystroke for the dollar sign, so I did it as follows -
```
(global-set-key (kbd "s-m") (lambda () (interactive) (insert "$")))
```
But if I enter a dollar sign using the above keystroke, I no longer get a matching dollar sign as opposed to if enter a dollar sign the normal way (`shift`+`4`).
I'm not sure I understand why this happens. If anyone could point to the right place in the documentation so I can work out a fix, it'd be much appreciated.
# Answer
The issue was the dollar-sign key was bound to command `TeX-insert-dollar`, which can take an optional argument indicating the number of dollar signs to print.
This is why mapping the same key to inserting the character `$` did not work.
To make it work, I just bound the key to a command that invokes `TeX-insert-dollar`, passing `2` as the argument, and all works fine.
```
(global-set-key (kbd "s-m")
(lambda ()
(interactive)
(TeX-insert-dollar 2)
(backward-char 1)))
```
> 1 votes
---
Tags: auctex
---
|
thread-54563
|
https://emacs.stackexchange.com/questions/54563
|
automatically open new buffer in new frame
|
2019-12-28T14:59:17.910
|
# Question
Title: automatically open new buffer in new frame
I use tiling window manager and usually prefer it to handle emacs frames instead of using emacs windows. Is there a way I could force emacs to spawn new buffers in new frames automatically? Ideally this behavior should be toggled via some command.
# Answer
`C-h v pop-up-frames` tells you this. It should get you much of the way there.
> **`pop-up-frames`** is a variable defined in `window.el`.
>
> Its value is `t`
>
> Original value was `nil`
>
> Documentation:
>
> Whether \`display-buffer' should make a separate frame.
>
> If `nil`, never make a separate frame.
>
> If the value is `graphic-only`, make a separate frame on graphic displays only.
>
> Any other non-`nil` value means **always make a separate frame**.
>
> You can customize this variable.
---
This, and its linked pages, might also help, at least by describing some of the problems of trying to use frames-only by default.
> 7 votes
# Answer
`pop-up-frames` certainly does the trick but it is too awkward to use. It will spawn **everything** in new frame.
Much finer control may be reached by using `display-buffer-alist`. It allows conditionally opening buffers in new frames.
I wrote a small minor mode `pop-up-frames-mode` using `display-buffer-alist` method:
```
;; https://stackoverflow.com/a/1511827/5745120
(defun which-active-modes ()
"Which minor modes are enabled in the current buffer."
(let ((active-modes))
(mapc (lambda (mode) (condition-case nil
(if (and (symbolp mode) (symbol-value mode))
(add-to-list 'active-modes mode))
(error nil) ))
minor-mode-list)
active-modes))
(defun pop-up-frames-switch-to-buffer (buffer alist)
"Pop up frames switch to buffer command."
(member 'pop-up-frames-mode (which-active-modes)))
(setq display-buffer-alist
(append display-buffer-alist
'((pop-up-frames-switch-to-buffer . ((display-buffer-reuse-window display-buffer-pop-up-frame) . ((reusable-frames . 0)))
))))
(define-minor-mode pop-up-frames-mode
"Pop up frames minor mode"
:lighter " PUF")
(provide 'pop-up-frames-mode)
```
It spawns new frame only when `pop-up-frames-mode` is enabled in current buffer and does not create duplicate windows.
> 1 votes
---
Tags: frames
---
|
thread-55598
|
https://emacs.stackexchange.com/questions/55598
|
How to prevent the completion window from hogging up nearly whole frame (-3 lines)?
|
2020-02-17T22:04:16.727
|
# Question
Title: How to prevent the completion window from hogging up nearly whole frame (-3 lines)?
One or the other of the various Emacsen has been, at different times, my one and only editor on all \*nix systems¹. I usually use one X window per buffer, so I can arrange windows side by side, or use windows manager shortcuts to switch. So, one file, one tall 80x55 window. Fig 1.
When I hit TAB in the window above, I'm getting this (Fig 2). The temporary completion window hogs up all but 3 lines of the frame. The same exact thing happens in any edit mode, as long as the completion list is long enough.
Nothing really drastic happens, any cursor movement command dismisses the unhelpful completion window, but I'm visually lost in the file for a moment: if I was editing near the bottom of the frame, the contents of the buffer scrolls up, and what I might have looked at is now above the top of window.
I suspect, but won't claim under sworn oath, this behavior is new to Emacs 24. Before that, the completion buffer height was visually about half of the window height. And, fellow Emacsierres, it's annoying enough that it makes me swear at times without any oath in sight.
It is also worth noting that the problem affects *only temporary completion windows*. For example, Help on function or variable pops up at the bottom, taking exactly 1/2 window height, just the way I'm used to (Fig. 3).
---
I tried:
1. Per this answer, customized `window-combination-resize` to `t`. Zero effect.
2. After digging some more, set `temp-buffer-max-height` to `(lambda (buffer) (/ (- (frame-height) 2) 2))`². The size it computes is quite sensible (27 for my 55-line buffer). Nope, nothing changed. What *troubles me here* is that the totally nebulous computation that I removed (see the note² for details) did not affect anything.
I should make it clear that my other displays have 100% scaling, aren't close to 4K high-DPI and other buzzwords, but still the completion want all but 3 lines of the window and messes up my scrolling position of the file I edit. So high-DPI is **certainly not** part of the problem. I'm just writing this question on the go, from that high-DPI laptop.
I'm out of ideas, really, thanks for any help.
---
¹ Coincidentally, albeit not very relevant to the point, I'm responsible for a lot of C ad .el code in the once-wannabe-competitor project, XEmacs, likely more than half of its MS-windows-specific part, in the mid 1990s when Emacs updates slowed to nil, so I'm not exactly a n00b; but some stuff I forgot, and some things changed in these 25 years beyond recognition. By now, I should grade myself a n00b+, no higher. Please bear with me.
² The original value from help.el
```
(lambda (buffer)
(if (and (display-graphic-p) (eq (selected-window) (frame-root-window)))
(/ (x-display-pixel-height) (frame-char-height) 2)
(/ (- (frame-height) 2) 2)))
```
was also sensible, but only as long as your font scaling is set to 100% on an MS Windows desktop. With a "high-DPI" laptop, the function produced nonsensical values. With my 200% font scaling, `(x-display-pixel-height)` returned exactly half screen pixel height, 1080 vs actual 2160, and `(frame-char-height)` 14 instead of actual 55, 4 times less--looks like the scaling was applied the wrong way, inconsistently, and twice. I do not know if this is an Emacs or the X Server issue, but anyway, I got rid of this bogus branch. I'm leaving this note for high-DPI users, just in case. Did me neither help nor harm, but was clearly wacky.
# Answer
> What *troubles me here* is that the totally nebulous computation that I removed did not affect anything.
And for a reason. The `temp-buffer-max-height` variable does not have any effect unless another variable, namely `temp-buffer-resize-mode`, is set to `t`. Both variables are customizable. This is *kind of* documented with the `temp-buffer-max-height` variable help:
> This is effective only when Temp Buffer Resize mode is enabled.
This assumes that the reader is aware what does the “Temp Buffer Resize mode” do, how to tell if it is enabled, and how to enable it if it is not. I was not.
And yeah, my impression that the behavior is fairly recent was correct: looking at the change history, `temp-buffer-max-height` was added in the version 24.3.
> 1 votes
---
Tags: window, completion, window-splitting
---
|
thread-55601
|
https://emacs.stackexchange.com/questions/55601
|
re-search-forward Regex behavior for OR boolean
|
2020-02-18T03:36:43.260
|
# Question
Title: re-search-forward Regex behavior for OR boolean
We usually use `\|` to depict OR in Regex. Using `a\|b` as input to `Regexp I-search` and `Occur` both gave the desired result. But `re-search-forward` seems unable to recognize this notation.
> abcdcba
```
(re-search-forward "a\|b")
;; Search failed: "a|b"
```
# Answer
> 3 votes
Elisp regexps are represented as strings, which means backslashes are interesting, as they are not only special to regexps, but also when writing strings.
Emacs requires a literal `\` character to be escaped in the double-quoted *read syntax* for strings and so, when the code is processed by the *lisp reader*, `"\\"` becomes a string *object* containing a single `\` character; and hence that single backslash is what the regexp engine sees when it uses that string object.
So in your instance, the regexp `a\|b` is represented by `"a\\|b"` in the double-quoted read syntax for strings.
Conversely `"a\|b"` is the regexp `a|b` (because `\|` is not a special construct in the read syntax for strings, so all we have done there is needlessly escaped a `|` character; hence `"a\|b"` is no different to `"a|b"`), and `a|b` contains no regexp-special constructs, so it matches the three-character sequence `a|b` literally.
The elisp manual explains further:
```
`\' has two functions: it quotes the special characters (including
`\'), and it introduces additional special constructs.
Because `\' quotes special characters, `\$' is a regular
expression that matches only `$', and `\[' is a regular expression
that matches only `[', and so on.
Note that `\' also has special meaning in the read syntax of Lisp
strings (*note String Type::), and must be quoted with `\'. For
example, the regular expression that matches the `\' character is
`\\'. To write a Lisp string that contains the characters `\\',
Lisp syntax requires you to quote each `\' with another `\'.
Therefore, the read syntax for a regular expression matching `\'
is `"\\\\"'.
```
-- `C-h``i``g` `(elisp)Regexp Special`
It is also worth noting that `\` is not special within a character alternative (this is also true for most other regexp-special characters), and therefore `[\]` (aka `"[\\]"`) matches a backslash.
```
As a `\' is not special inside a character alternative, it can never
remove the special meaning of `-' or `]'. So you should not quote
these characters when they have no special meaning either. This would
not clarify anything, since backslashes can legitimately precede these
characters where they _have_ special meaning, as in `[^\]' (`"[^\\]"'
for Lisp string syntax), which matches any single character except a
backslash.
```
---
Tags: regular-expressions, string, backslash
---
|
thread-55574
|
https://emacs.stackexchange.com/questions/55574
|
Unbind key in org-mode (with evil-mode)
|
2020-02-16T23:43:42.310
|
# Question
Title: Unbind key in org-mode (with evil-mode)
I cannot unbind the key `M-l` in org-mode.
When the cursor is in an org-mode buffer, I tried to eval (`M-:`)
```
(unbind-key "M-l" org-mode-map)
;; ^^^ from bind-key.el
(define-key org-mode-map (kbd "M-l") nil)
```
But `C-h k M-l` always says:
```
M-l runs the command org-demote-subtree (found in org-mode-map), which
is an interactive compiled Lisp function in ‘org.el’.
It is bound to M-l, C-c C->, <normal-state> M-l.
```
Same problem for other keys, e.g. `C-k`. I also use bind-key.el for other bindings, in case that is of interest.
# Answer
> 3 votes
I always use helpful-key to unbind my keys. It's not mandatory but gives better readability.
As you know, for different Emacs configuration everybody has different modes keybindings. So there is not any exact answer for everybody, but there is same path that can lead you to unbind unwanted keys.
The way that I do.
1. Install package
2. M-x `helpful-keybind`
3. Press `M-l`
**Key Bindings(Before)**
```
evil-org-mode-map <insert-state> M-l
evil-org-mode-map <normal-state> >
evil-org-mode-map <normal-state> M-l
org-mode-map ESC <right>
```
4. Depends on your keybinding, apply this changes
```
(define-key evil-org-mode-map (kbd "<insert-state> M-l") nil)
(define-key evil-org-mode-map (kbd "<normal-state> M-l") nil)
```
**Key Bindings(After)**
```
esc-map l
global-map M-l
```
---
Tags: org-mode, key-bindings
---
|
thread-55599
|
https://emacs.stackexchange.com/questions/55599
|
Define a function in Calc (Embedded)
|
2020-02-17T22:22:11.743
|
# Question
Title: Define a function in Calc (Embedded)
In Calc Embedded Mode, you can define a variable with the `:=` operator. You can then use it in an equation using the `=>` operator and it will be automatically updated when you change the variable. See (calc) Assignments in Embedded Mode.
*Example:*
* Create a new buffer containing:
```
x := 3
x + 2 => 9999
```
* Invoke `calc-embedded-activate` (`C-x * a`)
* Invoke `calc-embedded-update-formula` (`C-x * u`) on the bottom equation. It changes to `x + 2 => 5`
* Now enter embedded mode on the top equation and change it to `x := 30`. The bottom one will change to `x + 2 => 32`.
But this doesn't work with functions. Create a buffer containing
```
f(x) := 2 x
f(2) => 9999
```
Invoke `C-x * a` anywhere and invoke `C-x * u` on the bottom equation. It changes to `f(2) => f(2)`. Changing the top equation doesn't affect the bottom one.
Is there any way to define a function from within Calc or does it have another way of dealing with this? I know of `defmath` but that doesn't help in e.g. a Latex document (unless you define the function twice, likely making mistakes).
# Answer
> 3 votes
This probably won't be very satisfying but you can use the anonymous function syntax and call the function with the `call` function:
```
f := <x : 2 x>
call(f, 7) => 14
```
(Sadly `f(7)` doesn't work.)
---
Tags: calc
---
|
thread-55611
|
https://emacs.stackexchange.com/questions/55611
|
Counting number of matches in number of lines for regex search
|
2020-02-18T11:40:49.507
|
# Question
Title: Counting number of matches in number of lines for regex search
I have functions that run `re-search-forward` and gather its output into a buffer.
```
(defun my-search (pattern)
"Uses `re-search-forward` to return matching lines."
(let ((src)
(rslt))
(progn
(goto-char (re-search-forward pattern))
(save-excursion
(setq rslt (buffer-substring (progn (beginning-of-line-text)(point))
(progn (end-of-line) (point)))))
(format "%s\n\n" rslt))))
(defun my-search-results ()
"Iterate through buffer with `my-search` and gather matching lines into a buffer."
(interactive)
(let ((pattern (read-regexp "Regex Pattern to Search for: "))
(rslt (generate-new-buffer "*Search Results*"))
(match 0)
(nlines 0)
(current-line 0))
(while (not (eq (ignore-errors (save-excursion (re-search-forward pattern))) nil))
(princ (my-search pattern) rslt)
(incf match))
(switch-to-buffer "*Search Results*")))
```
We all know that `Occur` will display `"%d matches in %d lines."` in its search result. How do we do the same for these functions without repetition when there is more than one match in a line?
Currently, `match` would keep track of the number of iteration cycles, which should be equivalent to the number of matching pattern found.
Adding an `if` clause to `my-search-results` doesn't solve the problem.
```
(defun my-search-results ()
(interactive)
(let ((pattern (read-regexp "Regex Pattern to Search for: "))
(rslt (generate-new-buffer "*Search Results*"))
(match 0)
(nlines 0)
(current-line 0))
(beginning-of-buffer)
(while (not (eq (ignore-errors (save-excursion (re-search-forward pattern))) nil))
(princ (my-search pattern) rslt)
(incf nlines)
(incf match)
(if (= (line-number-at-pos)
(save-excursion
(progn
(re-search-forward pattern)
(point))))
(progn (re-search-forward pattern)
(incf match))))
(message "%d matches in %d lines." match nlines)
(switch-to-buffer "*Search Results*")))
```
---
# Test Data:
```
abacd
efgja
ogjfh
```
# Desired Outcome:
`M-x``my-search-results a`
```
;; Result:
;; abacd
;; efgja
;; 3 matches in 2 lines.
```
# Answer
I took your code as base and rewrote it somewhat.
The following function is *one possible* solution to solve that problem in one function:
```
(defun my-search-results (pattern)
(interactive (list (read-regexp "Regex Pattern to Search for: ")))
(let ((result-buffer (generate-new-buffer "*Search Results*"))
(matches 0)
(lines 0)
(last-printed-line -1))
(save-excursion
(beginning-of-buffer)
(while (re-search-forward pattern nil t)
(incf matches)
(let ((line-number-at-pos (line-number-at-pos)))
(unless (= line-number-at-pos last-printed-line)
(incf lines)
(setq last-printed-line line-number-at-pos)
(princ (thing-at-point 'line t) result-buffer)))))
(switch-to-buffer "*Search Results*")
(message "%d matches in %d lines." matches lines)))
```
*Notes about changes:*
* I moved `save-excursion` out of the loop, because this function call is expensive and would slow down the loop without benefit. This is also responsible, that `point` is locatet at the last match and I can get the current line number
* I compare current line number with the last printed line number to decide weather to increase `lines` and print, or not.
* I used `thing-at-point` to get the current line as a string
* I used available parameters of `re-search-forward` to suppress errors.
> 1 votes
---
Tags: regular-expressions, search
---
|
thread-55369
|
https://emacs.stackexchange.com/questions/55369
|
Compile output re-write
|
2020-02-07T20:53:37.060
|
# Question
Title: Compile output re-write
I'm working with an old compiler that puts out error lines like this:
```
./code\driver.c(327): WARNING C4200: Other...
```
I need to fix a couple things:
1. Fix the path from Wine/DOS mode to local: ./code\driver.c -\> driver.c
2. Rewrite "Entering directory ..." lines
3. Rewrite the line info: driver.c(327): -\> driver.c:327
4. And keep everything after that intact
Anybody know a way to re-write compile output to be emacs compatible?
I ended up writing a Python script, but I wouldn't be surprised if there is something directly in emacs that can do all this.
# Answer
Is that output in the command line or in an emacs compilation buffer?
If it is in a compilation buffer in Emacs, then you just need to make this buffer writeable again and then you can do text replacement with a couple of regex. Its rather simple to stuff all that in a command.
i.e
```
(defun simple-cleanup-compile-buffer ()
(interactive) ;; mark as command, so it is callable via `M-x`
(read-only-mode -1) ;; make compile buffer writeable
(goto-char 0) ;; goto beginning of buffer
(replace-regexp "\\([.A-z0-9]\\)\\\\\\([A-z0-9 ]\\)" "\\1/\\2") ;; replace \ with /
;; more regexps here ...
(read-only-mode 1))
```
Since you wrote that in phython, I guess you are able to figure out the other regexs yourself.
This site on Emacs Regexpressions might come in handy.
---
On the other hand, you could teach emacs how to interpret the compiler output.
Changing the variables `compilation-error-regexp-alist` and `compilation-error-regexp-alist-alist` could help.
> 1 votes
---
Tags: compile-mode
---
|
thread-55010
|
https://emacs.stackexchange.com/questions/55010
|
org-mode call python source within latex source block
|
2020-01-19T15:10:02.863
|
# Question
Title: org-mode call python source within latex source block
I have a piece of python code that outputs latex code. I'm trying to call the python source block from within a latex source block so it will format the output as latex when I export.
Any idea how to do this? I was hoping something similar to the below would work.
```
#+name: gradient_potential
#+BEGIN_SRC python :exports none :results output
from sympy import symbols, sqrt, diff, latex
x, y = symbols('x y')
U = x * y
print(latex(diff(U, y)))
#+END_SRC
#+begin_export latex
\begin{align}
#+CALL: gradient_potential() :results output
\end{align}
#+end_export
```
# Answer
> 3 votes
Use a Noweb reference `<<src block call>>` to inject the results of source blocks into other source blocks.
Example:
```
#+NAME: ltxInput
#+BEGIN_SRC emacs-lisp :exports none :results raw drawer
"\\sqrt{x^2+y^2}"
#+END_SRC
#+RESULTS: ltxInput
:results:
\sqrt{x^2+y^2}
:end:
#+NAME: ltxSrc
#+BEGIN_SRC latex :noweb yes :exports results
\begin{align*}
<<ltxInput()>>
\end{align*}
#+END_SRC
#+RESULTS: ltxSrc
#+begin_export latex
\begin{align*}
\sqrt{x^2+y^2}
\end{align*}
#+end_export
```
Tested with Emacs 26.3 and Org 9.2.6.
Note that your approach with the `:var` header argument of a `latex` source block did not work for me. I got an error `"Wrong use of \ in replacement string."` for the slash in `\sqrt{x^2+y^2}`.
# Answer
> 1 votes
I found a way to do this, I'll post for anyone who has the same issue in the future. The method I found is using both a python source block and a latex source block.
```
#+name: gradient_potential_py
#+BEGIN_SRC python :exports none :results output :cache yes
from sympy import symbols, diff, latex
x, y = symbols('x y')
U = x * y
print(latex(diff(U, y)), end='')
#+END_SRC
#+name: gradient_potential
#+begin_src latex :var expr1=gradient_potential_py :exports none
\begin{align}
expr1
\end{align}
#+end_src
#+CALL: gradient_potential()
```
I found that I need the `end=''` in the print statement when exporting to latex.
---
Tags: org-mode, org-export, org-babel
---
|
thread-30894
|
https://emacs.stackexchange.com/questions/30894
|
Show current org-mode outline position in modeline
|
2017-02-20T17:24:47.123
|
# Question
Title: Show current org-mode outline position in modeline
I'm using `org-mode` with really huge files (what I love in `org-mode` is having everything in a single file).
I would like to know where I am in the file by having a look at the modeline.
If I have the following :
```
* Foo
** Bar
*** Dump
[cursor being here]
** Egg
```
I'd like the modeline to show me something like `Foo > Bar > Dump`
Any ideas on how to achieve that?
# Answer
The `which-function` minor mode by default shows part of the org outline path in the mode line; you can turn it on using `M-x which-function-mode`. In general, `which-function` tries to show the current function in the mode line. It works in most languages.
If you want to see the entire path, you just have to add a new function to the variable `which-func-functions`. The first function in this list that returns non-nil is what `which-function` uses. Here is a function that uses `org-get-outline-path` to get the full path, if the current major mode is `org-mode`
```
(defun org-which-function ()
(interactive)
(when (eq major-mode 'org-mode)
(mapconcat 'identity (org-get-outline-path t)
" > ")
))
(add-to-list 'which-func-functions #'org-which-function)
```
You will quickly run out of room in your mode line, so try putting it in the header line instead. For example, this snippet will put the current buffer name and the outline path in the header:
```
(setq header-line-format
'(:eval
(list
(header-buffer-name)
" "
(header-function-name))))
```
\[EDIT\] Here, the fuctions `header-buffer-name` and `header-function-name` are the author's private functions, and defined in this answer.
> 9 votes
# Answer
The following is an interactive command that will give you your location within the current `org-mode` tree:
```
(defun org-where-am-i ()
"Returns a string of headers indicating where point is in the
current tree."
(interactive)
(let (headers)
(save-excursion
(while (condition-case nil
(progn
(push (nth 4 (org-heading-components)) headers)
(outline-up-heading 1))
(error nil))))
(message (mapconcat #'identity headers " > "))))
```
I'd actually suggest *not* putting it in the modeline, if for no other reason than the fact that it'll take over the whole thing. Instead, I'd suggest you bind the command to a key and call it whenever you want to know where you are.
(Note: if you *really* want to put it in the modeline, you'll want to remove the call to `message` in the last line.)
> 1 votes
# Answer
What Dan said is true. The Modeline is already very populated and showing the outline path there overfloods it. Alternatively you could also use the header line:
```
(defvar-local org+-header-line-format nil
"Cons with position of last synchronization of outline path
and the header line string.")
(defun org+-list-mapconcat (fun list separator)
"Replace each non-nil cdr SUBLIST of LIST with `(,(FUN SEPARATOR) . SUBLIST)."
(setq list (mapcar fun list))
(let ((sublist list))
(while (cdr sublist)
(setcdr sublist (cons separator (cdr sublist)))
(setq sublist (cddr sublist))))
list)
;; Test: (assert (equal (org+-list-mapconcat #'1+ '(1 2 3) 0) '(2 0 3 0 4)) "Outch.")
;; (assert (equal (org+-list-mapconcat #'identity '(1) 0) '(1)) "Outch.")
(defun org+-get-outline-path (&optional maxdepth)
"Return the outline path of the current entry.
MAXDEPTH defaults to 10."
(unless (numberp maxdepth)
(setq maxdepth 10))
(save-excursion
(let (ret)
(while (and
(numberp maxdepth)
(>= maxdepth 1)
(re-search-backward (format "^\\*\\{1,%d\\} " maxdepth) nil t))
(let* ((components (org-heading-components))
(level (car components))
(txt (nth 4 components)))
(setq maxdepth (1- level))
(push (cons txt (point)) ret)))
ret)))
(defun org+-header-line ()
"Outline path in header line of Org."
(let ((pos (car org+-header-line-format))
(pt (point)))
(when (or (null (number-or-marker-p pos))
(save-excursion
(goto-char (min pos pt))
(re-search-forward "^\\*+ " (max pos pt) t)))
(setq org+-header-line-format
(cons (point)
(append
(list " ")
(org+-list-mapconcat
(lambda (txt-pos)
(list :propertize
(car txt-pos)
'local-map
(let ((map (make-sparse-keymap))
(pos (set-marker (make-marker) (cdr txt-pos))))
(define-key map [header-line mouse-1]
(lambda ()
(interactive)
(switch-to-buffer (marker-buffer pos))
(goto-char pos)))
map))
)
(org+-get-outline-path)
" ‖ "))))))
(cdr org+-header-line-format))
(defvar-local org+-heder-old-header nil
"Old value of `header-line-format'.")
(define-minor-mode org+-header-outline-path-mode
"Show outline path in header line."
:ligher nil
(if org+-header-outline-path-mode
(setq org+-header-old-header header-line-format
header-line-format '((:eval (org+-header-line))))
(setq header-line-format org+-header-old-header)))
(add-hook 'org-mode-hook #'org+-header-outline-path-mode)
```
Note that this will probably interfere with `org-columns`. But it is a viable option, if you do not use `org-columns` extensively.
> 0 votes
---
Tags: org-mode, mode-line
---
|
thread-55623
|
https://emacs.stackexchange.com/questions/55623
|
How to give background color to hl-todo-keywords?
|
2020-02-19T08:04:22.177
|
# Question
Title: How to give background color to hl-todo-keywords?
I am using following setup in my `.emacs` file:
```
(setq hl-todo-keyword-faces
'(("TODO" . "#FF0000")
("FIXME" . "#FF0000")
("DEBUG" . "#A020F0")
("GOTCHA" . "#FF4500")
("STUB" . "#1E90FF")))
```
Here all those keywords shown as bold and as their defined color.
In addition to that, I want to provide yellow background highlight color to all. Is it possible?
# Answer
The doc string of `hl-todo-keyword-faces` says:
> Each entry has the form (KEYWORD . COLOR). KEYWORD is used as part of a regular expression. If (regexp-quote KEYWORD) is not equal to KEYWORD, then it is ignored by \`hl-todo-insert-keyword'. Instead of a color (a string), each COLOR may alternatively be a face.
So `COLOR` can also be a face. You can define your own faces with `defface`.
Example:
```
(defface hl-todo-TODO
'((t :background "#f0ffd0" :foreground "#ff0000" :inherit (hl-todo)))
"Face for highlighting the HOLD keyword.")
```
* The `hl-todo-TODO` is the face name which you can put into `hl-todo-keyword-faces` instead of the color string `"#FF0000"`.
* The third arg of `defface` is the face specification which is an alist that maps terminal types to attributes. Use `t` as terminal type if you do not care.
* Behind the `t` the property list with the face attributes starts. You can inherit from face `hl-todo` and set your own foreground and background color.
* The last arg of `defface` is the doc string for the face.
> 3 votes
---
Tags: highlighting
---
|
thread-26865
|
https://emacs.stackexchange.com/questions/26865
|
Magit - How to expand all and collapse all sections in magit-status
|
2016-09-06T00:17:56.640
|
# Question
Title: Magit - How to expand all and collapse all sections in magit-status
Pressing `TAB` on a single unstaged file shows or hides details pertaining to that file.
How do I show & hide (toggle) details of all unstaged files at once?
I did come across outline-hide-sublevels via `M-x`. But I would like to know a key combination to do this in a toggle fashion.
I also typed `?` to check the keybinding shortcuts for the magit-status area but could not find an answer.
# Answer
I think you want `M-TAB` `magit-section-cycle-diffs`
> Cycle the visibility of diff-related sections in the current buffer.
https://magit.vc/manual/magit.html#Section-Visibility-1
> 34 votes
# Answer
Another method (if you do not want to change key bindings for the `M-TAB` solution) is to position your cursor on the line with the section heading, e.g. "Unstaged changes", and press `2` to collapse all changes in that section, or `4` to expand them.
It also works for collapsing/expanding changes per subsection/file.
> 19 votes
# Answer
You can use `S-TAB` (that's `shift`) to invoke `magit-section-cycle-global` for a coarse-granularity full-expand and -collapse.
> 5 votes
# Answer
The following works as an replacement to `M-tab`.
```
(define-key magit-mode-map [(control >)] 'magit-section-cycle-diffs)
```
`M-tab` doesn't work on most MS Windows systems
> 0 votes
---
Tags: magit
---
|
thread-55631
|
https://emacs.stackexchange.com/questions/55631
|
How to set #+STARTUP: content globally in .emacs?
|
2020-02-19T13:21:59.007
|
# Question
Title: How to set #+STARTUP: content globally in .emacs?
I want to change the default behavior of org-mode to show all headings when opening a org file. Per file this is possible with `#+STARTUP: content`. Unfortunately I can't manage to set this globally in my .emacs.
I am aware of the corresponding manual entry but I can't get it to work. `(setq org-startup-folded "content")` has no effect.
# Answer
> 2 votes
I figured it out: It's
```
(setq org-startup-folded 'content)
```
Rather than the string `"content"`, it needs to be the *symbol* `'content`.
---
Tags: org-mode
---
|
thread-55622
|
https://emacs.stackexchange.com/questions/55622
|
Not understanding ring structure
|
2020-02-19T07:13:14.563
|
# Question
Title: Not understanding ring structure
I want to learn Elisp so I'm trying to solve perl6 weekly challenges. There is one on the week 48:
> Survivor
>
> There are 50 people standing in a circle in position 1 to 50. The person standing at position 1 has a sword. He kills the next person i.e. standing at position 2 and pass on the sword to the immediate next i.e. person standing at position 3. Now the person at position 3 does the same and it goes on until only one survives.
>
> Write a script to find out the survivor.
I want to implement it using rings and see how the sequence is descending, but it seems that when it has two elements it is not working properly, or probably I do not get the point:
```
ELISP> (setf r (ring-convert-sequence-to-ring (number-sequence 1 5)))
(0 5 .
[5 4 3 2 1])
ELISP> (princ-list (ring-remove r 1) r)
2(0 4 . [5 4 3 1 nil])
"
"
ELISP> (princ-list (ring-remove r 2) r)
4(0 3 . [5 3 1 nil nil])
"
"
ELISP> (princ-list (ring-remove r 3) r)
1(0 2 . [5 3 nil nil nil])
"
"
ELISP> (princ-list (ring-remove r 4) r)
3(0 1 . [5 nil nil nil nil])
"
"
```
Maybe at the end of each loop I need to change it but working in another way I get:
```
ELISP> (setf r (ring-convert-sequence-to-ring (number-sequence 5 1 -1)))
(0 5 .
[1 2 3 4 5])
ELISP> (princ-list (setf (car r) 1) (ring-remove r) (ring-resize r 4) r)
120(0 4 . [3 4 5 1])
"
"
ELISP> (princ-list (setf (car r) 1) (ring-remove r) (ring-resize r 3) r)
140(0 3 . [5 1 3])
"
"
ELISP> (princ-list (setf (car r) 1) (ring-remove r) (ring-resize r 2) r)
110(0 2 . [3 5])
"
"
ELISP> (princ-list (setf (car r) 1) (ring-remove r) (ring-resize r 1) r)
150(0 1 . [nil])
"
"
```
But I do not understand the last step.
So firstly I want to know how ring works, and are there circular linked lists in EmacsLisp?
Or maybe I need to focus on the recursive solution of the problem, and not work with circular linked lists.
# Answer
> I want to implement it using rings and see how the sequence is descending, but it seems that when it has two elements it is not working properly, or probably I do not get the point
It seems to be working as expected in your example. The key thing to note about rings is that they are modulo-indexed, i.e. if you have the ring `(3 5)` (from newest element to oldest) and try to remove the element at index `4`, then you will be left with the ring `(5)`, as the index `4` modulo the length of the ring `2` is `0`, which corresponds to the newest element, which in this case is `3`.
> But I do not understand the last step.
The last step should make more sense if you read the docstring of `ring-resize`:
```
ring-resize is a compiled Lisp function in `ring.el'.
(ring-resize RING SIZE)
Set the size of RING to SIZE.
If the new size is smaller, then the oldest items in the ring are
discarded.
```
Before calling `ring-resize`, you have the ring `(1 1 . [nil 3])` with size `2`, length `1`, and oldest element `3` at index `1`.
Resizing to `1` means getting rid of the oldest element `3`, leaving you with the ring `(nil)`.
The reason this is not a bug in the `ring.el` package is because you are manually changing the "head" (i.e. the index of the oldest element). The ring structure wouldn't have reached the state `(1 1 . [nil 3])` if you used its public API. As Tobias notes, the ring structure itself is an internal implementation detail and not to be relied on externally.
> are there circular linked lists in EmacsLisp
Yes, see `(elisp) Cons Cells`. For example:
```
(let ((l (list 1 2)))
(nth 2 l) ; => nil
(nconc l l) ; Loop back to the start
(nth 2 l)) ; => 1
```
> Or maybe I need to focus on the recursive solution of the problem, and not work with circular linked lists.
Actually, I think circular lists are probably the simplest and most efficient solution to this problem in Elisp.
Here's a sample circular solution:
```
(defun my-survivor-circular (first last)
"Solve the Survivor puzzle for numbers FIRST through LAST.
Return the single surviving number.
Implemented using a circular list."
(let ((circle (number-sequence first last)))
;; Make circle circular
(nconc circle circle)
;; Kill next person so long as they are not us
(while (not (eq circle (cdr circle)))
(setcdr circle (cddr circle))
;; Pass sword to next survivor
(pop circle))
;; Return single survivor
(or (car circle) first)))
(my-survivor-circular 1 0) ; => 1
(my-survivor-circular 1 1) ; => 1
(my-survivor-circular 1 2) ; => 1
(my-survivor-circular 1 3) ; => 3
(my-survivor-circular 1 4) ; => 1
(my-survivor-circular 1 5) ; => 3
(my-survivor-circular 1 50) ; => 37
```
Here's the same idea but without using circular lists:
```
(defun my-survivor-proper (first last)
"Solve the Survivor puzzle for numbers FIRST through LAST.
Return the single surviving number.
Implemented using a proper list."
(let* ((circle (number-sequence first last))
(sword circle))
;; As long as there is more than one survivor
(while (cdr circle)
;; Kill next person or one at beginning
(if (cdr sword)
(setcdr sword (cddr sword))
(pop circle))
;; Pass sword to next survivor or wrap around to beginning
(setq sword (or (cdr sword) circle)))
;; Return single survivor
(or (car circle) first)))
(my-survivor-proper 1 0) ; => 1
(my-survivor-proper 1 1) ; => 1
(my-survivor-proper 1 2) ; => 1
(my-survivor-proper 1 3) ; => 3
(my-survivor-proper 1 4) ; => 1
(my-survivor-proper 1 5) ; => 3
(my-survivor-proper 1 50) ; => 37
```
And finally here's a sample solution using rings:
```
(defun my-survivor-ring (first last)
"Solve the Survivor puzzle for numbers FIRST through LAST.
Return the single surviving number.
Implemented using a ring."
(let ((ring (ring-convert-sequence-to-ring (number-sequence first last)))
(sword first))
(while (> (ring-length ring) 1)
(let* ((kill (ring-next ring sword))
(next (ring-next ring kill)))
(ring-remove ring (ring-member ring kill))
(setq sword next)))
(if (ring-empty-p ring) first sword)))
(my-survivor-ring 1 0) ; => 1
(my-survivor-ring 1 1) ; => 1
(my-survivor-ring 1 2) ; => 1
(my-survivor-ring 1 3) ; => 3
(my-survivor-ring 1 4) ; => 1
(my-survivor-ring 1 5) ; => 3
(my-survivor-ring 1 50) ; => 37
```
As you can see, the ring does not lend itself as neatly or as efficiently to this problem as a circular list. I think this is because a ring's circularity is inherent in its index, rather than its data, and perhaps because Emacs' ring API could be enriched.
> 4 votes
# Answer
Don't look at the innards of the ring. That is an implementation detail. Look at the results of the interface functions.
You can see what's in the ring with `ring-elements`. The list indexes of that list are also the indexes of the elements in the ring.
```
(let ((r (ring-convert-sequence-to-ring (number-sequence 1 5))))
(ring-elements r))
```
(1 2 3 4 5)
Let us remove element 1 and look at the resulting list:
```
(let ((r (ring-convert-sequence-to-ring (number-sequence 1 5))))
(ring-remove r 1)
(ring-elements r))
```
(1 3 4 5)
The element 2 is removed.
If we reference the new element at index 1 we get 3:
```
(let ((r (ring-convert-sequence-to-ring (number-sequence 1 5))))
(ring-remove r 1)
(ring-ref r 1))
```
3
So the solution of the task at hand is:
```
;; (org-src-debug)
(let ((r (ring-convert-sequence-to-ring (number-sequence 1 50)))
l)
(setf i 0)
(while (> (setq l (ring-length r)) 1)
(ring-remove r (setq i (mod (1+ i) l))))
(ring-ref r 0))
```
37
`i` kills its current successor with index `(mod (1+ i) l))` where `l` is the current length of the ring. The successor of the killed takes the place of the killed (we let do that the ring).
> 3 votes
---
Tags: rings
---
|
thread-55636
|
https://emacs.stackexchange.com/questions/55636
|
Make forward-list search for specific symbol only
|
2020-02-19T16:51:32.363
|
# Question
Title: Make forward-list search for specific symbol only
Is there a way to make `forward-list` and `backward-list`search for specific symbols (such as `「」『』`) only?
I have code that make use of these functions to iterate through `「」『』` pairs in plain text. But `forward-list` would apply to `()《》〈〉` etc. as well, which makes the code very inefficient.
`(re-search-forward "「\\|『" nil t)` is not the optimal solution because I am dealing with balanced pairs of quotes, and only have to deal with the outer-most paretheses. For instance, `forward-list` would stop 2 times in the scenario below, while `re-search-forward` would take 4.
`forward-list`:
> 「『』『』」1「」2
`re-search-forward`:
> 「1『2』『3』」「4」
# Answer
You can define your own temporary syntax table. Just start with a newly created character table with default nil entries and modify only those syntax entries you need.
The following Elisp function demonstrates that. It creates a temporary syntax table with the syntax you want and sends you into recursive edit.
You can then interactively try commands like `forward-list` with the binding `C-M-n`.
Exit recursive edit with `C-M-c` when you are done.
```
(defun my-stops ()
"Test modified syntax table with `recursive-edit'."
(interactive)
(with-syntax-table (make-char-table 'syntax-table)
(modify-syntax-entry ?\「 "(」")
(modify-syntax-entry ?\」 ")「")
(modify-syntax-entry ?\『 "(』")
(modify-syntax-entry ?\』 ")『")
(let ((header-line-format "Test the modified syntax in recursive edit. Leave with M-C-c."))
(recursive-edit))))
```
If you want to avoid the creation of a syntax table at each function call just store it in a global variable and re-use it a la
```
(defvar my-syntax-table nil)
(defun my-stops ()
(with-syntax-table (or my-syntax-table
(setq my-syntax-table (let ((table (make-char-table 'syntax-table)))
(modify-syntax-entry ?\「 "(」" table)
...
table)))
...))
```
---
Independently of what I wrote above I would actually use a combination of `re-search-forward` and `forward-sexp` instead of modifying the syntax table for a task like that.
> 3 votes
---
Tags: search, list, motion
---
|
thread-55637
|
https://emacs.stackexchange.com/questions/55637
|
Convert old advise ad-set-arg to new advice
|
2020-02-19T16:55:32.130
|
# Question
Title: Convert old advise ad-set-arg to new advice
How would I convert the following old style advice to a new style advice?
```
(setq python--pdb-breakpoint-string "import pdb; pdb.set_trace()")
(defadvice compile (before ad-compile-smart activate)
"Advises `compile' so it sets the argument COMINT to t
if breakpoints are present in `python-mode' files"
(when (derived-mode-p major-mode 'python-mode)
(save-excursion
(save-match-data
(goto-char (point-min))
(if (re-search-forward (concat "^\\s-*" python--pdb-breakpoint-string "$")
(point-max) t)
;; set COMINT argument to `t'.
(ad-set-arg 1 t))))))
```
Snippet from: https://masteringemacs.org/article/compiling-running-scripts-emacs
---
From Porting old advice, the recommendations are `:around` or `:filter-args`.
Using `:filter-args`, I'm at a loss for what to return for the first argument of `compile`. The first argument is `command`. I have no clue what that is, or might be, and don't know how to find it during advising/let it pass through.
```
(advice-add 'compile :filter-args
(lambda ()
(when (derived-mode-p major-mode 'python-mode)
(save-excursion
(save-match-data
(goto-char (point-min))
(if (re-search-forward (concat "^\\s-*" python--pdb-breakpoint-string "$") (point-max) t)
;; new arglist:
;; (command t)
))))))
```
Using `:around`, I think I have the same issue, but it's hard to tell. I'm getting overwhelmed by the documentation. It seems like I would need to call `apply` if the `if` passes and call the original `compile` otherwise:
```
(advice-add 'compile :around
(lambda (oldcompile)
(when (derived-mode-p major-mode 'python-mode)
(save-excursion
(save-match-data
(goto-char (point-min))
(if (re-search-forward (concat "^\\s-*" my-python-break-string "$")
(point-max) t)
(apply oldcompile command t)
oldcompile))))))
```
# Answer
See the documentation for `add-function` or the corresponding page in the manual:
If you define an `:filter-args` advice your function `FUNCTION` advising `OLDFUN` is called as follows:
> `(lambda (&rest r) (apply OLDFUN (funcall FUNCTION r)))`
That means you get the arguments as list, may modify that list, and pass it as list of arguments to the old function.
```
(setq python--pdb-breakpoint-string "import pdb; pdb.set_trace()")
(defun my-compile-advice (args)
"Advises `compile' so it sets the argument COMINT to t
if breakpoints are present in `python-mode' files"
(when (derived-mode-p major-mode 'python-mode)
(save-excursion
(save-match-data
(goto-char (point-min))
(if (re-search-forward (concat "^\\s-*" python--pdb-breakpoint-string "$")
(point-max) t)
;; set COMINT argument to `t'.
(let ((command (car args)))
(setq args (list command t)))))))
args)
(advice-add 'compile :filter-args #'my-compile-advice)
```
I recommend always to define a function for advising OLDFUN. That gives you the possibility to jump to the definition of the advice from the help of OLDFUN. Furthermore, it simplifies debugging a lot.
> 1 votes
# Answer
You need to know how your function will be invoked, that is, what arguments it will take and what result must return, (info "(elisp) Advice combinators") or `C-h add-function` says:
> :filter-args `(lambda (&rest r) (apply OLDFUN (funcall FUNCTION r)))`
thus your function (that is `FUNCTION` in above) should take exactly one argument, which is always a list (suggested by `&rest`), and return another list (suggested by `apply`).
For example, we want to swap `A` and `B` in `foo`
```
(defun foo (a b) (list a b))
(define-advice foo (:filter-args (args) swap)
"Swap A and B."
(list (nth 1 args) (nth 0 args)))
(foo 1 2)
;; => (2 1)
```
`:around` is the most generic one, it can replace all others
> :around `(lambda (&rest r) (apply FUNCTION OLDFUN r))`
so your function should accept one or more argument, the first is `OLDFUN`, thus both of the following work
```
(define-advice foo (:around (old-fun a b) swap-2)
(funcall old-fun b a))
(define-advice foo (:around (old-fun &rest r) swap-3)
(apply old-fun (nreverse r)))
```
> 1 votes
# Answer
I guess the closest replacement for
```
(defadvice FOO (before ...)
... (ad-set-arg N V) ...)
```
is
```
(advice-add FOO :around
(lambda (orig-fun &rest args)
... (setf (nth N args) V) ...
(apply orig-fun args)))
```
But as Tobias points out, this can fail if there is no Nth argument. Also using `setf/setq` makes you lose valuable karma points. So you're better off writing code that's not as similar-looking as the original. E.g.
```
(advice-add 'compile :around
(lambda (orig-fun command &optional comint)
(funcall orig-fun command
;; Set COMINT argument to t if there's a Python breakpoint.
(or (when (derived-mode-p major-mode 'python-mode)
(save-excursion
(save-match-data
(goto-char (point-min))
(re-search-forward
(concat "^\\s-*" python--pdb-breakpoint-string "$")
nil t))))
comint))))
```
> 1 votes
---
Tags: advice, nadvice
---
|
thread-55570
|
https://emacs.stackexchange.com/questions/55570
|
YASnippet: Avoid electric pairs at expansion time
|
2020-02-16T17:00:04.347
|
# Question
Title: YASnippet: Avoid electric pairs at expansion time
I am used to bind my YASnippet trigger keys to sequences that start with `<` (e.g. when I type `<hn` in org-mode, it expands to a custom header for my notes).
The problem is that in some modes, the `<` character is part of electric pairs (I have `electric-pair-mode` enabled), which automatically writes a closing `>` when I type it. As a consequence, my snippet expansions are followed by an unwanted `>`.
The `<` character is not in `electric-pair-pairs` nor in `electric-pair-text-pairs`, so it does not seem easy to just avoid electric pairing for this character (which, besides, I do not want for certain modes).
How should I go about it? Is there a way to make YASnippet delete the `>` character at expansion, before the actual expansion is written?
# Answer
You can delete chars from the buffer during expansion, but modifying the buffer during expansion is dicouraged.
Deleting chars is pretty easy, because yasnippet allows to eval elisp code during expansion. You have to put this code into `back-quotes` Read more about it here.
Your snippet would then look like this example (you need to refine this crude example, to match your needs, of course):
```
# -*- mode: snippet -*-
# name: <hn
# key: <hn
# --
${0:* blubb}`(when (eq major-mode 'org-mode) (delete-char 2))`
```
*Note:* This snippet, when expanded in an `org-mode` buffer, triggers at `<hn| >` and replaces it with `* blubb`. (`|` is cursor position)
> 1 votes
# Answer
You can disable pairing of `<..>` as follows:
```
(add-function :before-until electric-pair-inhibit-predicate
(lambda (c) (eq c ?<)))
```
> 3 votes
# Answer
I ended up using closing brace for snippets, e.g. `}` expands to `{{ | }}` for me. Try `>hn` instead of `<hn`.
> 0 votes
---
Tags: yasnippet, electric-pair-mode
---
|
thread-55618
|
https://emacs.stackexchange.com/questions/55618
|
Rules for dealing with email in mu4e
|
2020-02-18T20:06:46.970
|
# Question
Title: Rules for dealing with email in mu4e
The Mail application in macOS allows creation of rules, such as `Sender X and keyword Y in subject -> mark as read and move to archive.` I am looking for something similar in mu4e.
Smart refiling has a similar feature:
> you can select some messages in the headers view, then press `r`, and have them all marked for refiling to their particular folders.
What I'm looking for is that result without having to see the message or press `r` to refile it.
Does it exist?
# Answer
> 1 votes
I don't think so. In any case, the function that does the refiling is called `mu4e~proc-move`, so all you need is the message's `docid` and target folder. But how do you know which messages are new during the indexing process? One way around this is to find messages flagged unread using the `mu find` command (see below).
```
(defvar mu4e-find-new-messages-command
"mu find maildir:/YOUR_INBOX_FOLDER flag:unread --format=sexp 2>/dev/null")
(defun mu4e-refile-messages ()
(let* ((cmd mu4e-find-new-messages-command)
(res (concat "(list" (shell-command-to-string cmd) ")"))
(msgs (car (read-from-string res))))
(unless (equal '(list) msgs)
(dolist (msg msgs)
(when-let ((docid (mu4e-message-field msg :docid))
(maildir (funcall mu4e-refile-folder msg)))
(mu4e~proc-move docid maildir))))))
(add-to-list 'mu4e-index-updated-hook 'mu4e-refile-messages)
```
---
Tags: mu4e
---
|
thread-28161
|
https://emacs.stackexchange.com/questions/28161
|
yasnippets - finding and modifying some snippets
|
2016-10-27T10:43:20.863
|
# Question
Title: yasnippets - finding and modifying some snippets
I'm struggling a bit with yasnippet. My question must be very basic but I would like to modify some snippets but I can't locate them. I have for example a snippet `style` for `html-mode` but it does not appear where it should be that is either under :
```
~/.emacs.d/elpa/yasnippet
```
or
```
~/.emacs.d/snippets
```
My config is the following:
```
(add-to-list 'load-path
"~/.emacs.d/elpa/yasnippet-20160801.1142")
(require 'yasnippet)
(yas-global-mode 1)
(add-to-list 'yas-snippet-dirs "~/.emacs.d/snippets")
```
Any would be appreciated!
# Answer
Considering your configuration, using *elpa*, they are located in `~/.emacs.d/elpa/yasnippet-20160801.1142/snippets`.
Your custom snippets should be at `~/.emacs.d/snippets` so they don't get overwritten in each update. Also check the value of the variable `yas-snippets-dirs` with `Ctr-h v yas-snippets-dir`.
> 7 votes
# Answer
In your buffer, `M-x yas-visit-snippet-file`, then type the name of the snippet you want to edit, or choose from a prompted list. Then it will open a buffer for you to edit. From the buffer you can `M-: buffer-file-name` to see the path of the file containing the snippet.
> 5 votes
# Answer
If you want to edit a snippet from the mode you are in just press the standard commands :
`C-c & C-v` to view an existing snippet (you should know what name it has)
or
`C-c & C-n` to create a new snippet for the mode you're in.
In this way you don't have to care about where the snippets are located, YASnippet should do that automatically.
You can also open existing/new snippets by clicking on the menu bar YASnippet (if you're using the GUI).
I hope this could help you.
> 2 votes
# Answer
Try `(setq yas-snippet-dirs '("~/.emacs.d/snippets"))`
When you miss a snippet, that you've already created, use `yas-reload-all`.
And you don't need the first line.
> 0 votes
---
Tags: yasnippet
---
|
thread-55627
|
https://emacs.stackexchange.com/questions/55627
|
Regular expression to ignore a domain in address completion
|
2020-02-19T09:11:29.767
|
# Question
Title: Regular expression to ignore a domain in address completion
I read the manual on address autocompletion:
> `mu4e-compose-complete-ignore-address-regexp` — a regular expression to filter out other ‘junk’ e-mail addresses; defaults to `"no-?reply"`.
I am looking for a regular expression that matches that `no-?reply` username, a username and a domain, and a domain.
My first try was:
```
(setq mu4e-compose-complete-ignore-address-regexp
(concat "\\(?:no-?reply"
"\\|.*first\\.last@domain\\.com"
"\\|.*@other-domain\\.com"
"\\)"))
```
The middle match works and I am not prompted for that email address. The last match fails and I still have hundreds of completions for that domain name.
What is a regular expression that ignores those three types of addresses?
# Answer
See here for explanations, but (forgetting about the tiresome escaping) the regex `(?:...)` is a `shy group`, i.e. a group that cannot be referred to through the `\N` mechanism. What you want is a straight alternation: match this *OR* that *OR* the other. The question mark in `no-?reply` has a different meaning: it matches zero or one of the previous char (or class or group), so `no-?reply` will match either `noreply` or `no-reply`. Putting it all together you end up with
```
no-?reply|first\.last@domain\.com|.*@other-domain\.com
```
and adding back the escapes:
```
(setq mu4e-compose-complete-ignore-address-regexp
(concat "\\(no-?reply"
"\\|first\\.last@domain\\.com"
"\\|.*@other-domain\\.com"
"\\)"))
```
should more-or-less work.
Caveats: It is not quite clear whether you need to group everything (i.e. whether the enclosing parens are necessary); it's also not clear that `.*` is correct for matching the user name in the `other-domain.com` case: it will match spaces, as well as alphanumerics and punctuation, so I don't think it conforms to email user-name syntax, but I'm not sure about the standard: you might want a character class like `[a-zA-Z0-9.-]` instead of the "anything goes" period, but take this with the appropriate grain of salt. Also, the `*` will allow matching the empty string which you probably want to avoid: use a `+` instead. I think I would prefer to write it like this:
```
(setq mu4e-compose-complete-ignore-address-regexp
(concat "\\(no-?reply"
"\\|first\\.last@domain\\.com"
"\\|[a-zA-z0-9.-]+@other-domain\\.com"
"\\)"))
```
Note that the period *inside* the character class `[a-zA-z0-9.-]` is a *literal* period and the `-` *has* to be at either the beginning or (as here) at the end, or else it is interpreted as a range (like `a-z`).
As mentioned in the comments, `re-builder` is an excellent way to interactively build and test a regex: you create a buffer, type a bunch of things that you want to match and a bunch of things that you don't want to match, then invoke `re-builder` and enter the proposed regex: it'll interactively show you what that regex matches and what it does not. It helps to have a basic idea of the regex you want, but you can take care of minor details this way.
> 2 votes
---
Tags: regular-expressions, mu4e
---
|
thread-36284
|
https://emacs.stackexchange.com/questions/36284
|
How to open eww in readable mode?
|
2017-10-19T10:45:37.210
|
# Question
Title: How to open eww in readable mode?
I have added in my init something like:
```
(defun today-CA ()
(interactive)
(eww "https://www.google.com"))
```
This opens `eww` through the `today-CA` function. I want to open it in readabe form, i.e. as if `eww-readable` had been invoked in the `eww` buffer. How to do that? This doesn't work:
```
(defun today-CA ()
(interactive)
(eww "https://www.google.com")
(eww-readable))
```
# Answer
> This doesn't work
The reason calling `eww-readable` right after `eww` does not work is because `eww` is asynchronous; when `eww-readable` is called the `eww` buffer is not yet rendered, so there are no "unreadable" parts to omit.
> How to do that?
There may be a more elegant way, but if you have lexical binding (see the last section) enabled in your init file, you can write something like the following:
```
(defun today-ca ()
"Open Google homepage in `eww' with `eww-readable' enabled."
(interactive)
(letrec ((nonce (lambda ()
(unwind-protect
(eww-readable)
(remove-hook 'eww-after-render-hook nonce)))))
(add-hook 'eww-after-render-hook nonce))
(eww "https://google.com"))
```
The basic idea is adding the function `eww-readable` to `eww-after-render-hook`, so that it is run in the finalised buffer. The only issue lies in cleaning up the hook so that `eww-readable` does not apply all the time.
We can't call `remove-hook` right after `eww` because `eww-after-render-hook` will not have been run by that point. So the function we add to `eww-after-render-hook` must remove itself. With `lexical-binding` we can just create a closure as per my previous example. Alternatively, you could write an additional global helper function:
```
(defun my-eww-readable-nonce ()
"Once-off call to `eww-readable' after EWW is done rendering."
(unwind-protect
(eww-readable)
(remove-hook 'eww-after-render-hook #'my-eww-readable-nonce)))
(defun today-ca ()
"Open Google homepage in `eww' with `eww-readable' enabled."
(interactive)
(add-hook 'eww-after-render-hook #'my-eww-readable-nonce)
(eww "https://google.com"))
```
You could remove the call to `unwind-protect`, but it ensures the hook is cleaned up even if something in `eww-readable` fails.
> 6 votes
# Answer
You can also load the content manually with url-retrieve and render it in eww yourself, and then run eww-readable, like this
```
(defun t/eww-readable-after-render (status url buffer)
(eww-render status url nil buffer)
(switch-to-buffer buffer)
(eww-readable))
(defun t/eww-readable (url)
(interactive "sEnter URL: ")
(let ((buffer (get-buffer-create "*eww*")))
(with-current-buffer buffer
(autoload 'eww-setup-buffer "eww")
(eww-setup-buffer)
(url-retrieve url 't/eww-readable-after-render (list url buffer)))))
```
> 0 votes
# Answer
Using Basil's answer, here is a solution for using eww to browse dash API docs - effectively making dash API docs open in eww buffers that are then collapsed to "readable" form. eww-readable-url can also prompt for a URL to open in eww-readable form if you pass nil and can be called interactively from anywhere to open a eww-readable browser.
```
(use-package
eww
:custom
(browse-url-browser-function 'eww-browse-url)
(dash-docs-browser-func 'eww-readable-url)
:config
(use-package helm-eww)
(defun make-eww-readable()
;; make current eww buffer eww-readable and then remove the hook that called this so normal buffers are not eww-readable.
(unwind-protect
(eww-readable)
(remove-hook 'eww-after-render-hook #'make-eww-readable)))
(defun eww-readable-url (url)
;; when the eww buffer has rendered call a hook function that implements eww-readable and then removes that hook.
;; primarily for 'dash-docs-browser-func
(interactive "sURL:")
(add-hook 'eww-after-render-hook #'make-eww-readable)
(eww url))
:bind
("C-c o" . 'browse-url)
("C-c O" . 'eww-readable-url)
(:map eww-mode-map
("O" . www-open-current-page-external)
("o" . www-open-link-external)))
```
> 0 votes
---
Tags: eww
---
|
thread-55544
|
https://emacs.stackexchange.com/questions/55544
|
How to correctly configure Flow backend for LSP mode?
|
2020-02-15T12:25:53.973
|
# Question
Title: How to correctly configure Flow backend for LSP mode?
I'm using `spacemacs` @develop (branch). I can't use `lsp` and `lsp-ui`. In vscode everything works (using flow lsp mode). With `company-flow` I can also make it working.
When opening a `.js` file with `// @flow` comment the lsp mode is activating automatically and tries to run the flow server and crashes:
```
Server flow-ls:7818 status:starting exited with status exit. Do you want to restart it? (y or n) y
```
Each time I'm trying to restart I see the same thing. So the type inspection and type checks doesn't work. Syntax is highlighted but I think it doesn't work (when I set `js2-mode-show-parse-errors nil` variable in the layers variable I see different view (eg the `import type` is not highlighted in red).
I'm running the latest version of flow, and have `flow-bin` installed (same version) in the package (`node_modules`) and globally. `flow` binary is in the PATH.
# Answer
1. Check the corresponding stderr log
2. Make sure the language server runs in the terminal
> 0 votes
# Answer
1. Install `flow-bin` (globally or as a dependency in your `package.json`).
2. Make sure that the LSP project root is the same as your JavaScript project and you have the `.flowconfig` file there. (that was my initial error)
3. Install `flow-js2-mode` package to your Emacs.
4. Enable `flow-js2-mode` in javascript files - this is to enable Flow syntax.
```
(add-hook 'js2-mode-hook #'flow-js2-mode))
```
5. All JavaScript files in the flow mode must have `// @flow` comment at the beginning of the file.
> 0 votes
---
Tags: javascript, lsp-mode, lsp-ui
---
|
thread-55554
|
https://emacs.stackexchange.com/questions/55554
|
Equivalent of helm-ag-edit with ivy
|
2020-02-15T20:16:55.910
|
# Question
Title: Equivalent of helm-ag-edit with ivy
I've been trying to switch to Ivy from Helm for the past little while. One feature I miss (and because of this I keep helm installed) is the ability to run `helm-ag`, and then to hit `C-c C-e` so I can edit the lines in the file that `helm-ag` matched.
Is there any equivalent functionality with Ivy/Swiper/Projectile/etc.?
# Answer
> 4 votes
Thanks to this blogpost, I found a solution. The real tool that I was looking for was *wgrep* which does the multi-editing heavy lifting that I was missing. Here are the steps for using the Silver Searcher backend:
* Invoke `counsel-ag`
* After you've found the search results, run `C-c C-o` (`ivy-occur`)
* Toggle the edit flag of the buffer to enter `wgrep` mode: hit `C-x C-q`
* Once done with the edits, hit `C-c C-c` to commit your changes
This also works with other tools like ripgrep; use the associated `counsel-*` command. (In the case of ripgrep, use `counsel-rg`.)
---
Tags: helm, projectile, ivy
---
|
thread-55666
|
https://emacs.stackexchange.com/questions/55666
|
Nesting conditionals, consolidating functionality in elisp
|
2020-02-21T04:14:04.797
|
# Question
Title: Nesting conditionals, consolidating functionality in elisp
Working in an org-mode file, I have this table
```
#+tblname: site-charac-matrix
| | glaze | orn | color | thin |
|---+-------+-----+-------+------|
| A | 0 | 1 | 0 | 0 |
| B | 1 | 0 | 0 | 0 |
| C | 1 | 0 | 1 | 0 |
| D | 1 | 1 | 1 | 1 |
| E | 0 | 1 | 1 | 1 |
```
which represents archaeological dig sites (one per row) for pottery, where four characteristics of the pottery are noted, 1 or 0 for yes or no for that characteristic of the pottery. Here is the "internal" list for the table
```
#+begin_src emacs-lisp :var site-matrix=site-charac-matrix :results raw
site-matrix
#+end_src
#+RESULTS:
((A 0 1 0 0) (B 1 0 0 0) (C 1 0 1 0) (D 1 1 1 1) (E 0 1 1 1))
```
I created this function to input a site and a characteristic argument and get back a yes or no statement
```
#+begin_src emacs-lisp :var site-matrix=site-charac-matrix
(defun site-charac-4 (site charac)
(cond ((= site 1) (format "At site %d the pottery %s have the %s characteristic."
site (if (= 1 (nth (charac-to-index charac) (nth 0 site-matrix))) "does" "does not") charac))
((= site 2) (format "At site %d the pottery %s have the %s characteristic."
site (if (= 1 (nth (charac-to-index charac) (nth 1 site-matrix))) "does" "does not") charac))
((= site 3) (format "At site %d the pottery %s have the %s characteristic."
site (if (= 1 (nth (charac-to-index charac) (nth 2 site-matrix))) "does" "does not") charac))
((= site 4) (format "At site %d the pottery %s have the %s characteristic."
site (if (= 1 (nth (charac-to-index charac) (nth 3 site-matrix))) "does" "does not") charac))
((= site 5) (format "At site %d the pottery %s have the %s characteristic."
site (if (= 1 (nth (charac-to-index charac) (nth 4 site-matrix))) "does" "does not") charac))
(t nil)))
#+end_src
```
As you see, I have a `cond` to sort for the incoming site number, but then I need another conditional, an `if` embedded in each `cond` to get the yes or no of the characteristic from the site's row list. In addition, to translate the characteristics, I have this function
```
#+begin_src emacs-lisp
(defun charac-to-index (charac)
(pcase charac
('glaze 1)
('orn 2)
('color 3)
('thin 4)))
#+end_src
```
which gives `nth` an index for accessing the correct place in the site row lists. This all works
```
#+begin_src emacs-lisp :var site-matrix=site-charac-matrix
(site-charac-4 5 'color)
#+end_src
#+RESULTS:
At site 5 the pottery does have the color characteristic.
```
My Lisp beginner's question is, could some of this be consolidated, e.g., the `charac-to-index`into the main function? Also, how do you have nested conditionals? I can't help but think my use of `if` embedded in the `format` of each `cond` case is kludgy. Any insights appreciated.
# Answer
> 2 votes
I think indexing org tables by column and row names is such a general task that it deserves a general function `org+-table-get`.
You could put the following code into your initialization file.
```
(defsubst org+-table-get-row (table row-id &optional start noerror)
"Get Org TABLE row by ROW-ID.
Search for ROW-ID from START.
START is zero-based. It defaults to 1.
That way the header row is skipped.
Don't panic in the case of out-of-range access if NOERROR is nil."
(unless (numberp start)
(setq start 1))
(unless (or
noerror
(>= start 0)
(< start (length table)))
(user-error "Start row index %s out of range [0,%s)" start (length table)))
(when (< start 0)
(setq start 0))
(when (symbolp row-id)
(setq row-id (symbol-name row-id)))
(let ((ret (assoc row-id (nthcdr start table))))
(unless (or noerror ret)
(user-error "Row %s not found" row-id))
ret))
(defun org+-table-get (table row-id col-id &optional start-row start-col noerror value)
"Get Org TABLE element content by ROW-ID and COL-ID.
Search rows from START-ROW and cols from START-COL.
START-ROW and START-COL are zero-based and default to 1.
That way the header row and the column with the row names are skipped.
Don't panic in the case of out-of-range access if NOERROR is nil.
If VALUE is non-nil then assign VALUE to the table cell."
(when (symbolp col-id)
(setq col-id (symbol-name col-id)))
(unless (numberp start-col)
(setq start-col 1))
(let* ((col-nr (+ start-col (cl-position col-id (nthcdr start-col (car table)) :test #'equal)))
(row (if col-nr
(org+-table-get-row table row-id start-row noerror)
(unless noerror
(user-error "Column %s not found" col-id)))))
(and row
(if value
(setf (nth col-nr row) value)
(nth col-nr row)))))
(defun org+-table-setter (&rest args)
""
(let ((val (car (last args)))
(n (length args)))
(setq args (butlast args))
(when (< n 7)
(setq args (append args
(make-list (- 7 n) nil))))
(unless val
(setq val ""))
(setq args (nconc args (list val)))
(apply #'org+-table-get args)))
(gv-define-simple-setter
org+-table-get
org+-table-setter)
(defun org+-table-add-header-hline (table)
"Add hline below header row by modifying TABLE.
Return the modified TABLE."
(setcdr table (cons 'hline (cdr table)))
table)
```
With those definitions the code in the following Org file would work:
```
#+tblname: site-charac-matrix
| | glaze | orn | color | thin |
|---+-------+-----+-------+------|
| A | 0 | 1 | 0 | 0 |
| B | 1 | 0 | 0 | 0 |
| C | 1 | 0 | 1 | 0 |
| D | 1 | 1 | 1 | 1 |
| E | 0 | 1 | 1 | 1 |
#+BEGIN_SRC emacs-lisp :var matrix=site-charac-matrix site="E" char='color :colnames no
(format "At site %s the pottery does%s have the %s characteristic.\n"
site
(if (eq (org+-table-get matrix site char) 1)
""
" not")
char)
#+END_SRC
#+RESULTS:
: At site D the pottery does have the color characteristic.
Also setting table cells is possible:
#+BEGIN_SRC emacs-lisp :var matrix=site-charac-matrix site="E" char='color val=2 :colnames no
(setf (org+-table-get matrix site char) val)
(org+-table-add-header-hline matrix)
#+END_SRC
#+RESULTS:
| | glaze | orn | color | thin |
|---+-------+-----+-------+------|
| A | 0 | 1 | 0 | 0 |
| B | 1 | 0 | 0 | 0 |
| C | 1 | 0 | 1 | 0 |
| D | 1 | 1 | 1 | 1 |
| E | 0 | 1 | 2 | 1 |
```
# Answer
> 1 votes
There are lots of different ways to write code that's similar but a bit different. So the question might be closed as being a bit opinion-based.
Anyway, here's one rewrite, which factors some of the stuff. I don't claim it is in any particular way better than what you wrote.
```
(setq site-matrix '((A 0 1 0 0) (B 1 0 0 0) (C 1 0 1 0) (D 1 1 1 1) (E 0 1 1 1)))
(defun site-charac-4 (site charac)
(let* ((ii (1- site))
(jj (nth (cl-case charac
(glaze 1)
(orn 2)
(color 3)
(thin 4))
(nth ii site-matrix)))
(dn (if (= 1 jj) "" " not")))
(and (member site '(1 2 3 4 5))
(format "At site %d the pottery does%s have the %s characteristic." site dn charac))))
;; (site-charac-4 5 'color)
;; => "At site 5 the pottery does have the color characteristic."
```
# Answer
> 1 votes
This is an X-Y-problem.
Just avoid the multi-branched conditionals if you actually do not need them. I show you one way to do that with the code below.
The most important details of the code:
* If you use the `:colnames no` header argument you get the characteristics in the first line of the matrix.
* You can get the column number of the given characteristic with the column names with `cl-position`.
* You can select the site with its site name via `assoc-string`.
* You can process multiple characteristics at once for one site with `cl-loop`.
```
#+tblname: site-charac-matrix
| | glaze | orn | color | thin |
|---+-------+-----+-------+------|
| A | 0 | 1 | 0 | 0 |
| B | 1 | 0 | 0 | 0 |
| C | 1 | 0 | 1 | 0 |
| D | 1 | 1 | 1 | 1 |
| E | 0 | 1 | 1 | 1 |
#+BEGIN_SRC emacs-lisp :results none
(defun site-char (matrix site &rest characteristics)
"Report whether SITE has CHARACTERISTICS in MATRIX.
MATRIX is a cons (COLSROW . DATA).
COLSROW is a a cons (\"\" . PROPS) where
the list PROPS contains the property names.
DATA contains the data rows.
Each data row is a cons (NAME . FLAGS).
NAME contains the name of the site as string or symbol.
FLAGS is a list of flags with the same length as PROPS.
SITE is one of the site names in MATRIX.
CHARACTERISTICS is a list with names from PROPS.
SITE's flags are those associated with SITE in DATA.
SITE can also be the site's row index."
(when (numberp site) ;; unify treatment of sites
(unless (and (> site 0)
(<= site (length (car matrix))))
(user-error "Index out of range"))
(setq site (car (nth site matrix))))
(let (col row)
(setq row (assoc-string site matrix))
(unless row
(user-error "Site %s unknown." site))
(cl-loop for char in characteristics
if (setq col (cl-position char (car matrix) :test #'string-equal))
collect (format "At site %s the pottery does%s have the %s characteristic.\n"
site
(if (eq (nth col row) 1)
""
" not")
char)
else
do (user-error "Characteristic %s unknown" char))))
#+END_SRC
#+BEGIN_SRC emacs-lisp :var matrix=site-charac-matrix site="E" char='color :colnames no
(site-char matrix site char)
#+END_SRC
#+RESULTS:
| At site E the pottery does have the color characteristic. |
```
# Answer
> 1 votes
I might be missing the point of the question, but I think the main reason this looks messy is that the cond statement has 5 branches. A nested conditional on its own doesn't look that bad to me, so noticing that the only thing changing in the main cond branch is the argument to `nth`, I would rewrite the function as
```
(defun site-charac-4 (site charac)
(if (and (< 0 site) (> 6 site))
(format "At site %d the pottery %s have the %s characteristic."
site
(if (= 1 (nth (charac-to-index charac)
(nth (- site 1) site-matrix)))
"does"
"does not")
charac)))
```
---
Tags: org-table, conditionals
---
|
thread-55675
|
https://emacs.stackexchange.com/questions/55675
|
Escape Swiper even when match is required
|
2020-02-21T12:55:41.720
|
# Question
Title: Escape Swiper even when match is required
Swiper automatically moves to the next location that matches your current input. You can press RET to return to the main buffer when the search is successful.
When you type in a word that does not exist, Swiper remains at the last location where a match was found. Then, when you press RET, Swiper says "match required" and does not return to the buffer. It seems that the only options are to cancel (C-g, which returns to the position before calling Swiper) or to modify the input in the minibuffer.
Is it possible to by-pass the "matching requirement" and to return to the buffer at the location selected by Swiper, even when there is no more matching? Swiper behavior is very annoying and slow (because of the cancelling of the search or the changing of the input search), when you just mistyped or went too restrictive in the search.
# Answer
You can try `(setq swiper-stay-on-quit t)`.
When you hit C-g you'll be redirected to the location selected by swiper.
> 1 votes
---
Tags: completion, swiper
---
|
thread-55677
|
https://emacs.stackexchange.com/questions/55677
|
Customizing f6-key for fast "M-x imenu" + "Pr" + Enter
|
2020-02-21T13:48:25.507
|
# Question
Title: Customizing f6-key for fast "M-x imenu" + "Pr" + Enter
I wish to customize my `f6`key so it corresponds to a fast way of doing `M-x imenu`, then `Pr RET`. I've added the following to my `~/.emacs`:
`(global-set-key [f6] 'imenu)`
Then I've tried to add different stuff after `'imenu`, but all has failed and I've tried to google Emacs forums and google, but didn't find an obvious solution.
When `M-x imenu` is started it gives the user 4 possibilities:
2: *Rescan*
3: Procedures
4: Types
5: Modules
I always want to go into `Procedures` so it's enough to type `Pr`
followed by `RET`. And that explains the full key-sequence: `M-x imenu`, then `Pr RET`.
How can I proceed from the `(global-set-key [f6] 'imenu)` step and make the `F6` key work as described above...
**UPDATE**: Thanks a lot so far (also for "pretty"-fying the question), however something new happened: Based on the answer from RichieHH I tried adding the following to my ~/.emacs file (although on a different system/computer, please bear over with that):
```
(fset 'lastMacro
(lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item (quote ([120 31 escape 120 105 109 101 110 117] 0 "%d")) arg)))
(global-set-key [f5] 'lastMacro)
(fset 'yep
(lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item (quote ([escape 120 105 109 101 110 117 return 109 97 105 110 return] 0 "%d")) arg)))
(global-set-key [f6] 'yep)
```
Thing thing is that now the F5-key works - but not the F6-key. If you want to use the same "test file" as I'm using, grab the example at https://raw.githubusercontent.com/orlp/pdqsort/master/bench/bench.cpp and then `M-x imenu` should allow to quickly jump to different sections in that file. The problem seems to be: I'm running the X11 version of emacs (didn't try terminal-only) and if I type `M-x imenu` a "text-menu" pops up. If I instead use the F5-key, a GUI/X11-menu pops up, at the mouse cursor location... And that's probably why the F6-key doesn't work... I appreciate if anyone could please explain that behaviour and if I'm doing something wrong (reading the answer incorrect)?
# Answer
Look up emacs keyboard macros
You will record a sequence, save it resulting in a function, then bind that function to your f6 key.
> 1 votes
---
Tags: key-bindings, keyboard-macros, imenu
---
|
thread-55275
|
https://emacs.stackexchange.com/questions/55275
|
How to Redefine Meta Key to Use Esc Key Only and Allow Using Alt Key for Another Purpose
|
2020-02-03T14:40:25.727
|
# Question
Title: How to Redefine Meta Key to Use Esc Key Only and Allow Using Alt Key for Another Purpose
I am using ubuntu 18.04. The Esc-v scrolls up by a page as expected (classical Emacs command with Esc being the meta key). But I want to use Alt-v as a "paste command". In other words: can I decouple the Alt key from Esc key so that Esc remains as the meta key but the Alt key is used for other stuff?
# Answer
> 1 votes
Emacs wants to make the `ESC` key equivalent to the *Meta* modifier. This actually is fine with your goal, which is to fre the *Alt* modifer. All you need to do is to stop Emacs's "remapping" of the *Alt* modifier, which it does when it sees that there's no Meta modifier. Details will vary depending on your system, but for me:
```
xmodmap -e 'remove mod1 = Meta_L'
xmodmap -e 'add mod3 = Meta_L'
```
makes convinces Emacs that I have a *Meta* modifier, and from then on, Emacw will not treat my `Alt` key as the *Meta* modifier but as the *Alt* modifier, so `Alt-x` turns into `A-x` rather than `M-x`.
Of course, you can also arrange to have both *Alt* and *Meta* modifier keys (e.g. by remapping the left and the right `Alt` keys differently, e.g. one to `Alt_L` and the other to `Meta_R`).
# Answer
> -1 votes
Both the alt key and the esc key are setting the "Meta" modifier on the key.
Differentiating them without v significant collateral damage by breaking other meta binding is going to be difficult.
The easiest change to achieve what you desire might be to rebind something else to the `scroll-down-command` (which is what `M-v` is bound to by default).
A good option might be to define `C-c v` to `scroll-down-command`
From the manual:
> Sequences consisting of `C-c` and a letter (either upper or lower case) are reserved for users; they are the only sequences reserved for users, so do not block them.
---
Tags: key-bindings
---
|
thread-55684
|
https://emacs.stackexchange.com/questions/55684
|
Default argument when nil is provided
|
2020-02-21T20:11:16.470
|
# Question
Title: Default argument when nil is provided
I'm writing a function which wraps `org-export-as` for use in html conversion of a file. In this function, I define the options for `org-export-with-toc`, `org-export-with-section-numbers`, and `org-html-htmlize-output-type` based on the optional arguments provided to the user. If the user fails to provide an argument, I supply a default.
```
(defun my-export (file &optional toc section-num output-type backend)
"Export FILE to html string using `org-export-as'.
This function wraps `org-export-as'. See that function for greater argument
details.
TOC and SECTION-NUM generate table of contents and section
numbers, respectively. Defaults for each are nil.
OUTPUT-TYPE is 'css, 'inline-css, or nil as defined by
`org-html-htmlize-output-type'. Default is 'css.
BACKEND is the export backend. Default is 'html."
(let* ((org-export-with-toc toc)
(org-export-with-section-numbers section-num)
(backend (or backend 'html))
;; Want 'css to be the default value here
(org-html-htmlize-output-type
(find output-type '(css inline-css nil))))
(converted
(with-temp-buffer
(insert-file-contents-literally file)
(org-export-as backend nil nil t nil)))) converted))
```
The trouble is this: `org-html-htmlize-output-type` only accepts three values, `'css`, `'inline-css`, or `nil`. However, when a user fails to provide an optional argument, `nil` is passed. I have no way to discern if `nil` was provided intentionally as the preferred `OUTPUT-TYPE` or if it was simply ignored in favor of the default!
How is such a dilemma commonly handled?
One approach is to create a new value to represent `nil` and use `cond` to filter for the various choices:
```
(defun my-export (file &optional toc section-num output-type backend)
(let* ((org-export-with-toc toc)
(org-export-with-section-numbers section-num)
(backend (or backend 'html))
;; To toggle nil, user must specify 'plain-text
(org-html-htmlize-output-type
(cond ((eq output-type 'css) type)
((eq output-type 'inline-css) type)
((eq output-type 'plain-text) nil)
('css)))
(converted
(with-temp-buffer
(insert-file-contents-literally file)
(org-export-as backend nil nil t nil))))
converted))
```
Another thought I had was to use `'nil` instead of `'plain-text` but (un)fortunately `(eq nil 'nil)` is `t`.
---
Timing all the options, they are all on par.
```
(defun test-export-cond (file &optional arg1 arg2 arg3 opt4)
"Test export using cond."
(let* ((opt1 arg1)
(opt2 arg2)
(opt3 (cond ((eq arg3 'css) type)
((eq arg3 'inline-css) type)
((eq arg3 'plain-text) nil)
('css)))
(opt4 (or opt4 'html)))
(list file opt1 opt2 opt3 opt4)))
(defun test-export-if (file &rest rargs)
"Test export using if."
(let* ((nargs (length rargs))
(opt1 (nth 0 rargs))
(opt2 (nth 1 rargs))
(opt3
(if (< nargs 3)
'css
(nth 2 rargs)))
(opt4
(if (< nargs 4)
'html
(nth 3 rargs))))
(list file opt1 opt2 opt3 opt4)))
(cl-defun test-export-cl (file &optional arg1 arg2 (arg3 'css) (opt4 'html))
"Test export using cl-lib."
(let* ((opt1 arg1)
(opt2 arg2)
(opt3 arg3))
(list file opt1 opt2 opt3 opt4)))
(test-export-cond "~/file.txt")
(test-export-if "~/file.txt")
(test-export-cl "~/file.txt")
(defmacro test-measure-time (times &rest body)
"Measure the average time it takes to evaluate BODY."
`(let ((cur-time (current-time)))
(dotimes (i ,times)
,@body)
(message "%.06f" (/ (float-time (time-since cur-time))) ,times)))
(setq test-do-times 1000000)
(test-measure-time test-do-times (test-export-cond "~/file.txt")) ; "0.063467"
(test-measure-time test-do-times (test-export-if "~/file.txt")) ; "0.064669"
(test-measure-time test-do-times (test-export-cl "~/file.txt")) ; "0.066125"
```
# Answer
> 4 votes
A simple way to differentiate between value `nil` and a missing optional argument is to use `&rest` instead of `&optional`. I demonstrate that with the following test function:
```
(defun testfun (arg &rest optArgs)
"Do something with ARG, OPT1, and OPT2.
OPT1 and OPT2 can be nil, 1, and 2.
The default of OPT1 is 1 and the default of 2 is 2.
\(fn ARG &optional OPT1 OPT2)"
(let* ((nOpt (length optArgs))
(opt1 (if (< nOpt 1)
1
(nth 0 optArgs)))
(opt2 (if (< nOpt 2)
2
(nth 1 optArgs))))
(list arg opt1 opt2)))
```
Note also the `\(fn ARG &optional OPT1 OPT2)` in the doc string. That replaces the actual implementation `(testfun ARG &rest OPTARGS)` in the help buffer generated by `describe-function`. In this way the user is not bothered with the implementation details but directly informed about the meaning.
Test 1: Set `opt2` explicitly to nil:
```
(testfun 1 'a nil)
```
(1 a nil)
Test 2: Setting `opt1` and `opt2` explicitly to nil:
```
(testfun 1 nil nil)
```
(1 nil nil)
Test 3: Setting `opt1` explicitly to nil and using default `opt2`:
```
(testfun 1 nil)
```
(1 nil 2)
Test 4: Only using default values:
```
(testfun 1)
```
(1 1 2)
That is the way if you do not want to draw in `cl-lib`. But, wait... I will provide another solution with `cl-lib`.
# Answer
> 2 votes
`cl-defun` from `cl-macs.el` allows you to specify default values (beside much other mind-blowing stuff).
```
(cl-defun testfun (arg &optional (opt1 1) (opt2 2))
"Process normal ARG and optional args OPT1 and OPT2 with defaults 1 and 2, respectively."
(list arg opt1 opt2))
```
Test 1: Set `opt2` explicitly to nil:
```
(testfun 1 'a nil)
```
(1 a nil)
Test 2: Setting `opt1` and `opt2` explicitly to nil:
```
(testfun 1 nil nil)
```
(1 nil nil)
Test 3: Setting `opt1` explicitly to nil and using default `opt2`:
```
(testfun 1 nil)
```
(1 nil 2)
Test 4: Only using default values:
```
(testfun 1)
```
(1 1 2)
# Answer
> 1 votes
The cleanest way IMO is to define an additional variable in the argument list that indicates if the argument was supplied by the caller. This can be done using `cl-defun` since it supports Common Lisp style argument lists. For example,
```
(require 'cl-macs)
(cl-defun test (&optional (x nil supplied-p))
(list x supplied-p))
(test) => (nil nil)
(test 1) => (1 t)
(test nil) => (nil t)
```
---
Tags: functions, arguments
---
|
thread-55645
|
https://emacs.stackexchange.com/questions/55645
|
org-agenda-files variable is getting reset each time I launch emacs
|
2020-02-19T21:14:42.083
|
# Question
Title: org-agenda-files variable is getting reset each time I launch emacs
Each time I launch Emacs, `org-agenda-files` is reset to `nil`. I can `C-h v org-agenda-files`, which confirms that the value of the variable is `nil`.
I have the following in `.emacs.d/package-init.el`:
```
(use-package org
:ensure t
:config
(setq org-agenda-files (quote ("~/org/"))
org-startup-indented 1
org-default-notes-file (concat org-directory "/inbox.org")
org-refile-targets '(
(nil :maxlevel . 9)
(org-agenda-files :maxlevel . 9)
)
org-agenda-window-setup 'current-window
org-agenda-restore-windows-after-quit t
)
(define-key global-map "\C-cc" 'org-capture)
(global-set-key (kbd "C-c l") 'org-store-link)
(global-set-key (kbd "C-c a") 'org-agenda)
(global-set-key (kbd "C-c c") 'org-capture)
(add-hook 'org-mode-hook 'turn-on-flyspell)
)
```
Everything else under the `:config` for org mode is getting set correctly.
What’s really strange is that if I open the package config file as a buffer and `M-x eval-buffer`, `org-agenda-files` gets set correctly, which I can confirm by using help on the variable.
How is this possible?
# Answer
Check your custom.el.
I have frequently been caught out with having explicit :custom sections in use-package forms. Often things are saved in groups including these values - and the custom.el values then override your :custom declarations.
Look for custom-set-variables.
> 1 votes
# Answer
So, it looks like there was a line in `(custom-set-variables)` in my init.el that was setting `(org-agenda-files)` to `nil`. `(custom-set-variables)` is after the line where I source my package\_config.el.
Seems silly that I didn't notice that to begin with, sorry that I wasted anyones time. Honestly, I'm not sure what the `(custom-set-variables)` chunk in my `.init.el` is, I'm fairly new to Emacs. The commonts in the chunk say not to edit it by hand, so I just kind of ignore it.
Thanks for all the help everyone!
> 0 votes
---
Tags: org-mode
---
|
thread-55657
|
https://emacs.stackexchange.com/questions/55657
|
Bind keybord shortcuts to a MIDI keyboard?
|
2020-02-20T19:58:20.650
|
# Question
Title: Bind keybord shortcuts to a MIDI keyboard?
I'm exploring the possibility of using a programmable keybord like this one:
https://storefront.expertkeys.com/startseite/28-expertkeys-ek-20-usb-tastatur-0700587547911.html
to expand and simplify my keyboard shortcuts.
Now I'm wondering if there is the possibility to use a musical MIDI keyboard instead? E.g. like this one:
https://www.akaipro.com/lpk25
This solution would be much cheaper and, in my opinion, "smarter".
Anyone have news of such a project?
# Answer
I'd suggest not using a midi keyboard, but instead, using any keyboard which is capable of running `QMK` firmware.
This has the following advantages:
* It can work in any application and doesn't rely on configuring your operating system/software for non-standard input devices *(from the perspective of using it for keyboard shortcuts at least).*
* You can enable modifier keys to switch layers.
* You can configure keys to run multiple keystrokes (including typing in text).
* It can record/playback macros.
You could use the plank keyboard or lets-split as a large num-pad, programming F-Keys 13..24, as well as other available keys.
For example, you could bind each key to a `Hyper-[A-Z]` combination, assuming you're not already using the Hyper modifier elsewhere.
See qmk/keyboards for a full list of supported keyboards.
> 1 votes
---
Tags: key-bindings
---
|
thread-38708
|
https://emacs.stackexchange.com/questions/38708
|
How to replace the default contents of the scratch buffer with the contents of a file (if it exists)?
|
2018-02-09T07:07:30.060
|
# Question
Title: How to replace the default contents of the scratch buffer with the contents of a file (if it exists)?
I would like emacs to check for a `~/emacs.d/scratch.txt` and use it's contents instead of the default message when emacs starts.
How can this be done?
# Answer
> 3 votes
`initial-buffer-choice` allows to specify a path to a file or directory:
```
(let ((filename "~/.emacs.d/startup.txt"))
(when (file-exists-p filename)
(setq initial-buffer-choice filename)))
```
# Answer
> 3 votes
This will do the job.
```
(let ((filename (concat user-emacs-directory "scratch.txt")))
(when (file-exists-p filename)
(let ((scratch-buf (get-buffer "*scratch*")))
(when scratch-buf
(with-current-buffer scratch-buf
(erase-buffer)
(insert-file-contents filename))))))
```
# Answer
> 2 votes
This can be done using `initial-buffer-choice`,
While `initial-buffer-choice` can be set to a filename, this will load the file as well as any files passed via the command line *(splitting the window or not even showing the buffer depending on your setup)*.
So reading file data into `*scratch*` buffer has the advantage that exact behavior is preserved, just replacing the text.
This example:
* Only runs when the user starts without loading a file.
* Loads in a text file into the startup buffer.
* Users a default `startup.txt`, optionally taking a user defined startup file.
* Sets the mode based on the filename, so users can pass in `startup.org` for an org-mode buffer.
* Adds a short commented line at the top of the file, eg:
`# Emacs: 28.0, time: 0.93, packages: 58`
* When no startup file is found, the name of the file to create is referenced.
```
;; Load startup text when available.
;;
;; Example usage:
;;
;; (my-scratch-buffer-from-file)
;;
;; Or if you like to use an org-mode scratch buffer,
;; an option file path can be passed in.
;; The file extension is used to set the mode:
;;
;; (my-scratch-buffer-from-file (concat user-emacs-directory "scratch.org"))
;;
(defvar my-scratch-buffer-from-file--value nil)
(defun my-scratch-buffer-from-file (&optional scratch-file)
(setq inhibit-startup-screen t)
(setq initial-scratch-message nil)
(when scratch-file
(setq my-scratch-buffer-from-file--value scratch-file))
(setq
initial-buffer-choice
(lambda ()
(if (buffer-file-name)
(current-buffer) ;; leave as-is
(let ((original-buffer (current-buffer))
(filename
(or my-scratch-buffer-from-file--value
(concat user-emacs-directory "scratch.txt")))
;; Not essential, just gives some handy startup info.
(startup-info
(format
"Emacs: %d.%d, time: %.2f, packages: %d"
emacs-major-version
emacs-minor-version
(float-time (time-subtract after-init-time before-init-time))
(length package-activated-list))))
(with-current-buffer (get-buffer-create "*scratch*")
;; Don't track undo.
(buffer-disable-undo)
;; Set the mode based on the filename, users may use filenames that infer modes.
(condition-case err
(let ((buffer-file-name filename))
(set-auto-mode t))
(error (message "Unable to activate mode: %s" err)))
;; Use the comment character set by the mode where possible.
(let ((comment-start-or-empty
(if comment-start
;; Ensure one trailing space (some comments include space).
(concat
(replace-regexp-in-string "[[:blank:]]*$" "" comment-start)
" ")
"")))
(if (file-exists-p filename)
(insert-file-contents filename)
(insert
comment-start-or-empty
(format "Scratch buffer, create '%s' to replace this text on startup."
filename))
(goto-char (point-min)))
;; Add some startup info above the static text.
(insert comment-start-or-empty startup-info "\n\n"))
(buffer-enable-undo)
(set-buffer original-buffer)))))))
```
---
Others might suggest how this can be done better, it seems to work well enough though.
# Answer
> 2 votes
I would use `initial-scratch-message`.
```
(let ((file "~/.emacs.d/scratch.txt"))
(when (file-exists-p file)
(setq initial-scratch-message
(with-temp-buffer
(insert-file-contents file)
(buffer-string)))))
```
---
Tags: start-up, scratch-buffer
---
|
thread-55647
|
https://emacs.stackexchange.com/questions/55647
|
Manually close a (compilation) window that was most recently opened by running e.g. 'grep'
|
2020-02-20T10:28:57.457
|
# Question
Title: Manually close a (compilation) window that was most recently opened by running e.g. 'grep'
I'm trying to find a way to quickly close the window that I just created by running 'grep' (i.e. a kind of compilation window).
I'd like the solution to be independent of my current window layout and also of which window that's currently in focus. This so I can always use the same keyboard shortcut.
I thought I could find an Emacs command to switch to the most recently created window, i.e. the one just created by 'grep'. Then I could just use that command followed by 'q' to close the 'grep' window. However, I haven't been able to find such a command.
Unfortunately the 'other-window' command (C-x o) doesn't work as well as I'd like in the following configuration. Here the Emacs frame is split into two windows (C-x 3) with the cursor in the right window (W2). I.e. it initially looks like this:
```
.-------.-------.
| W1 | W2 _ |
| | |
| | |
| | |
'-------'-------'
```
Then, after the grep command, it looks like this, with focus still on 'w2':
```
.-------.-------.
| W1 | W2 _ |
| | |
|-------| |
| *grep*| |
'-------'-------'
```
The annoyance is now that 'C-x o' switches to 'W1' rather than 'grep'.
Now, when I'm in 'W2' I can use e.g. 'C-- C-x o' to switch to 'grep'. But unfortunately, but if the cursor is instead in 'W1', then 'C-- C-x o' leaves me in 'W2' rather than 'grep'. So I'll then have to remember which command to use depending on my location.
Note: I could create a shortcut that closes the 'grep' window/buffer, but it'd be nice if the solution here works also for other compilation-like windows.
Update/clarification:
If the Emacs frame isn't as tall, e.g. on a laptop, this window setup:
```
.-------.-------.
| W1 | W2 _ |
| | |
'-------'-------'
```
results in 'W1' being replaced by 'grep' instead of a 'grep' window being added. I.e. it results in this:
```
.-------.-------.
| grep | W2 _ |
| | |
'-------'-------'
```
In this case, as some of the answers suggest deleting the 'grep' window, the resulting window setup ends up being this:
```
.---------------.
| W2 _ |
| |
'---------------'
```
So it turns out I don't necessarily/always want to delete the window containing the 'grep' buffer.
# Answer
If you want to target whichever compilation (or similar) buffer is *currently* being used by `next-error` and `previous-error`, I would suggest this:
```
(defun my-delete-compilation-window ()
"Delete all windows displaying the `next-error-find-buffer' buffer."
(interactive)
(when-let ((buf (next-error-find-buffer)))
(delete-windows-on buf)))
```
Or based on the modified requirements:
```
(defun my-quit-compilation-window ()
"Invoke `quit-window' for all windows displaying the compilation buffer."
(interactive)
(when-let ((buf (next-error-find-buffer)))
(let (win)
(while (setq win (get-buffer-window buf t))
(quit-window nil win)))))
```
n.b. In either case you may need to `(require 'subr-x)` for the use of `when-let`.
> 2 votes
# Answer
The Elisp below defines a command `my-delete-compilation-window` that deletes the first compilation window in the window list. That should normally be the last selected compilation window. The command is bound to `C-c w` but you can modify that to your own liking.
```
(defmacro with-compilation-window (&rest body)
"Select first compilation window in `window-list' and eval BODY.
BODY is not evaluated if there is no window in `compilation-mode'."
(declare (debug body))
`(cl-loop for win being the windows do
(with-selected-window win
(when (derived-mode-p 'compilation-mode)
(progn ,@body)
(cl-return)))))
(defun my-delete-compilation-window ()
"Delete compilation window found first in `window-list'."
(interactive)
(with-compilation-window
(delete-window)))
(global-set-key (kbd "C-c w") #'my-delete-compilation-window)
```
> 2 votes
# Answer
Add the following to your init file:
```
(winner-mode 1)
```
Then whenever your window configuration is unexpectedly changed, or you simply want to go back to an earlier configuration, use `C-c``<left>` to call `winner-undo` (which you can do repeatedly if necessary).
Obviously if additional window config changes have happened since the window in question was created (if you had navigated through the grep results, for instance), then this solution might be less practical; although note that you can use `repeat` to ease the process: `C-c``<left>``C-x``z``z``z`...
`C-c``<right>` returns you to the most recent configuration (immediately, rather than step-by-step).
> 2 votes
# Answer
Not necessarily a single key press, but this can help, I think: by default, `C-x 0` in minor mode Icicle is bound to command `icicle-delete-window`. You can use a prefix arg to pick which window(s) to delete.
> **`C-x 0`** runs the command **`icicle-delete-window`** (found in `icicle-mode-map`), which is an interactive compiled Lisp function in `icicles-cmd1.el`.
>
> It is bound to `C-x C-z`, `C-x 0`, `remap delete-window`.
>
> `(icicle-delete-window BUFFERP)`
>
> `delete-window` or prompt for buffer and delete all its windows.
>
> When called from the minibuffer, remove the `*Completions*` window.
>
> Otherwise:
>
> * With no prefix argument, delete the selected window.
> * With a prefix argument, prompt for a buffer and delete all windows, on any frame, that show that buffer.
>
> With a prefix argument, this is an Icicles multi-command - see command `icicle-mode`. Input-candidate completion and cycling are available. While cycling, these keys with prefix **`C-`** are active:
> * `C-RET` \- Act on current completion candidate only
> * `C-down` \- Move to next completion candidate and act
> * `C-up` \- Move to previous completion candidate and act
> * `C-next` \- Move to next apropos-completion candidate and act
> * `C-prior` \- Move to previous apropos-completion candidate and act
> * `C-end` \- Move to next prefix-completion candidate and act
> * `C-home` \- Move to previous prefix-completion candidate and act
> * `C-!` \- Act on *all* candidates (or all that are saved), successively (careful!)
>
> With prefix **`C-M-`** instead of `C-`, the same keys (`C-M-mouse-2`, `C-M-return`, `C-M-down`, and so on) provide help about candidates.
>
> Use `mouse-2`, `RET`, or `S-RET` to finally choose a candidate, or `C-g` to quit.
>
> By default, Icicle mode remaps all key sequences that are normally bound to `delete-window` to `icicle-delete-window`. If you do not want this remapping, then customize option `icicle-top-level-key-bindings`.
> 0 votes
# Answer
Easiest way IMO which is usable across windows of all types is simply to use the excellent ace windows extension:
```
(use-package ace-window
:bind*
("C-x o" . ace-window)
("C-x O" . ace-delete-window))
```
Here's what I see when I "ace delete" with three windows open. It is clever when you have 2.. obviously, delete the other one.
> 0 votes
---
Tags: window
---
|
thread-55207
|
https://emacs.stackexchange.com/questions/55207
|
Org-Babel Unable to Tangle to Write-Protected Folders?
|
2020-01-31T02:39:44.750
|
# Question
Title: Org-Babel Unable to Tangle to Write-Protected Folders?
I'm trying to move my OS configuration over to org mode, and in the process I'd like to be able to tangle to write-protected directories like /etc
Unfortunately, tangle doesn't seem to work whenever the target file needs elevated permissions. So for instance, using `org-babel-tangle` works on this code block
```
#+BEGIN_SRC sh :tangle psmouse.conf
options psmouse synaptics_intertouch=1
#+END_SRC
```
but trying to tangle this one will ask me for my password (which I can give just fine) and then promptly fail
```
#+BEGIN_SRC sh :tangle /sudo::/etc/modprobe.d/psmouse.conf
options psmouse synaptics_intertouch=1
#+END_SRC
```
The error message I get in the minibuffer says
```
Copying directly failed. See buffer '*tramp/sudo root@pop-os*' for details
```
But the weird part is, although the buffer mentioned above is created on error, it's actually empty.
My *Messages* buffer is a little bit more informative as to what's going on
```
Setting up indent for shell type bash
Indentation variables are now local.
Indentation setup for shell type bash
Copying /tmp/tramp.l6Xnsw.conf to /sudo:root@pop-os:/etc/modeprobe.d/psmouse.conf...failed
tramp-error: Copying directly failed, see buffer ‘*tramp/sudo root@pop-os*’ for details.
```
# Answer
The source of the error ended up being a spelling mistake on my part. See my comments on the question. Thanks to @Melioratus for their help!
> 1 votes
---
Tags: org-mode, org-export, spacemacs, org-babel
---
|
thread-55682
|
https://emacs.stackexchange.com/questions/55682
|
Emacs 26.3: Weird frame title issue with KDE
|
2020-02-21T19:03:14.390
|
# Question
Title: Emacs 26.3: Weird frame title issue with KDE
I recently switched to CentOS 7.7, KDE 4.x, and Emacs 26.3. Previously, I was using GNOME and a much older version of Emacs. Before, whenever I opened Emacs, the titlebar of a lone Emacs window was `emacs@hostname`. Now, it's `emacs@hostname <@hostname>`, which seems less than desirable. I can't figure out if the issue is with Emacs or KDE. Any ideas as to what is wrong here and what I can do to get it back to `emacs@hostname`?
# Answer
> 0 votes
Emacs controls its frametitle via variable `frame-title-format`.
So you could change the value of that variable temporarily, to get an idea weather or not KDE is manipulating it somehow.
I.e. do `M-: (setq frame-title-format "foobar")` `return` and check the new title of the frame.
If the frametitle is now `foobar <@hostname>`, then KDE changes it and you have to look into KDE settings or KDE applets, plugins or whatever to modify the behavior.
If it is now just `foobar`, then it is controlled entirely by emacs. Have a read at EmacsWiki: Frame Title to see what options you can use to change it to what you like.
---
Tags: frames
---
|
thread-55663
|
https://emacs.stackexchange.com/questions/55663
|
Using ctrl-n and ctrl-p inside the box for suggessted words to auto-complete
|
2020-02-20T22:43:34.297
|
# Question
Title: Using ctrl-n and ctrl-p inside the box for suggessted words to auto-complete
By default to move up (`ctrl-p`) and to move down (`ctrl-n`) key bindings are used.
When I am using auto-complete mode, a box with suggested words is pop up. On there when I press `ctrl-p` or `ctrl-n` instead of moving within the box, it closes from it. I can move around only by using `tab` or `alt-p` or `alt-n`.
**\[Q\]** Inside the box for suggessted word to auto-complete, is there any way to move around by `ctrl-p` and `ctrl-n`?
# Answer
> 2 votes
You can configure that behaviour via customize.
Just do `M-x customize-option` `<return>` `ac-use-menu-map` `<return>`, then set this option to `on (non-nil)` and save it for future use.
Thats it.
How did I get this information? I looked at the source code. But it was also possible to find this from `M-x customize-group` `<return>` `auto-complete` `<return>`.
---
Nevertheless, I would recommend, switching to another completion framework (like `company`) because auto-complete seems abandoned. With last commit in Jan 2017.
*Edit:* To enable this behaviour with company, simply bind the keys and corresponding functions in companys keymap:
```
(with-eval-after-load "company"
(define-key company-active-map (kbd "C-p") #'company-select-previous-or-abort)
(define-key company-active-map (kbd "C-n") #'company-select-next-or-abort))
```
---
Tags: key-bindings, auto-complete-mode
---
|
thread-7761
|
https://emacs.stackexchange.com/questions/7761
|
Use the command key in Terminal on OSX?
|
2015-01-28T14:09:12.150
|
# Question
Title: Use the command key in Terminal on OSX?
Is there a way to use the Apple command key in Emacs in the terminal? It would be nice to expand the set of easy to get at key bindings I can use.
# Answer
> 5 votes
I am using macOS Catalina, and iTerm2 3.3. This method probably works for several prior versions of macOS and iTerm2 but I have not researched it.
Note that when you remap the modifier keys below using iTerm2, will need to allow iTerm2 to "control" the OS (or take care of it when iTerm2 asks you to allow it) by checking iTerm under Security & Privacy-\>Accessibility. You can uncheck it after the procedure is done if that is an issue.
1. First, remap the Left Option key in your Profile to Esc+. This allows a terminal Emacs to use the Left Option (Alt) key as Meta. To do this:
a. In iTerm2 Preferences, click on Profiles, then on your default Profile, then click the button next to Esc+.
2. Then, while still in Preferences click Keys-\>Remap Modifiers. This will allow you to switch the Command key with the Alt Key. After you do this, a terminal Emacs will use the Command key to send Meta- to Emacs.
a. Remap left command key to Left Option.
b. Remap left option key to Left Command.
Note that while you are using terminal Emacs in iTerm2 you will have to use the Option key to do whatever MacOS believes is mapped to the Command key, for example, to Tab between Spaces. Once you are out of iTerm2 the Command key works normally again.
# Answer
> 3 votes
The answer below tells you how to use Command as a second, redundant Meta key, which is pointless. As far as I know, it's not possible to use Command as a distinct modifier key in Terminal/iTerm---say, by mapping Command it to the Hyper key, for instance---the way you can with GUI Emacs.
# Answer
> 0 votes
First stem, get iTerm!
After that, (this has been answered here, so I can't take credit for it.)
Go to Bookmarks \> Manage Profiles. Then select Keyboard Profiles \> Global and choose Option Key as Meta.
# Answer
> 0 votes
cmd-key-happy will do this for Terminal - and other applications.
---
Tags: key-bindings, osx, terminal-emacs
---
|
thread-36899
|
https://emacs.stackexchange.com/questions/36899
|
Disable clickable links for misspelled words (flyspell)
|
2017-11-15T23:27:05.573
|
# Question
Title: Disable clickable links for misspelled words (flyspell)
Is there a way to disable the way flyspell converts misspelled words into clickable links, as well as the background colour (pink, at least for my colour theme) it uses?
I find it confusing and unnecessary.
See here:
# Answer
> 1 votes
Following code installs an advice, which removes the overlay properties which flyspell uses on incorrect words for mouse operations.
```
(defun make-flyspell-overlay-return-mouse-stuff (overlay)
(overlay-put overlay 'help-echo nil)
(overlay-put overlay 'keymap nil)
(overlay-put overlay 'mouse-face nil))
(advice-add 'make-flyspell-overlay :filter-return #'make-flyspell-overlay-return-mouse-stuff)
```
---
To make above code working automatic from your init.el, it needs to be evaled after flyspell has been loaded. Below are two variants, one for users of `use-package` and one for users without `use-package`. Replace `...` with the above given code.
without `use-package`:
```
(with-eval-after-load "flyspell"
...
)
```
with `use-package`:
```
(use-package flyspell
:config
...
)
```
---
Tags: flyspell
---
|
thread-41339
|
https://emacs.stackexchange.com/questions/41339
|
Copy/paste between SSH terminal Emacs and macOS
|
2018-05-05T00:05:36.080
|
# Question
Title: Copy/paste between SSH terminal Emacs and macOS
Suppose you are working in macOS, and you decide to SSH into a Linux box and fire up terminal Emacs. **How do you copy and paste between macOS and your SSH terminal-Emacs?**
Copying and pasting between macOS and *local* terminal-Emacs is not a problem with `xclip`: install `xclip` through ELPA and put `(xclip-mode 1)` in your Emacs init file. This doesn't work when running terminal Emacs over an SSH session, however, and while there is much information online about accessing the X11 clipboard from Emacs, I am running terminal Emacs on a remote machine that doesn't have X11 installed either way. Is there a solution for terminal Emacs copy-paste over an SSH session?
# Answer
I just recently wrote an Emacs package called Clipetty which solves this very problem. It uses OSC-52 xterm escape sequences, is smart enough to know when you're running on a remote host, and can deal with both nested and non-nested terminal multiplexers like GNU Screen and Tmux. The README.md file explains in more detail how it works.
> 4 votes
# Answer
AFAIK there is no magic way to do that.
The closest thing I know uses the "OSC-52" xterm escape sequences. Emacs can use those if your xterm supports them, but AFAIK most builds disable them, partly because of security concerns.
See the values `getSelection` and `setSelection` in `xterm-extra-capabilities`. This support was new in Emacs-25, whose etc/NEWS file said:
```
*** Killing text now also sets the CLIPBOARD/PRIMARY selection
in the surrounding GUI (using the OSC-52 escape sequence). This only works
if your xterm supports it and enables the 'allowWindowOps' options (disabled
by default at least in Debian, for security reasons).
Similarly, you can yank the CLIPBOARD/PRIMARY selection (using the OSC-52
escape sequence) if your xterm has the feature enabled but for that you
additionally need to add 'getSelection' to 'xterm-extra-capabilities'.
```
> 3 votes
# Answer
I have just implemented a solution using reverse ssh tunneling.
On your mac you need to enable `Settings->Sharing->Remote Login`.
I connect to the remote server using this command: `ssh -R 1234:localhost:22 <user>@<remote-server>` where `1234` is a available port on your server.
Be sure to copy your ssh key from the remote server to your macOS user, on ubuntu that can easily be done by running `ssh-copy-id <macusername>@localhost:1234` after logging inn with the above command. This makes the solution work without having to enter you mac password everytime you copy.
In my `.emacs` file I add:
```
(defun write-region-to-client-clipboard (beg end)
(interactive "r")
(copy-region-as-kill beg end)
(shell-command-on-region beg end "ssh -p 1234 <macusername>@localhost pbcopy" nil nil nil t))
(global-set-key (kbd "C-u") 'write-region-to-client-clipboard)
```
So now when I mark a region in emacs and hit `Ctrl + u` it copies the region to my macOS client's clipboard, as well as to my emacs kill-ring(clipboard)
This only works when copying within emacs, but could be setup to work from a remote tmux session as well.
> 1 votes
# Answer
This is possible using Tmux and iTerm2. I am using Tmux version 3.0, iTerm2 version 3.3 and macOS Catalina. It probably works for a few earlier version but I have not researched it.
First, you need to enable iTerm2 to access the system clipboard. It is not enabled by default.
1. iTerm2 -\> Preferences -\> Selection -\> \[check\] Applications in terminal may access clipboard.
Then, from within a tmux session, ssh into your system and go to where you want to copy something.
2. At this point you need to know how to enter Tmux's "copy mode".
a. The default method is to use the key combination: `prefix-[`
b. Now you need to know how to select what you want. Tmux's 'copy-mode' has two different methods depending on how you have set up your environment. One way is to use 'vi' key bindings; the other is to use 'emacs' key bindings. You either need to know which key bindings your system uses, or configure tmux to use the one you want.
c. Assuming you know how to select, then you just need to paste, and the selection will be added to macOS's system clipboard.
Tmux's man page has information under the heading "Windows and Panes", then directly under that, 'copy mode'. Once you get the configuration and key bindings figured out, it is just a matter of copying and pasting from within iTerm2 inside a tmux session ssh'ed into your Linux box.
> 0 votes
---
Tags: osx, terminal-emacs, copy-paste, ssh, linux
---
|
thread-55706
|
https://emacs.stackexchange.com/questions/55706
|
Symbol's function definition is void: cl-loop
|
2020-02-22T18:38:49.620
|
# Question
Title: Symbol's function definition is void: cl-loop
I'm trying to turn off all colored text when using gnu emacs as `emacs -nw` on linux. This answer gives a snippet of code to use for this purpose:
```
(cl-loop for face in (face-list) do
(set-face-attribute face nil :foreground nil :background nil))
```
However, when I put this in my .emacs file, I get this error:
```
Symbol's function definition is void: cl-loop
```
How do I fix this?
# Answer
The direct solution is to `(require 'cl-lib)` somewhere, but this is a trivial enough loop that Emacs comes with a macro specifically for it, without needing `cl-lib`:
```
(dolist (face (face-list))
(set-face-attribute face nil :foreground nil :background nil))
```
> 2 votes
---
Tags: init-file, cl-lib
---
|
thread-55406
|
https://emacs.stackexchange.com/questions/55406
|
use-package: autoload function outside the main package file
|
2020-02-10T15:17:07.717
|
# Question
Title: use-package: autoload function outside the main package file
I am trying to install simplenote2 to read my org files on my phone. The official setup method is:
```
(require 'simplenote2)
(setq simplenote2-email "email@example.com")
(setq simplenote2-password "yourpassword")
(simplenote2-setup)
```
and the app starts with
```
M-x simplenote2-list
```
In practice credentials are not necessary in clear and `(require...)` can be omitted because `simplenote2-setup` is autoloaded.
I would like to use a `use-package` declaration, therefore I am using:
```
(use-package simplenote2
:config
(setq simplenote2-email "email@example.com")
(setq simplenote2-password "yourpassword")
(setq simplenote2-notes-mode (quote org-mode))
(simplenote2-setup))
```
(The extra line is for org-mode integration).
When I start the library with `M-x simplenote2-list`, I get an error due to a void variable `simplenote2-notes-info-version`. This variable is defined through a `defvar` in simplenote2.el. So, it seems that the `use-package` declaration is not requiring `simplenote2.el`.
The likely cause is that the autoloaded function `simplenote2-list` is defined in the separate file `simplenote2-list.el`. Therefore `simplenote2-list` requires only `simplenote2-list.el`, but not `simplenote2.el`.
If this is the cause, how can I instruct `use-package` to require also `simplenote2.el` the first time `M-x simplenote2-list` is run?
Or alternatively: before running `M-x simplenote2-list`, how can I run the autoloaded `(simplenote2-setup)`, which automatically requires `simplenote2.el`?
Note that I have the global option `use-package-always-defer` set true.
# Answer
> 1 votes
You cannot easily run `simplenote2-setup` when lazy loading the package.
However, there are several options, to make lazy loading happening:
---
1. use of `:after` and defining a use-package declaration for `simplenote2-list` i.e.:
```
(use-package simplenote2-list
:after (simplenote2))
```
---
2. require `simplenote2` from simplenote2-list use-package declaration
```
(use-package simplenote2-list
:config (require 'simplenote2))
```
---
3. you could define a keybinding for `simplenote2-list` from `simplenote2 use-package` declaration:
```
(use-package simplenote2
:bind ("C-c s" . simplenote2-list)
:config
...)
```
This works for the same reason like the next option.
---
4. a somewhat hacky one, declaring `simplenote2-list` as command of `simplenote2`. This works because `simplenote2-list` is required by `simplenote2`.
```
(use-package simplenote2
:commands (simplenote2-list)
:config
...)
```
---
5. if simplenotes2 is able to be started with hooks or mode-interpreters, you could emulate the simplenote2-setup with keywords `:mode` or `:hook`. Please read the use-package manual.
---
Tags: package, use-package, autoload, require
---
|
thread-55328
|
https://emacs.stackexchange.com/questions/55328
|
change use-package indentation
|
2020-02-05T21:37:58.600
|
# Question
Title: change use-package indentation
I'd like to change `use-package`'s indentation style to look more distinguishable, (more or less) similar like the following indentation style:
```
(use-package foo
:commands (gah)
:init (setq f 1)
(blubb g 2)
:config
(blah h 3)
(moo i 4))
```
This means, keywords should be indented normal but all following options to such a keyword, should be indented a bit more and should align vertically.
---
I already know, that it is possible to define a function to calculate the current indentation column. Per default it is set to standard `defun` indentation:
```
(get 'use-package 'lisp-indent-function)
; → defun
```
The following function definition and set up of property, changes that, but I struggle with the implementation details of function `my-use-package-indent-function`.
```
(defun my-use-package-indent-function (indent-point state)
(let* ((normal-indent (current-column))
(indent-offset (progn (back-to-indentation)
(current-column))))
(goto-char indent-point)
(back-to-indentation)
(if (eq ?: (char-after))
(+ indent-offset 2)
(+ indent-offset 5))))
(put 'use-package 'lisp-indent-function #'my-use-package-indent-function)
```
Above is a naive, incomplete version, but how to calculate the indentation value properly?
# Answer
Since no one came up with an answer, I stepped with the debugger through the process of indenting and came up with following code.
```
(defun my--use-package-indent-function (indent-point state)
"custom indentation rules for use-package s-exps.
`;;!' indents to same level as keywords
for some reason `;;;' won't be indented at all"
(let ((indent-offset (progn (back-to-indentation)
(current-column))))
(goto-char indent-point)
(back-to-indentation)
(cond ((eq ?: (char-after))
(+ indent-offset 2))
((and (eq ?\; (char-after)) (eq ?! (char-after (+ (point) 2))))
(+ indent-offset 2))
((eq ?\) (char-after))
(+ indent-offset 2))
((eq ?: (progn (backward-sexp)
(char-after)))
(+ indent-offset (+ 2 4)))
(t (current-column )))))
(put 'use-package 'lisp-indent-function #'my--use-package-indent-function)
```
It seems to work, but I'm unsure how robust this code is.
Better implementations are welcome!
*Edit*: following code sets up electric indent to trigger on ':', so keywords will be indented right at insertion.
```
(setq electric-indent-chars (append electric-indent-chars '(?:)))
```
> 2 votes
---
Tags: indentation, use-package
---
|
thread-55715
|
https://emacs.stackexchange.com/questions/55715
|
Disable coloring of text in operations in emacs -nw, during operations like searching
|
2020-02-23T01:11:43.890
|
# Question
Title: Disable coloring of text in operations in emacs -nw, during operations like searching
I'm using gnu emacs as `emacs -nw` in a terminal window. Colored text is usually almost completely illegible for me. As recommended in this answer, I have done the following in an attempt to get rid of all coloring:
```
(dolist (face (face-list))
(set-face-attribute face nil :foreground nil :background nil))
```
However, I still get colored text when I do operations like searching. For example, if I do control-S, I get a dark blue prompt that says "I-search," and if the search is failing, then the trailing part of the search string is highlighted in pink.
Also, if I start up emacs without giving a filename, there is a help screen with hyperlinks, which are colored.
Is there some way to get rid of these other types of coloring as well?
# Answer
> 0 votes
You need to run your uncolor loop after loading of any package, because packages can introduce new colored faces when they (lazy or auto) load.
To ensure all colors are removed after any loading of a package, you could use the hook `after-load-function`. Following code will do this:
```
(defun uncolor-after-load (&rest foo)
(dolist (face (face-list))
(set-face-attribute face nil :foreground nil :background nil)))
(add-to-list 'after-load-functions #'uncolor-after-load)
```
*Edit:* `after-load-functions` is a list of functions, so I changed the `setq` above to an `add-to-list`, which keeps former entries.
---
Tags: display
---
|
thread-28736
|
https://emacs.stackexchange.com/questions/28736
|
Emacs point(cursor) movement lag
|
2016-11-18T10:45:21.637
|
# Question
Title: Emacs point(cursor) movement lag
When running `previous-line`, `C-p` or `<up>` the cursor jumps up a line without any issues or lags. When running `next-line`, `C-n` or `<down>` the cursor properly jumps down a line, but with a significant lag. When I hold the down key I can't even see the point moving, it just appears somewhere below. I ran the Emacs profiler and it seems that the culprit is `cl-position`. What it works out to be is that `previous-line` literally just moves the cursor, while `next-line` runs a whole lot of functions.
What is the issue and how can it be fixed?
# Answer
I have found an answer to my question through narrowing down the naughty bit and googling. I have managed to reduce the lag 10 TIMES!!!! I mean....It is insane on how much computing power `next-line` was using to move a cursor down ?!?!
The fix:
Put this code into your init.el: `(setq auto-window-vscroll nil)`
The proof:
Now `next-line` does not trigger `line-move-partial` therefore reducing the lag. I do not remember setting up `auto-window-vscroll` to `t`. It wasn't anywhere in any of my `.el` files, I am not sure how it got set to `t` to begin with. So if anyone has an performance issues with the cursor movement, then the above fix will reduce the lag from about 50%-80% cpu time to 5% cpu time !!!
To quickly check if you are affected just run `C-h v auto-window-vscroll`. If it is set to `t` you might be having major performance issues. Verify with the Emacs profiler if the cursor movement does indeed cause a lag.
Best of luck fellow Emacs lovers!!!
Source of fix
> 28 votes
# Answer
I'm not absolutely sure what is the problem, but your profiler report seems to indicate that posn-at-point performs more redisplay than expected, which in turns causes recomputation of the mode-line, and that powerline should make more effort to memoize its computation for the modeline.
IOW, I suggest you `M-x report-emacs-bug` and you might also report a bug to the powerline maintainers.
> 3 votes
# Answer
I noticed that my `doom-modeline` is also contributing to the lag. In fact, it is said in the doc of `doom-modeline`:
```
;; If it brings the sluggish issue, disable `doom-modeline-enable-word-count' or
;; remove the modes from `doom-modeline-continuous-word-count-modes'.
```
After setting `(setq doom-modeline-enable-word-count nil)` I got a noticeable speed-up in cursor movements.
> 1 votes
# Answer
It looks like you're using powerline. In particular, you're display the projectile project name in your modeline. There have been some improvements to the projectile package recently that have mitigated some of that. Make sure you're up to date.
https://github.com/bbatsov/projectile/issues/1212
https://github.com/bbatsov/projectile/pull/1213
It's also possible to memoize functions that the modeline calls. I've done this a lot on my modeline to make it very fast.
> 0 votes
---
Tags: point, motion
---
|
thread-55361
|
https://emacs.stackexchange.com/questions/55361
|
Org Reveal : Tabular fragments
|
2020-02-07T14:28:26.573
|
# Question
Title: Org Reveal : Tabular fragments
I'm using org-reveal to make a presentation.
I want to have elements in tabular form appear sequentially but in column-major order.
I know you can put `:frag` property-markers for gradual appearance. But I don't know how to do that inside tables.
Maybe tables are not the way to do this???
My basic question is how to make things appear (reveal!) in reveal in the general case:
* arbitrary order
* 2-d grid
# Answer
> 2 votes
You can use the following code as a starting point:
```
| @@html: <div class="fragment" data-fragment-index="0"> A </div>@@ | @@html: <div class="fragment" data-fragment-index="3"> B </div>@@ |
|--------------------------------------------------------------------+---|
| @@html: <div class="fragment" data-fragment-index="1"> C </div>@@ | @@html: <div class="fragment" data-fragment-index="2"> D </div>@@ |
```
Please notice the data-fragment-index property that give the order of appearance (first 0, then 1...). Also, the fragment class has several variants that you can find in the doc: https://github.com/hakimel/reveal.js/#fragments
# Answer
> 2 votes
For those who find this, heres a slightly less verbose approach to @Lgen 's answer using a macro `a` (for appear). Though I must confess to hardly knowing the ins and outs of macros in org
```
#+MACRO: a @@html: <span class="fragment" data-fragment-index="$2">$1</span>@@
* Column Major
| {{{a(Hello,0)}}} | {{{a(yes,1)}}} |
| {{{a(there,0)}}} | {{{a(no,1)}}} |
```
---
Tags: org-mode, org-table, org-reveal
---
|
thread-48205
|
https://emacs.stackexchange.com/questions/48205
|
How to execute external commands from an Eshell script
|
2019-03-06T21:09:37.147
|
# Question
Title: How to execute external commands from an Eshell script
I would like to create an elisp function such as
```
(defun script()
(run "bash" "-c" "echo 1; sleep 3; echo 2")
(eshell-print "Done"))
```
From an Eshell, its execution should look like:
```
eshell $ script
1
2
Done
eshell $
```
With the following requirements:
* the stdout of the bash process has to be "streamed" in the eshell buffer.
* it must be possible to `C-c` the script
Any idea on how to do that?
# Answer
You can copy the following Elisp code to your init files.
It contains a modified version of function `eshell-source-file`. Essentially I changed `(insert-file-contents file)` to `(insert string)`. Furthermore I needed a minor modification of `'eshell-command-name`.
It also contains the function `define-eshell-script` defining an Eshell command with a doc string and an Eshell script given by a string. The script takes care of the formalities for the script required by Eshell internals (e.g., correctly registering in the list variable `eshell-complex-commands`). Those formalities make the newly defined command interruptible.
```
(require 'cl-lib) ;; for macro `cl-pushnew' (not autoloaded ?!)
(require 'esh-cmd) ;; for variable `eshell-complex-commands'
(defun eshell-source-string (string &optional args subcommand-p)
"Execute a series of Eshell commands in STRING, passing ARGS.
Comments begin with `#'."
(interactive "sString to be evaluated as eshell script: ")
(let ((orig (point))
(here (point-max))
(inhibit-point-motion-hooks t))
(goto-char (point-max))
(with-silent-modifications
;; FIXME: Why not use a temporary buffer and avoid this
;; "insert&delete" business? --Stef
(insert string)
(goto-char (point-max))
(throw 'eshell-replace-command
(prog1
(list 'let
(list (list 'eshell-command-name (list 'quote "source-string"))
(list 'eshell-command-arguments
(list 'quote args)))
(let ((cmd (eshell-parse-command (cons here (point)))))
(if subcommand-p
(setq cmd (list 'eshell-as-subcommand cmd)))
cmd))
(delete-region here (point))
(goto-char orig))))))
(defun define-eshell-script (cmd doc string)
"Define CMD as eshell script STRING with documentation DOC.
CMD can be a string or a symbol."
(let ((fun (intern (concat "eshell/" cmd))))
(fset fun
`(lambda (&rest args)
,doc
(eshell-source-string ,string args)))
(cl-pushnew cmd (default-value 'eshell-complex-commands) :test #'equal)
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (derived-mode-p 'eshell-mode)
(cl-pushnew cmd eshell-complex-commands :test #'equal))))
(put fun 'eshell-no-numeric-conversions t)))
```
If the above functions are available you can define your actual script with the help of `define-eshell-script` as follows.
```
(define-eshell-script "script" "The doc-string: Output 1, sleep, and output 2."
"bash -c \"echo 1; sleep 3; echo 2;\"
echo DONE")
```
The usage example in Eshell looks like you want it:
```
/Path/to/current/dir $ script
1
2
DONE
/Path/to/current/dir $
```
> 1 votes
# Answer
I am having a blast using eshell on MS Windows, even forgetting sometimes I am not on GNU/Linux, and I think I have two nice examples that some of you can relate to.
For console applications (your case):
```
(defun eshell/vbox-startvm-headless (name)
"VBoxManage.exe startvm <vmname> --type headless"
(let* ((cmdlist (list (shell-quote-argument (vboxmgr-path)) "startvm" name "--type" "headless")))
(message (format "%S" cmdlist))
(throw 'eshell-replace-command (eshell-parse-command (car cmdlist) (cdr cmdlist)))))
(add-to-list 'eshell-complex-commands "vbox-startvm-headless")
```
For GUI applications:
```
(defun eshell/virtualbox (&optional args)
"VirtualBox.exe [args...]"
(start-process "virtualbox" nil (virtualbox-path)))
```
The snippets above are from my `init.el` and they rely on `vboxmgr-path` and `virtualbox-path` to point to `VBoxManage.exe` and `VirtualBox.exe`, respectively.
> 0 votes
---
Tags: eshell
---
|
thread-38730
|
https://emacs.stackexchange.com/questions/38730
|
How do I configure helm-git-grep candidates limit?
|
2018-02-09T21:16:00.290
|
# Question
Title: How do I configure helm-git-grep candidates limit?
I have this in my `.emacs` file but it still shows that the limit is 300 Candidates.
```
(require 'helm-git-grep) ;; Not necessary if installed by package.el
(global-set-key (kbd "C-c g") 'helm-git-grep)
(setq helm-candidate-number-limit 200)
```
# Answer
> 0 votes
try customizing the variable `helm-git-grep-candidate-number-limit`. I used `M-x customize-variable` to do it interactively.
---
Tags: helm, helm-grep
---
|
thread-50488
|
https://emacs.stackexchange.com/questions/50488
|
Adding header to a org-mode tangled file
|
2019-05-13T15:48:41.650
|
# Question
Title: Adding header to a org-mode tangled file
I am generating source code files from an org-mode file using org-babel-tangle.
How do I add headers to the files e.g. for python
> \# This is a generated file do not edit
for emacs lisp similar plus a header for lexical binding.
These would be different headers to a file I created directly in emacs so I think autoinsert.el won't have the flexibility.
# Answer
> 2 votes
You could use something this:
```
(defun add-tangle-headers ()
(message "running in %s" (buffer-file-name))
(cond
((f-ext? (buffer-file-name) "py")
(goto-char (point-min))
(insert "# This is a generated file do not edit\n"))
((f-ext? (buffer-file-name) "el")
(goto-char (point-min))
(insert ";;; -*- lexical-binding: t -*-\n"))
(t
nil))
(save-buffer))
(add-hook 'org-babel-post-tangle-hook 'add-tangle-headers)
```
The idea is to insert the desired line depending on the kind of src file you are tangling.
I would have thought you could use a :prologue header arg, but this seems to be only for execution.
Alternatively, you might try noweb:
First, name some source blocks like this with the header you want in each one.
```
#+name: elisp-header
#+BEGIN_SRC emacs-lisp
;;; -*- lexical-binding: t -*-
#+END_SRC
#+name: python-header
#+BEGIN_SRC python
# This is a generated file do not edit
#+END_SRC
```
Then, add a noweb yes header arg, and the target in the blocks where you want them.
```
#+BEGIN_SRC emacs-lisp :tangle test.el :noweb yes
<<elisp-header>>
(message "ok")
#+END_SRC
#+BEGIN_SRC python :tangle test.py :noweb yes
<<python-header>>
print('ok')
#+END_SRC
```
These will tangle as you want.
# Answer
> -2 votes
```
#+BEGIN_SRC python
# This is a generated file do not edit
#+END_SRC
```
or for lexical binding in an elisp file
```
#+BEGIN_SRC emacs-lisp
;;; -*- lexical-binding: t -*-
#+END_SRC
```
You will of course want to make sure that's the very first `BEGIN_SRC` block in the file.
---
Tags: org-babel, tangle
---
|
thread-55726
|
https://emacs.stackexchange.com/questions/55726
|
Using C-h inside the box to delete character [company-mode]
|
2020-02-23T16:39:07.737
|
# Question
Title: Using C-h inside the box to delete character [company-mode]
I am using `company-mode` for word suggestions.
In `company-mode`, when I use `C-h` instead of deleting a character it says `No documentation available`.
---
I have added following lines to `.emacs`, which did not solve it.
```
(add-hook 'after-init-hook 'global-company-mode)
(with-eval-after-load "company"
(define-key company-search-map (kbd "C-h") #'company-search-delete-char))
```
# Answer
> 1 votes
Your setting looks valid, but since it is not doing, what you expect, you probably changed the wrong keymap.
exchange your `(define-key...` line by:
```
(define-key company-active-map (kbd "C-h") nil)
```
if you have set up your emacs to normaly delete chars with `C-h`
or
```
(define-key company-active-map (kbd "C-h") #'backward-delete-char)
```
otherwise.
Note: you can still access the help feature of company by using `F1` key.
---
Tags: company-mode
---
|
thread-55723
|
https://emacs.stackexchange.com/questions/55723
|
How to hook to functions?
|
2020-02-23T14:46:42.950
|
# Question
Title: How to hook to functions?
I want to center my screen after calling `flyspell-goto-next-error`. If you have a "direct" solution please let me know, but I encounter the following issue more often:
I'm looking to hook to the invocation of a function, so that I can call my own function afterwards (or before). In this case, I would hook to `flyspell-goto-next-error` and execute the command to center my screen. Is this possible?
One possible solution is to write my own function that first calls `flyspell-goto-next-error`, and then performs the screen centering. However, that would require rebinding all instances where this function is called, which is not ideal.
# Answer
> 2 votes
Since not all emacs commands and features bring there own hook, you need to extend the given function.
One way is to use `advice-add` which can do all sorts of manipulation. (i.e filter function arguments, modify return values, call functions befor, after, etc). It is easy to apply and universal usable throughout emacs. For detailed information please look at the doc string of `add-function`
It can be used that way:
```
(defun my-flyspell-goto-next-error-do-stuff (&rest r)
(do some funky stuff))
(add-function 'flyspell-goto-next-error :after #'my-flyspell-goto-next-error-do-stuff)
```
---
Another way would be to copy the original function code, manipulate it as needed and define it as the new function.
There is one problem with that approach, if the original function changes for some reason (bugfix, improved features), you keep working with the old version and nothing gives you a hint about the change. It might happen that this introduces some weird behaviour on your config. There exist packages like el-patch, which address this issue.
---
I thought: both methods need to be installed **after** the original functionality has been loaded. `with-eval-after-load` can help you there.
But user Phils said otherwise in its comment below (forward advice).
I did not (yet) test this. In any case: you should be on the safe side if you install the advice after loading.
---
Tags: hooks, flyspell
---
|
thread-55673
|
https://emacs.stackexchange.com/questions/55673
|
Org Mode use radio target for Chinese Texts
|
2020-02-21T09:50:23.610
|
# Question
Title: Org Mode use radio target for Chinese Texts
Radio targets in `org-mode` work by recognizing spacing between words. This makes the function redundant in when work wth Chinese and Japanese texts.
I discovered an interesting function in `ol.el` with a comment that says:
> Some languages, e.g., Chinese, do not use spaces to separate words. Also allow to surround radio targets with line-breakable characters.
```
(defun org-update-radio-target-regexp ()
"Find all radio targets in this file and update the regular expression.
Also refresh fontification if needed."
(interactive)
(let ((old-regexp org-target-link-regexp)
;; Some languages, e.g., Chinese, do not use spaces to
;; separate words. Also allow to surround radio targets with
;; line-breakable characters.
(before-re "\\(?:^\\|[^[:alnum:]]\\|\\c|\\)\\(")
(after-re "\\)\\(?:$\\|[^[:alnum:]]\\|\\c|\\)")
(targets
(org-with-wide-buffer
(goto-char (point-min))
(let (rtn)
(while (re-search-forward org-radio-target-regexp nil t)
;; Make sure point is really within the object.
(backward-char)
(let ((obj (org-element-context)))
(when (eq (org-element-type obj) 'radio-target)
(cl-pushnew (org-element-property :value obj) rtn
:test #'equal))))
rtn))))
(setq org-target-link-regexp
(and targets
(concat before-re
(mapconcat
(lambda (x)
(replace-regexp-in-string
" +" "\\s-+" (regexp-quote x) t t))
targets
"\\|")
after-re)))
(unless (equal old-regexp org-target-link-regexp)
;; Clean-up cache.
(let ((regexp (cond ((not old-regexp) org-target-link-regexp)
((not org-target-link-regexp) old-regexp)
(t
(concat before-re
(mapconcat
(lambda (re)
(substring re (length before-re)
(- (length after-re))))
(list old-regexp org-target-link-regexp)
"\\|")
after-re)))))
(when (featurep 'org-element)
(org-with-point-at 1
(while (re-search-forward regexp nil t)
(org-element-cache-refresh (match-beginning 1))))))
;; Re fontify buffer.
(when (memq 'radio org-highlight-links)
(org-restart-font-lock)))))
```
Running the function on the sample text below shows that only 1 and 2 are linked.
```
<<<劉邵>>>
1. 劉邵
2. 其邯鄲淳事在〈王粲傳〉,蘇林事在〈劉邵〉、〈高堂隆傳〉,樂詳事在〈杜畿傳〉。
3. 六月,權令將軍賀齊督糜芳、劉邵等襲蘄春,邵等生虜宗。
```
How do we make radio targets work without the spacing requirement?
# Answer
You could insert the UTF-8 character Zero Width Space to *invisible* separate your targets from the rest of the text.
You can insert that character by using `C-x 8 <ret>` `zero width space`.
This seems the easiest option, but with a tradeof. Because, when introducing a new radio target, you need to do a search-replace operation (to insert those invisible spaces into the text).
> 1 votes
---
Tags: org-mode, org-link
---
|
thread-55721
|
https://emacs.stackexchange.com/questions/55721
|
Quick navigation (with autocompletion) to an org heading
|
2020-02-23T13:47:47.273
|
# Question
Title: Quick navigation (with autocompletion) to an org heading
I have a contacts.org file whose structure looks like this :
```
* Contacts
** John DOE
** Alicia PING
** Bob DELTA
```
I'd like to be able to :
* quickly set up a link to, for instance, Alicia PING, from a different org file;
* quickly navigate to Bob DELTA from anywhere in Emacs.
* in both cases, be able to do this with autocompletion (because I might not remember John's surname...)
How could I achieve this?
# Answer
I could not find a way to do this in the manual, so I programmed a solution in 3 steps:
1. Retrieve the headings of the org file `contacts.org`. Although a very simple requirement, no function seems to do that in the manual, so here's mine:
```
(defun get-headers (org-filename)
"Get the headers of the org-file located at <org-filename>"
(with-current-buffer (find-file-noselect org-filename)
(let ((parsetree (org-element-parse-buffer 'headline)))
(org-element-map parsetree 'headline
(lambda (hl) (org-element-property :title hl))))))
```
which you would call, for instance, with `(get-headers "~/contacts.org")` :
`("Contact" "John DOE" "Alicia PING" "Bob DELTA")`.
2. Building from that, here's how to create a quick link to a contact, from an org-file:
```
(defun link-to-contact ()
"Quickly insert a link to one of the contacts in ~/contacts.org, with autocompletion."
(interactive)
(let ((contact
(completing-read "Link to contact: " (cdr (get-headers "~/contacts.org")))))
(insert (format "[[file:~/contacts.org::*%s][%s]]" contact contact))))
```
3. And here's how to quickly go there:
```
(defun goto-contact ()
"Quickly navigate to a contact in ~/contacs.org"
(interactive)
(let ((contact
(completing-read "Go to contact: " (cdr (get-headers "~/contacts.org")))))
(pop-to-buffer (find-file-noselect "~/contacts.org"))
(beginning-of-buffer)
(search-forward (format "** %s" contact))))
```
> 1 votes
---
Tags: org-mode
---
|
thread-55736
|
https://emacs.stackexchange.com/questions/55736
|
buffer-substring fails in linux in a non-X terminal when I am in anything other than text mode
|
2020-02-24T00:10:44.287
|
# Question
Title: buffer-substring fails in linux in a non-X terminal when I am in anything other than text mode
NOTE: I was careless in evaluating this problem, and the data I posted here is not correct and does not reflect the actual issue that I am facing.
Since there are already answers to this question, I cannot delete it.
Please see the following question for the updated and corrected version of my query:
query-replace{-regexp} fails in linux in a non-X terminal when I am in anything other than text mode
Please ignore the rest of this. Thank you.
I am running emacs 26.1 under linux. It has been working fine for over a year. Recently, I upgraded a lot of packages on my machine, but I did not upgrade nor alter emacs in any way. Now, `buffer-substring` is failing when I run it in a non-X terminal with the `-nw` emacs command-line flag when not in `text-mode`. This failure never used to occur before my system upgrades. And it turns out that `buffer-substring` still works fine in all cases when I start emacs in an X window.
For example, suppose I have the following data in a file called `test.txt` ...
```
AAAA
BBBB
CCCC
DDDD
```
If I run `emacs -nw test.txt`, then `(buffer-substring 0 1)` works. However, if I run `(elisp-mode)` and then do a `(buffer-substring 0 1)`, I get this error: `args-out-of-range #<buffer test.txt> 0 1`
This occurs no matter what arguments I pass to `buffer-substring`. However, if I leave off `-nw` and do all the same things in an X-Window instance of emacs, `buffer-substring` always works.
In other words, with `emacs test.txt` (*i.e.*, no `-nw` flag), I never get this problem with `buffer-substring`, no matter what mode I am running in.
This is not only specific to `elisp-mode`. The error with `buffer-substring` in a non-X terminal buffer also occurs for `sh-mode` and some other modes.
Does anyone know what could be causing this error and what I have to do to fix it?
Thank you in advance.
UPDATE:
I set `debug-on-error` and re-ran `(buffer substring 0 1)` in one of the cases that fails. Here is what I got:
```
Debugger entered--Lisp error: (args-out-of-range #<buffer test.txt> 0 1)
buffer-substring(0 1)
eval((buffer-substring 0 1) nil)
eval-expression((buffer-substring 0 1) nil nil 127)
funcall-interactively(eval-expression (buffer-substring 0 1) nil nil 127)
call-interactively(eval-expression nil nil)
command-execute(eval-expression)
```
FURTHER UPDATE:
This error does not occur when I am running from my system console (with no X services running at all). The errors I saw did occur in `xterm` and `urxvt` windows under my X desktop manager, even when I have explicitly unset `DISPLAY`.
It seems like there is something about running within an X desktop manager which is confusing emacs with regard to buffer attributes when running with `-nw`, even with `DISPLAY` unset.
# Answer
Buffer positions are 1-based, not 0-based.
You asked for buffer position 0:
```
Debugger entered--Lisp error: (args-out-of-range #<buffer test.txt> 0 1)
buffer-substring(0 1)
```
You say:
> If I run `emacs -nw test.txt`, then `(buffer-substring 0 1)` works.
Are you sure? I don't see that.
> 1 votes
---
Tags: buffers
---
|
thread-37169
|
https://emacs.stackexchange.com/questions/37169
|
In Magit: fatal: Could not read from remote repository
|
2017-11-29T10:20:57.777
|
# Question
Title: In Magit: fatal: Could not read from remote repository
For some repositories at work I get the following message when I try to push my commits:
```
GitError! Could not read from remote repository. [Type `$' for details]
```
The details read:
```
128 C:/Program Files/Git/mingw64/libexec/git-core/git.exe … "push" "-v" "origin" "master:refs/heads/master"
Pushing to ssh://git@XXX.git
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
```
Any idea what the problem could be? Running the above git command from a git-bash (minus those tripple-dots) also works. In fact, that's my workaround. Compose the commit with magit and just type git push in a git-bash. Pushing to github.com repository on the same machine works from magit.
# Answer
The problem was that emacs was seeing a different $HOME variable than git-bash and could therefore not find the ssh-keys. Thanks to @wvxvw for pointing me in the right direction. After creating a symlink everything works now.
> 5 votes
# Answer
I had the same error message until moments ago. I had to install the package `ssh-agency`. A solution that is also documented in the link provided by @npostavs
In spacemacs you do that by adding it to `dotspacemacs-additional-packages`.
> 2 votes
# Answer
Working with remotes used to be fine until Emacs was updated to 26.3 from 26.2 on my Fedora 30 computer. The solution is to set the variable `SSH_AUTH_SOCK` for Emacs:
1. Check the value of this variable on your system
```
$ echo $SSH_AUTH_SOCK
```
2. Set it from Emacs with value from above. For me it's "/run/user/1000/keyring/ssh".
```
M-x setenv SSH_AUTH_SOCK RET /run/user/1000/keyring/ssh
```
Source: https://github.com/syl20bnr/spacemacs/issues/10969
> 1 votes
# Answer
I got the same error. For me, the `git` cli was working fine from the terminal but failed to work inside Emacs. I opened an interactive shell and ran the same command and the error was much clear:
```
sibi { ~/github/dotfiles }-> git fetch origin
Bad owner or permissions on /home/sibi/.ssh/config
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
```
Fixing it was much simpler after that:
```
$ chmod 600 ~/.ssh/config
```
And after that all the magit operations start working as usual.
> 0 votes
---
Tags: magit
---
|
thread-55730
|
https://emacs.stackexchange.com/questions/55730
|
Disable lsp-mode symbol highlighting?
|
2020-02-23T20:15:28.897
|
# Question
Title: Disable lsp-mode symbol highlighting?
When using lsp server, symbol highlighting obscures the highlighting done by region selection. I can toggle this behavior per-buffer with `lsp-toggle-symbol-highlight`, but cannot permanently disable it for all buffers. Is there a workaround to fix the current lack of a configuration setting?
# Answer
> 2 votes
Customize the `lsp-enable-symbol-highlighting` option:
```
(setq lsp-enable-symbol-highlighting nil)
```
or via Easy Customization Interface:
```
M-x customize-variable <RET> lsp-enable-symbol-highlighting <RET>
```
> Highlight references of the symbol at point.
---
Tags: highlighting, lsp-mode
---
|
thread-55734
|
https://emacs.stackexchange.com/questions/55734
|
Load a list from a file (in a script)
|
2020-02-23T22:57:20.213
|
# Question
Title: Load a list from a file (in a script)
I have a script containing this code:
```
(let
((JOURNALS
'(
("abhandlungen aus dem mathematischen seminar der hamburgischen universitet" .
"Abh. Math. Sem. Univ. Hamburg") ;; inSPIRE
("acm transactions on mathematical software" .
"ACM Trans. Math. Software") ;; inSPIRE
("acs applied materials and interfaces" .
"ACS Appl. Mater. Interfaces") ;; NLM Catalog
)))
...
)
```
and I need move the list of cons cells in a separate file. E.g.:
```
(let
((JOURNALS
'( (read-file "list-of-cons-cells.el")
)))
...
)
```
Where the `list-of-cons-cells.el` file contents is:
```
("abhandlungen aus dem mathematischen seminar der hamburgischen universitet" .
"Abh. Math. Sem. Univ. Hamburg") ;; inSPIRE
("acm transactions on mathematical software" .
"ACM Trans. Math. Software") ;; inSPIRE
("acs applied materials and interfaces" .
"ACS Appl. Mater. Interfaces") ;; NLM Catalog
```
What's the right way to load this file when I run my script?
**Edit.** This is a MWE of mi original idea (this is not the real function...):
```
(defun myfunction-orig ()
(interactive)
(let ((JOURNALS '(
("abhandlungen aus dem mathematischen seminar der hamburgischen universitet" .
"Abh. Math. Sem. Univ. Hamburg") ;; inSPIRE
("acm transactions on mathematical software" .
"ACM Trans. Math. Software") ;; inSPIRE
("acs applied materials and interfaces" .
"ACS Appl. Mater. Interfaces") ;; NLM Catalog
)
))
;; Debug:
(princ JOURNALS)
(sit-for 2)
(while JOURNALS
(read-string (car (car JOURNALS)))
(setq JOURNALS (cdr JOURNALS)))))
```
I tried to modified it on phils' suggestion:
```
(defun myfunction ()
(interactive)
(with-temp-buffer
(insert-file-contents "./list-of-cons-cells.el")
(let (JOURNALS form)
(while (setq form (ignore-errors (read (current-buffer))))
(push form JOURNALS))
(nreverse JOURNALS)
;; Debug:
(princ JOURNALS)
(sit-for 2)
(while JOURNALS
(read-string (car (car JOURNALS)))
(setq JOURNALS (cdr JOURNALS)))
)))
```
but it doesn't work.
**Solution.** This is the solution based on the edited phils' answer:
```
(defun myfunction ()
(interactive)
(let ((JOURNALS (with-temp-buffer
(insert-file-contents "./list-of-cons-cells.el")
(let (list form)
(while (setq form (ignore-errors
(read (current-buffer))))
(push form list))
(nreverse list)))))
;; Debug
(princ JOURNALS)
(sit-for 5)
(while JOURNALS
(read-string (car (car JOURNALS)))
(setq JOURNALS (cdr JOURNALS)))))
```
# Answer
Something along these lines?
```
(let ((JOURNALS (with-temp-buffer
(insert-file-contents FILENAME)
(let (list form)
(while (setq form (ignore-errors
(read (current-buffer))))
(push form list))
(nreverse list)))))
...)
```
> 1 votes
# Answer
You can throw the burden of iterating onto lisp's `read`. To do that you just need to realize that the list in journals is a lisp list with the beginning and ending parentheses missing. So fill-in the missing and read.
\[Ive renamed your `list-of-cons-cells.el` to `journals.txt` since its a lisp data-structure but not lisp code\]
```
(with-temp-buffer
(insert "(")
(insert-file-contents "journals.txt")
(goto-char (point-max))
(insert ")")
(goto-char (point-min))
(read (current-buffer)))
```
> 1 votes
---
Tags: files, load
---
|
thread-55742
|
https://emacs.stackexchange.com/questions/55742
|
Autocomplete suggestions after dot in python using company-mode
|
2020-02-24T09:03:32.060
|
# Question
Title: Autocomplete suggestions after dot in python using company-mode
Jedi has support for auto-completion after dot
`(setq jedi:complete-on-dot t)`
=\> Main goal is to Finding what methods a Python object has
---
**\[Q\]** Does `company-mode` has the same support (`complete-on-dot`)? Basically after the dot I want it to detect only the object's functions or variables for completion suggestions.
# Answer
Edit: not being a python programmer I hadn't actually looked up Jedi. Jedi is an emacs extension. Why not just use that? It IS integrated with company mode.
See here: Python Programming in Emacs
```
(defun company-jedi-setup ()
(add-to-list 'company-backends 'company-jedi))
(add-hook 'python-mode-hook 'company-jedi-setup)
```
and
```
(setq jedi:setup-keys t)
(setq jedi:complete-on-dot t)
(add-hook 'python-mode-hook 'jedi:setup)
```
===== below left for reference
You can bind "." to company-complete as described here
Something like
```
(defun dot-pressed()
(interactive)
(insert ".")
(call-interactively 'company-complete))
(define-key python-mode-map (kbd ".") #'dot-pressed)
```
but that would be pretty intrusive. I force completion with C-tab:-
```
(use-package
company
:diminish company-mode
:config
(use-package
company-box
:disabled
:diminish company-box-mode
:hook (company-mode . company-box-mode))
(require 'company-ispell)
(global-company-mode)
:bind ("C-<tab>" . company-complete))
```
That said I strongly recommend you have a look as lsp, this will give you live language-specific completion based on a background language server which parses your code and libraries and gives proper context-specific completion and navigation. It comes with its own "company-lsp" completion candidate for company.
Python and it's requirements are documented on that page linked above,
> 1 votes
---
Tags: python, company-mode
---
|
thread-55738
|
https://emacs.stackexchange.com/questions/55738
|
Why is cl-loop autoloaded on byte-compilation?
|
2020-02-24T05:45:59.030
|
# Question
Title: Why is cl-loop autoloaded on byte-compilation?
This question is motivated by a question about the "void function" error on `cl-loop` in the init file.
The following test shows that `(require 'cl-lib)` is not needed for byte-compilation:
* Assume you have a file `~/tmp/test.el` with the following content:
```
(defun test ()
(cl-loop for i from 1 to 2 do
(message "Looping %i." i)))
```
* Start Emacs 26.3 with `emacs -Q`.
* Run `M-:` `(byte-compile-file "~/tmp/test.el")`. Byte compilation works without errors.
* Run `M-x` `load-file` `RET` `~/tmp/test.el` `RET`.
The file is loaded and gives the message
```
Looping 1.
Looping 2.
```
But `cl-macs` is not loaded by default as the "void function" error on evaluating `cl-loop` shows.
The `cl` info manual says that `cl-lib.el` loads `cl-loaddefs.el`. This is done by a `(load "cl-loaddefs" 'noerror 'quiet)` in the code.
But in the test code above there is no `(require 'cl-lib)`. How gets `cl-macs` loaded at byte-compilation?
I already noted the `(register-definition-prefixes "cl-macs" '("cl-"))` in `loaddefs.el`.
The help string on `register-definition-prefixes` just says: `Register that FILE uses PREFIXES.`, which is as much as nothing.
The info manual does also not contain any information about `register-definition-prefixes`.
Might it be that that command causes the autoloading at byte-compilation?
A look into `register-definition-prefixes` shows that it registers the prefix in the variable `definition-prefixes`.
The doc-string of `definition-prefixes` says:
```
Hash table mapping prefixes to the files in which they're used.
This can be used to automatically fetch not-yet-loaded definitions.
More specifically, if there is a value of the form (FILES...) for
a string PREFIX it means that the FILES define variables or functions
with names that start with PREFIX.
Note that it does not imply that all definitions starting with PREFIX can
be found in those files. E.g. if prefix is "gnus-article-" there might
still be definitions of the form "gnus-article-toto-titi" in other files,
which would presumably appear in this table under another prefix such as
"gnus-" or "gnus-article-toto-".
```
Hm, "This can be used to automatically fetch not-yet-loaded definitions." seems to be a strong indication that `register-definition-prefixes` could play a role in the autoloading of `cl-macs` on byte-compiling code that contains `cl-loop`. But, the doc string does not say anything definite.
# Answer
`byte-compile-file` comes from bytecomp.el which `(require 'cl-lib)`, thus `cl-lib` is always already loaded before any byte compilation.
> The info manual does also not contain any information about register-definition-prefixes. Might it be that that command causes the autoloading at byte-compilation?
According to my understanding, that's a feature introduced in Emacs 26.3, you should be able to find more info in the NEWS file, that is, `loaddefs.el` contains
```
(register-definition-prefixes "cl-lib" '("cl-"))
```
then when you type `C-h f cl-` and `TAB` for completion, Emacs will **automatically** load `cl-lib.el`. I think it is too aggressive for me, thus I disable it:
```
(setq help-enable-completion-auto-load nil)
```
> 3 votes
# Answer
This is a bug (will be fixed in 27.1); https://debbugs.gnu.org/30635
> 3 votes
---
Tags: autoload, cl-lib
---
|
thread-55748
|
https://emacs.stackexchange.com/questions/55748
|
Identities between let/lambda/defun expressions and simplifying nested progn
|
2020-02-24T15:59:49.970
|
# Question
Title: Identities between let/lambda/defun expressions and simplifying nested progn
I learned that a `lambda` and `let` works as if they already include a `progn` in their definition. That is `(let ((x 1) (y 2) (z 3)) A B C)` works as if it had a `progn` after binding the variables: `(let ((x 1) (y 2) (z 3)) (<progn> A B C))`. `lambda` seems to have an "inherent" `progn` as well, such that `(funcall (lambda (x y z) A B C) 1 2 3)` is equivalent to `(let ((x 1) (y 2) (z 3)) A B C)`.
My question is:
a) What are the identifies between `lambda`, `let` and `progn`? (i.e. how would you implement `lambda` and `progn` just using `let`?);
b) Is `(progn (progn (A) (B) (C)))` always equivalent to `(progn ((A) (B) (C)))`?
# Answer
> 2 votes
> `lambda` seems to have an "inherent" `progn` as well, such that `(funcall (lambda (x y z) A B C) 1 2 3)` is equivalent to `(let ((x 1) (y 2) (z 3)) A B C)`.
"Equivalent" is a strong word. Calling a `lambda` with a set of arguments may have a similar effect to evaluating the `lambda`'s body with the appropriate `let` bindings in place, but their corresponding semantics are quite different.
> a) What are the identifies between `lambda`, `let` and `progn`?
Are you asking how they relate/compare to one another?
* `progn` is pure sequential evaluation of Lisp forms
* `let` is the same but with local variable binding at the start and unbinding at the end
* `lambda` evaluates to an anonymous function under dynamic binding, and a closure under `lexical-binding`
> how would you implement `lambda` and `progn` just using `let`?
That depends on what you mean by "implement using `let`". You can't use `let` alone to define a function, macro, or special form that will do the same thing as either `lambda` or `progn`, but some rewriting is possible in the case of `progn`:
```
;; Expressions of this form:
(progn BODY...)
;; can generally be written as:
(let () BODY...)
```
No such rewrite is possible for anonymous functions and closures in general, because their evaluation semantics and byte-compilation are quite different to those of `let`.
```
;; For example, this expression:
(lambda (x) (1+ x))
;; is not, under dynamic binding, the same as:
(list 'lambda '(x) '(1+ x))
;; and not, under lexical binding, the same as:
(list 'closure '(t) '(x) '(+ x y))
```
> b) Is `(progn (progn (A) (B) (C)))` always equivalent to `(progn ((A) (B) (C)))`?
No, those two forms are never equivalent.
`(progn (progn (A) (B) (C)))` is valid Elisp which evaluates `(A)`, `(B)`, and `(C)` in that order, and returns the result of evaluating `(C)`.
`(progn ((A) (B) (C)))` is valid if and only if `(A)` is a valid `(lambda ...)` expression, as the first element of an evaluated list must already be (not evaluate to) a valid function object. In that case, `(B)` and `(C)` are evaluated and passed as arguments to the anonymous function/closure `(A)`, whose result is then returned by `progn`.
(I have the faint impression that expressions of the form `((lambda ...))` are meant to eventually be outlawed in Elisp, but I'm not sure.)
**Update from Comments**
> In asking b), I meant to ask about the semantics and evaluation of the "implicit" `progn` in `let`/`lambda` and an explicit `progn` in their body, i.e. how does `(let () (progn BODY...))` work?
`(let () (progn BODY...))` is effectively the same as `(progn (progn BODY...))`, which is effectively the same as `(progn BODY...)`, i.e. adding an explicit `progn` where there is already an implicit one is practically redundant/idempotent.
The special form `let` is actually implemented in terms of `progn`; see `src/eval.c`:
```
DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
doc: /* Bind variables according to VARLIST then eval BODY.
The value of the last form in BODY is returned.
Each element of VARLIST is a symbol (which is bound to nil)
or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
All the VALUEFORMs are evalled before any symbols are bound.
usage: (let VARLIST BODY...) */)
(Lisp_Object args)
{
/* Bind local variables according to first argument. */
Lisp_Object varlist = XCAR (args);
ptrdiff_t count = SPECPDL_INDEX ();
/* ...magic happens here... */
/* Pass remaining arguments to 'progn'. */
Lisp_Object elt = Fprogn (XCDR (args));
/* Unbind local variables; return result of 'progn'. */
return SAFE_FREE_UNBIND_TO (count, elt);
}
```
Note that idiomatic Elisp avoids redundant nesting of `progn` where possible.
---
Tags: let-binding, defun
---
|
thread-55745
|
https://emacs.stackexchange.com/questions/55745
|
Delete multiple emails (articles)
|
2020-02-24T12:05:42.183
|
# Question
Title: Delete multiple emails (articles)
In Gnus, in summary buffer, how would one delete multiple emails (not retire, but actually delete). Deleting singe email (article) is `B``DEL` (or similar), but this doesn't seem to work on any kind of marking I was able to come up with.
# Answer
Mark the articles to be deleted with `#`.
> 3 votes
---
Tags: gnus, email
---
|
thread-55752
|
https://emacs.stackexchange.com/questions/55752
|
Change line number format with line-number-mode
|
2020-02-24T20:07:41.360
|
# Question
Title: Change line number format with line-number-mode
With `linum-mode`, you could change how the line numbers appears by customizing `linum-format`.
`line-number-mode` appears to have replaced linum-mode, and indeed it is better (for one thing, it correctly right aligns the line numbers). However, I can't find any formatting options.
What I would like to do is
* Remove the empty space before the line number
* Replace the space after the line number with .
(Note that I use terminal emacs)
I used to do this by setting `linum-format` to `%d⎢`.
If there aren't any formatting options, can I at least remove the left vertical column and change the character used, or if that's not possible, set a face for the right one?
# Answer
> 5 votes
In a closely related question How to change line-number gutter width using display-line-numbers mode? , I wrote up an answer essentially stating that there is no user option to configure the left/right padding for the built-in line numbers. This is written into the C internals of Emacs in the file `xdisp.c`. The *left* padding of the built-in line numbers is controlled by the line of code that reads `pint2str (lnum_buf, it->lnum_width + 1, lnum_to_display);` (i.e., the `+ 1` creates the left space); and, the *right* padding is controlled by the line of code that reads `strcat (lnum_buf, " ");`
I felt that the idea of having a user option was worth pursuing and I raised this issue on the Emacs Devel mailing list, including, but not limited to some proof-concept screenshots. The screenshots that I generated appear to be exactly what the O.P. is proposing in the question of this current thread:
https://lists.gnu.org/archive/html/emacs-devel/2019-08/msg00418.html
The lead maintainer/developer (Eli Z.), who created the built-in line numbers of `xdisp.c`, opted not to pursue this idea for the reasons stated in the thread:
https://lists.gnu.org/archive/html/emacs-devel/2019-08/msg00426.html
---
Tags: terminal-emacs, line-numbers
---
|
thread-13721
|
https://emacs.stackexchange.com/questions/13721
|
How can I override initial-buffer-choice if I specify a filename at command line?
|
2015-07-04T23:52:20.020
|
# Question
Title: How can I override initial-buffer-choice if I specify a filename at command line?
In my `.emacs` file I have the following line in `custom-set-variables`:
```
'(initial-buffer-choice "~/Programming/C++/<some project I'm working on>")
```
This works great. However, I use emacs to edit lots of other files too. Before I inserted the above line in `custom-set-variables`, I could specify the file I intended to edit from the command line. For example, when I intended to edit a file called `text_file.txt`, I could type this command:
```
emacs text_file.txt
```
And emacs would startup with `text_file.txt` as the selected buffer. Now that I've specified `initial-buffer-choice`, regardless of what I say after `emacs`, emacs will always open the file specified in `custom-set-variables`, and *not* the file specified at command line. For example, the command
```
emacs text_file.txt
```
now opens `~/Programming/C++/<some project I'm working on>` instead of `text_file.txt`.
How can I over ride `initial-buffer-choice` so when I do specify which file to open, that file will open?
# Answer
> 1 votes
What happens after Emacs opens to your choice of `initial-buffer-choice`? If you then use `C-x b` do you see the file you specified on the command line as an available buffer to choose from? And is it perhaps even the default (try `M-n` to see if it gets pulled immediately to the minibuffer)?
If yes, then it sounds like Emacs is doing what you told it to:
1. Visit the file you gave it on the command line.
2. Show the initial buffer that you chose.
And it's not hard to use `C-x b`. If the file in question comes up as the default buffer to switch to, things are easier still.
If that is not what you see then this sounds like a bug to me. If you can repro the behavior starting from `emacs -Q` (with any other specific switches and settings specified as part of the recipe), then consider filing a bug report: `M-x report-emacs-bug`.
Note too that you can try setting `initial-buffer-choice` to a *function* that picks up a command-line file argument and uses that as the buffer to show.
# Answer
> 0 votes
Use a function for that checks if the current buffer has a filename.
```
(setq initial-buffer-choice
(lambda ()
(if (buffer-file-name)
(current-buffer) ;; leave as-is
(find-file "~/Programming/C++/<some project I'm working on>"))))
```
Fo a full example see this answer.
---
Tags: init-file, customize, start-up, command-line-arguments
---
|
thread-283
|
https://emacs.stackexchange.com/questions/283
|
Command that formats (prettifies) Elisp code
|
2014-09-25T22:16:49.260
|
# Question
Title: Command that formats (prettifies) Elisp code
Let's say I have a function that looks like the following (as is often the case when printing elisp output).
```
(defun my-example-function () (let ((a (do-something)) (b (do-something))) (setq someone me) (with-current-buffer b (do-that (or this (and that those))) (format "%s" a))))
```
**I would like a command that can turn that into something a human would write, such as the following.**
```
(defun my-example-function ()
(let ((a (do-something))
(b (do-something)))
(setq someone me)
(with-current-buffer b
(do-that (or this (and that those)))
(format "%s" a))))
```
**I understand that there's more than one way to format a piece of elisp code**, and different human beings do it differently. Furthermore, I understand it's somewhat subjective. But it should be fairly easy to come up with a set of rules that results in code that is at least decent.
I actually tought of doing this myself a while ago, but I figured it's better to ask before I reinvent the wheel.
*Note, I'm aware of the pp function, but it doesn't quite get there:*
```
(defun my-example-function nil
(let
((a
(do-something))
(b
(do-something)))
(setq someone me)
(with-current-buffer b
(do-that
(or this
(and that those)))
(format "%s" a))))
```
# Answer
> 16 votes
As others have suggested in comments, "formatting" can mean different things.
For *indentation* that is pretty conventional, try using `C-M-q` (command `indent-pp-sexp` in Lisp modes) with the cursor somewhere inside the top-level sexp that you want to re-indent (e.g. the `defun` sexp).
No, this is not "automatic" indentation, but it can become a habit to use it. ;-)
For things other than indentation you will need to either do it manually or roll your own "formatting" command(s) or find some existing such.
See also the Emacs manual, node Multi-line Indent and the Elisp manual, node `Mode-Specific Indent`.
# Answer
> 14 votes
Here's how lispy re-formatted it for me (by pressing `M` at either end of the expression):
```
(defun my-example-function ()
(let ((a (do-something))
(b (do-something)))
(setq someone me)
(with-current-buffer b (do-that (or this (and that those)))
(format "%s" a))))
```
To get from this to the formatting that you specified, press `qk C-m [`.
# Answer
> 11 votes
Listing *Elisp* formatting tools here for completeness:
* Elisp-Autofmt Emacs integration to run on-save.
Formats files following this style by default (available on **melpa**).
* lispy includes auto-formatting functionality (`lispy` on **melpa**)
* ElispFormat produces idiomatic elisp, but seems to have right-shift problems - going over the fill column width (`elisp-format` on **melpa**).
* Grind no Emacs integration (not on **melpa**).
* Semantic Refactor (`srefactor` on **melpa**)
* Emacs 29+ `pp-emacs-lisp-code` (built-in, an extended pretty printer intended for use with code).
---
Tags: elisp, formatting
---
|
thread-50931
|
https://emacs.stackexchange.com/questions/50931
|
Emacs wont reopen my files from recover session
|
2019-06-10T10:58:56.793
|
# Question
Title: Emacs wont reopen my files from recover session
I was working in emacs when had a power outage, so my computer was knocked offline. After I got the computer back up, I launched emacs and tried to restore the last session. Emacs then said: "No files can be recovered from this session now". All my files were saved, so all that needs to happen them opened from the .saves-pid-hostname~ file.
I'm not sure if this is even possible after researching the issues. I found this bug report about emacs session restores. It seemed to suggest that emacs didn't perceive the files as needing to be restored because all changes had been saved to them.
What I'm looking for is a way to have emacs open the files that are listed in the saves file. This should only apply to the normal file names and excludes the files that emacs makes in-between saves, like "#filename#".
Saves File:
```
/home/user/Documents/2019/document1.txt
/home/user/Documents/2019/#document1.txt#
/home/user/Documents/2019/document2.txt
/home/user/Documents/2019/#document2.txt#
/home/user/Documents/2019/document3.txt
/home/user/Documents/2019/#document3.txt#
/home/user/Documents/2019/document4.txt
/home/user/Documents/2019/#document4.txt#
```
How do I have emacs automatically open these files? I don't need my work in emacs to be persistence across restarts, so I think desktop save mode would be over kill for the situation.
# Answer
> 3 votes
If you call `M-x` `recover-session` `RET` you are offered a dired buffer with save files. Pressing `RET` on one of those files opens it in an Emacs file buffer.
You can use the following function to open all files from that buffer.
```
(defun find-files-in-buffer (&optional include-auto-save separator)
"Find files listed in current buffer.
Find auto save files only if INCLUDE-AUTO-SAVE is non-nil.
SEPARATOR is used as regexp to split file names.
It defaults to the newline character.
In interactive calls INCLUDE-AUTO-SAVE is the raw prefix-argument \\[universal-argument]."
(interactive "P")
(unless (stringp separator)
(setq separator "\n"))
(let ((file-list (split-string (buffer-string) separator t)))
(unless include-auto-save
(setq file-list (cl-remove-if
(lambda (file)
(auto-save-file-name-p (file-name-nondirectory file)))
file-list)))
(cl-loop for file in file-list
when (file-readable-p file)
do (find-file file))))
```
# Answer
> 1 votes
I have been using the following code (essentially, a modified version of `recover-session`) for decades:
```
(defun restart-session ()
"Using the auto-save-list file from a previous Emacs session,
this command will reload the files from that session and/or
recover that file if an auto-save file exists for it.
This command first displays a Dired buffer showing you the
previous sessions that you can restart.
To choose one, move point to the proper line and then type C-c C-c."
(interactive)
(let ((ls-lisp-support-shell-wildcards t))
(dired (concat auto-save-list-file-prefix "*")))
(goto-char (point-min))
(or (looking-at "Move to the session you want to restart,")
(let ((inhibit-read-only t))
(insert "Move to the session you want to restart,\n"
"then type C-c C-c to select it.\n\n"
"You can also delete some of these files;\n"
"type d on a line to mark that file for deletion.\n\n")))
(use-local-map (nconc (make-sparse-keymap) (current-local-map)))
(define-key (current-local-map) "\C-c\C-c" 'restart-session-finish))
(defun restart-session-finish ()
"Choose one saved session to restart.
This command is used in the special Dired buffer created by
\\[restart-session]."
(interactive)
;; Get the name of the session file to reload/recover from.
(let ((file (dired-get-filename))
files-to-recover
files-to-reload
(buffer (get-buffer-create " *restart-session*")))
(dired-do-flagged-delete t)
(unwind-protect
(save-excursion
;; Read in the auto-save-list file.
(set-buffer buffer)
(erase-buffer)
(insert-file-contents file)
;; Loop thru the text of that file
;; and get out the names of the files to reload/recover.
(while (not (eobp))
(let (thisfile autofile)
(if (eolp)
;; This is a pair of lines for a non-file-visiting buffer.
;; Get the auto-save file name and manufacture
;; a "visited file name" from that.
(progn
(forward-line 1)
(setq autofile
(buffer-substring-no-properties
(point)
(save-excursion
(end-of-line)
(point))))
(setq thisfile
(expand-file-name
(substring
(file-name-nondirectory autofile)
1 -1)
(file-name-directory autofile)))
(forward-line 1))
;; This pair of lines is a file-visiting
;; buffer. Use the visited file name.
(progn
(setq thisfile
(buffer-substring-no-properties
(point) (progn (end-of-line) (point))))
(forward-line 1)
(setq autofile
(buffer-substring-no-properties
(point) (progn (end-of-line) (point))))
(forward-line 1)))
;; Ignore a file if its auto-save file does not exist now.
(if (file-exists-p autofile)
(setq files-to-recover (cons thisfile files-to-recover))
(if (file-exists-p thisfile)
(setq files-to-reload (cons thisfile files-to-reload))))))
(setq files-to-recover (nreverse files-to-recover))
(setq files-to-reload (nreverse files-to-reload))
;; The file contains a pair of line for each auto-saved buffer.
;; The first line of the pair contains the visited file name
;; or is empty if the buffer was not visiting a file.
;; The second line is the auto-save file name.
(if files-to-recover
(map-y-or-n-p "Recover %s? "
(lambda (file)
(condition-case nil
(save-excursion (recover-file file))
(error
"Failed to recover `%s'" file)))
files-to-recover
'("file" "files" "recover")))
(if files-to-reload
(map-y-or-n-p "Reload %s? "
(lambda (file)
(condition-case nil
(save-excursion (find-file-noselect file))
(error
"Failed to find `%s'" file)))
files-to-reload
'("file" "files" "reload")))
(if (not (or files-to-recover files-to-reload))
(message
"No files could be found or recovered from this session."))
(kill-buffer buffer)
(list-buffers)))))
```
Note: `recover-session` only opens files for which the auto-save file is newer than the original file. It recovers unsaved files, essentially. This `restart-session` reopens all of the files in the atuo-save-list file (which is what was requested), in addition to offering to recover unsaved files.
---
Tags: auto-save
---
|
thread-55613
|
https://emacs.stackexchange.com/questions/55613
|
Standard ML Emacs "real time" compilation?
|
2020-02-18T15:16:01.570
|
# Question
Title: Standard ML Emacs "real time" compilation?
I'm interested in configuring my Emacs environment to perform real-time compilation of a Standard ML buffer, on the event corresponding to a ";" character being entered (at the end of a line), such that the result of the compilation shows in a second buffer in a parallel window. The online SML interpreter SOSML (https://sosml.org/editor) does something like this, with the compiler output going in another text field on the same page. It is reactive this same way, using the ";" character.
I have been able to figure out how to compile SML in Emacs via a shell in a separate buffer and window (M-x run-sml), but only by explicitly entering commands when I'd like to compile an entire file. I do have SML Mode installed in Emacs and the text analysis is working well. But I'm struggling to find documentation about how Emacs might be able to watch a buffer and react in realtime to a character (such as ";") to trigger compilation of that same buffer in another buffer and window.
I appreciate any suggestions as to the appropriate convention and tool here.
# Answer
> 1 votes
A straightforward way to catch this `;` is with:
```
(add-hook 'post-self-insert-hook #'sml-recompile-after-semicolon nil t)
```
where `sml-recompile-after-semicolon` would look like:
```
(defun sml-recompile-after-semicolon ()
(when (eq last-command-event ?\;)
...trigger recompilation...))
```
To trigger recompilation you can probably call `sml-compile` or something like that, but you'll need to handle the usual problems of detecting if the previous recompilation is still in process (and deciding what to do about it).
Also you'll probably want to delay the actual recompilation a little bit rather than start it right then and there even before `self-insert-command` has finished execution. You can do that for example with `run-with-idle-timer`.
# Answer
> 0 votes
Stefan's answer is the correct logic, and that did it for me in a few lines of ELisp.
I used the commands run-sml and sml-prog-prog-send-buffer to send it to inferior mode in a parallel buffer window.
Eventually though I switched to a key binding, since the backtick "\`" character on my keyboard is more ergonomic for this purpose than the semicolon ";" character.
```
(defun sml-keybinding-hook () "Bind backtick for quick compilation"
(setq sml-indent-level 2)
(global-set-key (kbd "`") 'sml-prog-proc-send-buffer)
(setq words-include-escape t)
)
(add-hook 'sml-mode-hook 'sml-keybinding-hook)
```
---
Tags: buffers, compilation
---
|
thread-55765
|
https://emacs.stackexchange.com/questions/55765
|
A custom layer, org-roam, only works on the 3rd restart of spacemacs
|
2020-02-25T04:34:25.427
|
# Question
Title: A custom layer, org-roam, only works on the 3rd restart of spacemacs
I'm using Spacemacs v.0.200.13, and GNU Emacs 26.3 (build 2, x86\_64-pc-linux-gnu, GTK+ Version 3.22.30) of 2019-09-16.
I'd like to install and use the org-roam package.
The instructions indicate that Spacemacs users should create a custom layer, use `use-package` to fetch the package using `recipe :fetcher github :repo (url)`.
I have done so.
**/home/me/.emacs.d/private/org-roam/packages.el**
```
(defconst org-roam-packages
'((org-roam :location
(recipe :fetcher github :repo "jethrokuan/org-roam" :branch "develop"))))
(defun org-roam/init-org-roam ()
(use-package org-roam
:after org
:hook
(after-init . org-roam-mode)
:custom
(org-roam-directory "~/Dropbox/org/notes")
:init
(progn
(spacemacs/declare-prefix "ar" "org-roam")
(spacemacs/set-leader-keys
"arl" 'org-roam
"art" 'org-roam-today
"arf" 'org-roam-find-file
"arg" 'org-roam-show-graph)
(spacemacs/declare-prefix-for-mode 'org-mode "mr" "org-roam")
(spacemacs/set-leader-keys-for-major-mode 'org-mode
"rl" 'org-roam
"rt" 'org-roam-today
"rb" 'org-roam-switch-to-buffer
"rf" 'org-roam-find-file
"ri" 'org-roam-insert
"rg" 'org-roam-show-graph))))
```
Then, in my **.spacemacs**, I add the package to my `dotspacemacs-configuration-layers`.
**.spacemacs**
```
dotspacemacs-configuration-layers
'(
org-roam
)
```
Now, if I restart emacs using `restart-emacs-resume-layouts`, and attempt to run any of the `org-roam` functions, I get the following error:
```
command-execute: Wrong type argument: commandp, org-roam-find-file
```
Looking through my messages, I see no obvious warnings or errors.
Then, I delete `org-roam` from my `dotspacemacs-configuration-layers`. I `restart-emacs-resume-layouts`. I re-add `org-roam` to my \`\`dotspacemacs-configuration-layers`. Now, if I run any of the`org-roam`functions, they work. However, I get the infamous`SPC SPC is undefined`error, which I usually take to mean there's some kind of error in my`.spacemacs`. Again, though, nothing in`messages.\` And, if I restart again, the functions again error.
Here is my .spacemacs in its entirety.
If I do `describe-package` when spacemacs is in a state where any of the `org-roam` functions give the `commandp` error, I see:
```
org-roam is an installed package.
Status: Installed in ‘org-roam-20200224.258/’ (unsigned). Delete
Version: 20200224.258
Summary: Roam Research replica with Org-mode
Requires: emacs-26.1, dash-2.13, f-0.17.2, s-1.12.0, async-1.9.4, org-9.0
Homepage: https://github.com/jethrokuan/org-roam
Keywords: org-mode roam convenience
```
How can I successfully use `org-roam` while still maintaining my `SPC SPC` keybindings, and in a way where it persists across emacs restarts?
EDIT: If I delete the `org-roam` folder in `.emacs.d/elpa`, then restart emacs, I get into the state wherein `org-roam` functions work, but I get `SPC SPC is undefined` errors.
Here is my entire messages buffer after a restart into the state where org-roam functions work, but `SPC SPC` doesn't.
# Answer
> 1 votes
You might try and add this to the top of the packages file or in a `layers.el` file.
```
(configuration-layer/declare-layer 'org)
```
I placed this in a separate `layers.el` file since spacemacs will load that first.
This has worked for me but I can't get the shortcuts to work.
\[Edit\]
I also compared my config to yours. I'm using defer in the use-package init:
```
(defun org-roam-layer/init-org-roam ()
(use-package org-roam
:after org
:hook
(after-init . org-roam-mode)
:defer t
:init
(progn
...
```
---
Tags: spacemacs, package
---
|
thread-55769
|
https://emacs.stackexchange.com/questions/55769
|
How to display a python string in the modeline?
|
2020-02-25T09:26:11.363
|
# Question
Title: How to display a python string in the modeline?
I'm using a python script to get my monthly bandwith usage shown as string on the terminal stdout. How can I display & update it periodically in the modeline?
# Answer
> 2 votes
You want to append data to `global-mode-string` .
```
(add-to-list 'global-mode-string '(:eval (myfunc)))
```
The function:
```
(defun myfunc ()
(setq mystring (shell-command-to-string "myshellcommand")))
```
where `myshellcommand` is your python script invocation returning your data string.
Now this might stress the system, so instead
```
(run-at-time 0 60 'myfunc)
(defun myfunc2() mystring)
(add-to-list 'global-mode-string '(:eval myfunc2))
```
So here `myfunc` is called every minute to update `mystring`. `myfunc2` returns `mystring`. We called `myfunc2` rather than `myfunc` in the mode string update thus not calling your script too often.
Edit:
You might want the call to myfunc2 to do some other work but if not, you can add the symbol directly:-
```
(add-to-list 'global-mode-string 'mystring)
```
# Answer
> 2 votes
There are many ways to add stuff to the mode line.
One way is to define a global minor-mode and a global string variable, register the variable in `mode-line-format` when the minor mode is active.
Run your Python code with a timer and write the result to the string variable and call `force-mode-line-update` for all windows afterwards.
The following Elisp code demonstrates that. The Python code is replaced by a `(format-time-string " Seconds: %S")` from Elisp. Put in whatever you like there.
* Don't use the `(:eval ...)` construct of `mode-line-format` to run your heavy Python task. That eval may be run much more often than you want!
* Instead of a simple string you can also use a `(:propertize ...)` construct to add fancy text properties. Since you can change these properties by `my-mode-line-update-handler` you can vary the text color from green to red depending on the network load.
```
;; mode-line-format
(defvar my-mode-line-update-interval 1
"Mode line update in seconds.")
(defvar my-mode-line-entry ""
"String holding my actual modeline add-on.
See `mode-line-format'.")
;; We need the following if we want to propertize the string:
(put 'my-mode-line-entry 'risky-local-variable t)
(defun my-mode-line-update-handler ()
"Mode line update running for `my-mode-line-mode'."
(setq my-mode-line-entry (format-time-string " Seconds: %S")) ;; here you run your Python code.
(force-mode-line-update t))
(defvar my-mode-line-timer nil
"Timer running my function and updating the modeline.")
(define-minor-mode my-mode-line-mode
"Demonstration of an updating modeline entry."
:global t
(when (timerp my-mode-line-timer)
(cancel-timer my-mode-line-timer))
(if my-mode-line-mode
(progn
(unless (memq 'my-mode-line-entry mode-line-format)
(setq mode-line-format (nconc mode-line-format (list 'my-mode-line-entry))))
(setq my-mode-line-timer (run-with-timer 0 my-mode-line-update-interval #'my-mode-line-update-handler)))
(setq mode-line-format (delq 'my-mode-line-entry mode-line-format))))
```
---
Tags: mode-line
---
|
thread-55774
|
https://emacs.stackexchange.com/questions/55774
|
Working with printed macro expansions
|
2020-02-25T13:40:47.580
|
# Question
Title: Working with printed macro expansions
I am trying to write a macro. I have read the manual and learned about `macroexpand`. However, when I use it, I find the expansion difficult to read and work with.
How can I expand a macro in a readable, workable format?
Let me illustrate.
If I simply call `macroexpand`, the result is echoed in the minibuffer. When the expansion is large, the echo is all scrunched up:
```
(macroexpand '(with-temp-file (make-temp-file "test-file")))
```
I can go to `*Messages*` with `C-h e`, copy and paste it back into `*scratch*`, and then format it. But clearly that gets tiresome.
To save on the copy/paste, I have tried using `eval-last-sexp` with a universal argument, `C-u C-x C-e`. This indeed prints the output to the buffer...but it's in some weird interactive state that I cannot edit. Pressing `RET` causes it to alternate between an abbreviated and expanded form:
Abbreviated (expressions contain ellipses):
Expanded (Placing point before the expansion and pressing `RET` causes the ellipses to expand and not insert a line break):
After calling `macroexpand`, `C-h k RET` shows that `elisp-last-sexp-toggle-display` is now the binding for `RET`.
All of this implies some kind of workflow. However, the documentation for `macroexpand` describes none of this behavior. The source code is not distributed with my version of Emacs (Emacs 26.3 for Windows). Scouring the web has found no meaningful explanation of how to work with macro expansions.
# Answer
> 2 votes
The question is really more about printing Lisp sexps (including results of evaluation) than it is about macro expansion, per se. It's just that macro expansion typically results in a large Lisp sexp that can be difficult to work with or read, especially if parts of it are elided (`...`).
I use **`pp-eval-last-sexp`**, which I bind to **`C-x C-e`**. (With `C-u` it inserts the result at point, like `eval-last-sexp`.)
You've pointed out some difficulties with this. But try the version of it you get with library **PP+** (**`pp+.el`**).
It respects user options **`pp-eval-expression-print-length`**, **`pp-eval-expression-print-level`**, and **`pp-max-tooltip-size`**. The first two are similar to but separate from the standard options with the same names but without prefix `pp-`. So you can have separate values for pretty printing and non-pretty printing.
I also bind **`M-:`** to **`pp-eval-expression`**, instead of `eval-expression`.
Both of these commands also let you use **`M-0`** to toggle between using a tooltip for the result (when it is no larger than `pp-max-tooltip-size`) and the usual handling (echo area or insertion in current buffer).
(The commands also respect option `eval-expression-debug-on-error`.)
---
Tags: elisp-macros, print, pretty-print
---
|
thread-55754
|
https://emacs.stackexchange.com/questions/55754
|
How to run functions inside auto-insert template
|
2020-02-24T21:19:55.440
|
# Question
Title: How to run functions inside auto-insert template
I have this in my init file
```
(use-package autoinsert
:ensure t
:init
;; Don't want to be prompted before insertion:
(setq auto-insert-query nil)
(setq auto-insert-directory (locate-user-emacs-file "templates"))
(add-hook 'find-file-hook 'auto-insert)
(auto-insert-mode 1)
:config
(define-auto-insert "poolchem.org?$" "poolchem.org"))
```
IOW, I have the template file `poolchem.org` in `~/.emacs.d/templates/`, which contains six tables. I went this route because it seemed easier than hand-tooling such a big thing in `(customize-variable 'auto-insert-alist)`. But I would like various bits of embedded initialization code to run upon creating `poolchem.org`, e.g.,
```
(org-read-date nil nil "++mon" nil (org-time-string-to-time "2020-03-31"))
```
should place the date of the next Monday after 2020-03-31 in the text upon file open. How can I do this? I've experimented with eval of `org-sbe` in `# local variables: ...` but that was handy for running code blocks upon file open, not individual embedded functions.
# Answer
> 3 votes
You can specify a vector of actions for each entry in `auto-insert-alist`.
This way you can insert the contents of the template file with the first action and then use a function that searches the new file for special elisp forms that are to be replaced with their evaluated results.
Below you find the source code for one such function.
You just wrap your code in the template file with `(auto-insert-init-form ...)` and that form will be evaluated like `progn`.
The last form of the code must return a string that is used to replace the code in the target file.
```
(defcustom auto-insert-init-form 'auto-insert-init-form
"Symbol identifying init forms in template files."
:group 'auto-insert
:type 'symbol)
(defun my-eval-auto-insert-init-form ()
"Evaluate (AUTO-INSERT-INIT-FORM ...) in autoinsert templates.
Thereby, AUTO-INSERT-INIT-FORM stands for the symbol defined by
the customizable variable `auto-insert-init-form'.
\(auto-insert-init-form ...) works like `progn'.
Applied in the newly created file it should return the string
that replaces the form."
(goto-char (point-min))
(cl-letf (((symbol-function auto-insert-init-form) #'progn))
(while (re-search-forward "(auto-insert-init-form[[:space:]]" nil t)
(let* ((beg (goto-char (match-beginning 0)))
(end (with-syntax-table emacs-lisp-mode-syntax-table
(forward-sexp)
(point)))
(str (eval (read (buffer-substring beg end)))))
(delete-region beg end)
(insert str)))))
(define-auto-insert
"poolchem.org?\\'"
["poolchem.org"
my-eval-auto-insert-init-form])
```
Example of the contents of a template file:
```
| first | table |
#+DATE: (auto-insert-init-form (org-read-date nil nil "++mon" nil (org-time-string-to-time "2020-03-31")))
#+AUTHOR: (auto-insert-init-form (read-string "Author: "))
| SOME | OTHER | TABLE |
| | | |
```
---
Tags: org-mode, template
---
|
thread-55783
|
https://emacs.stackexchange.com/questions/55783
|
How to change current-directory with emacsclient?
|
2020-02-25T18:08:45.577
|
# Question
Title: How to change current-directory with emacsclient?
I am trying to change the default directory using `emacsclient`, but it isn't working as I had hoped.
```
$ cd
$ emacsclient -e '(emacs-version)'
"GNU Emacs 28.0.50 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.22.30, cairo version 1.15.10)\n of 2020-02-19"
$ emacsclient -e '(setq default-directory "/home/joe/system-test/auth/")'
"/home/joe/system-test/auth/"
```
`M-x` `describe-variable` `RET` `default-directory` `RET`
> default-directory is a variable defined in ‘C source code’. Its value is "/home/joe/" Local in buffer *shell*; global value is nil
# Answer
You did not say for which buffer you want to set the default directory.
If you want to do it for the (existing) shell buffer with name `*shell*` try the following shell command:
```
emacsclient -e '(with-current-buffer "*shell*" (setq default-directory "/home/joe/system-test/auth/"))`
```
> 1 votes
---
Tags: shell, emacsclient
---
|
thread-55777
|
https://emacs.stackexchange.com/questions/55777
|
How to quit serial-term?
|
2020-02-25T15:50:37.750
|
# Question
Title: How to quit serial-term?
I opened a serial-term to /dev/ttyUSB0. I can't quit it. `C-x k` results in the following message:
`term-quit-subjob: Process /dev/ttyUSB0 is not a subprocess`
# Answer
You should be able to kill the buffer with `C-c k`.
General: all `C-x` keys should work, if you use `C-c` instead. So to change to another window would be `C-c o` instead of `C-x o`.
*Edit* `C-c <letter>` is often used for user keybindings, therefore you maybe might need to unbound your user keybinding before this works.
> 1 votes
---
Tags: term
---
|
thread-55720
|
https://emacs.stackexchange.com/questions/55720
|
Links to .org files are not recognized as links in org-mode
|
2020-02-23T09:53:46.757
|
# Question
Title: Links to .org files are not recognized as links in org-mode
I've been trying to use links in my org files but it doesn't work as I'd expect. It works as is should - convert `[[target][Desc]]` to `Desc` and make it clickable for any target, except when the target ends with `.org`. Then it is just the "raw" text version. I've tested in on an empty init.el with the same result.
```
[[file:~/test.or][Works]]
[[file:~/test.org][Does not work]]
[[file:~/test.org-][Works]]
```
Whenever I change the org extension either by adding a letter or subracting one, it folds the link properly. What should I adjust to fix it?
Emacs version: emacs-26.3-z-mac-7.8
Thanks!
# Answer
The problem is related to `org-roam` library. Upgrading `org` to `9.3.6-17-g389288-elpa`fixes the problem.
This is how you can upgrade `org` which by default is a built-in library. Add to `init.el`
```
(require 'package)
(add-to-list 'package-archives '("org" . "https://orgmode.org/elpa/") t)
```
Reload emacs and run `M-x list-packages RET`.
Find `org` and you'll see two available versions. Install the one from orgmode elpa.
After restarting, the newer version should be run (which you can confirm by `M-x org-version`).
> 2 votes
---
Tags: org-mode
---
|
thread-55755
|
https://emacs.stackexchange.com/questions/55755
|
Change Background Color of Code Block for org-mode LaTeX export
|
2020-02-24T21:42:34.997
|
# Question
Title: Change Background Color of Code Block for org-mode LaTeX export
I'm inserting code fragments in an org-mode document like this:
```
#+CAPTION: My Caption
#+NAME: fig:figure_name
#+BEGIN_SRC a_language
My code ...
#+END_SRC
```
In PDF LaTeX export, the code blocks are not easily distinguished from the main text. Ideally, I would like to have a bounding box and/or a light gray background, similar to how Stack Exchange sets apart snippets of code. I've tried changing the LaTeX background color org-mode option, but it didn't seem to do what I want. Is there any easy way to accomplish this?
# Answer
> 3 votes
This is a solution using latex package `lstlisting` instead of `minted`
(lstlisting is not so powerful as minted but does not need a whole python stack).
You need to put following lisp code into your Emacs init.el (or try it in `*scratch*` buffer like I did.
```
(setq org-latex-listings t)
(add-to-list 'org-latex-packages-alist '("" "listings"))
(add-to-list 'org-latex-packages-alist '("" "color"))
```
These lines load the latex packages `listings` and `color` and advice org mode to export code block using the `listings` latex package.
After that you can write your code block that way:
```
#+CAPTION: Caption, my caption!
#+ATTR_LATEX: :options frame=single,backgroundcolor=\color{lightgray}
#+BEGIN_SRC C :results output :exports both
int i, x = 10;
for(i = 0; i < x; i++)
printf("%d ",i);
printf(" ~ %d\n", x);
#+END_SRC
```
Notice the extra line of
`#+ATTR_LATEX: :options frame=single,backgroundcolor=\color{lightgray}`,
which defines a frame around the source code and a background color.
---
Above settings should produce following lines (among others) in the resulting `.tex` file:
```
...
\usepackage{color}
\usepackage{listings}
...
\lstset{language=C,label= ,caption={Caption, my caption!},captionpos=b,numbers=none,frame=single backgroundcolor=\color{lightgray}}
\begin{lstlisting}
int i, x = 10;
for(i = 0; i < x; i++)
printf("%d ",i);
printf(" ~ %d\n", x);
\end{lstlisting}
```
---
*Remark:* in older Org-Versions (v8 and older) `#+ATTR_LATEX` uses another syntax. Space () instead of `=` is used. The `#+ATTR_LATEX` needs to be changed slightly. Read more at the question org ignores attr latex
---
*Note:* here is another solution, using `minted`: https://stackoverflow.com/a/60396939
---
Tags: org-mode, org-export, latex, colors
---
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.