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-63752 | https://emacs.stackexchange.com/questions/63752 | Key bindings For Doom Emacs | 2021-03-05T19:21:40.320 | # Question
Title: Key bindings For Doom Emacs
I am trying to start using Doom Emacs, but I find it increasingly difficult to find what the new key bindings are for certain tasks, like the ones for using Org Mode.
When I use vanilla Emacs, there is the documentation for every tasks, so how do people using other distributions, like Doom Emacs, find what all the new key bindings are?
For example Org Mode has hundreds of key bindings, are all these remapped to new ones for Doom? How do I find them?
# Answer
**To describe a key sequence**
`SPC h k` runs `helpful-key` and will describe what the key sequence does in the current context. This will take the full key sequence, e.g. `SPC h k` then `g g` , and describe what the key sequence does (in this case, run `evil-goto-first-line`)
**To show the key sequence for a known function**
`M-x <function name>`
**To see all keybinds**
`SPC h b b` runs `counsel-descbinds` and will show all defined keys and their definitions.
**To see all keybinds for a major mode**
For a specific major mode map, `SPC h b f` will prompt you for a major mode (e.g. `org-mode-map`) and then show the associated keybinds.
> 8 votes
---
Tags: key-bindings, doom
--- |
thread-63918 | https://emacs.stackexchange.com/questions/63918 | Dired+ doesn’t work on old remote system | 2021-03-16T06:12:08.967 | # Question
Title: Dired+ doesn’t work on old remote system
When connected to an old remote system with Tramp 2.4.3.27.1, the buffer shows no files. With `tramp-verbose` set to 6, I looked at the Tramp debug buffer, then found (anonymized):
```
13:27:21.657267 tramp-send-command (6) # /bin/ls --color=never --dired -algGh /user/user/. 2>/dev/null
```
When I remove `2>/dev/null` and execute the above command, I get:
```
/bin/ls: invalid option -- h
Try `/bin/ls --help' for more information.
```
`ls` on the remote system is part of GNU fileutils 3.16 and does not support the option `-h`. For my regular system I have configured dired+:
```
(dired-listing-switches "-algGh")
```
*Is there any way to use a different configuration for that remote system?*
What I tried, unsuccessfully:
```
(connection-local-set-profile-variables
'example.com
'((dired-listing-switches nil)))
(connection-local-set-profiles
'(:application 'tramp :machine "example.com")
'example.com)
```
# How I connect to the old system
The system only supports connection by SSH v1. For that purpose, `plink` and `pscp` do support the option `-1`. So I added to `tramp-connection-properties`:
```
("/plink:user@example\\.com:" "login-args"
(("-1")
("-l" "%u")
("%h")))))
```
Now I can connect to `/plink:user@example.com:`.
# My solution
Thanks to Michael Albinus’ answer, I came up with:
```
(defun my-dired-before-readin-hook ()
(let ((remote-host (file-remote-p default-directory 'host)))
(when (string= remote-host "example.com")
(setq dired-actual-switches "-algG"))))
(add-hook 'dired-before-readin-hook 'my-dired-before-readin-hook)
```
# Answer
> 3 votes
And not to forget the hint in the Tramp manual:
Emacs computes the ‘dired’ options based on the local host but if the remote host cannot understand the same `ls` command, then set them with a hook as follows:
```
(add-hook
'dired-before-readin-hook
(lambda ()
(when (file-remote-p default-directory)
(setq dired-actual-switches "-al"))))
```
# Answer
> 2 votes
Set `tramp-verbose` to 6, and rerun the test. There will be a Tramp debug buffer. Look for messages tagged with `(6)`, they contain sent commands, and the responses. Perhaps you'll see what's going on.
# Answer
> 1 votes
Something like this works for me:
```
(defconst tramp-connection-local-default-dired-switches
'((dired-listing-switches . "-al")
(dired-actual-switches . "-al"))
"Default connection-local dired switches.")
(connection-local-set-profile-variables
'tramp-connection-local-default-dired-switches
tramp-connection-local-default-dired-switches)
(defun tramp-dired-connection-local-variables-apply ()
"Set `dired-listing-switches' in dired buffers."
(when (file-remote-p default-directory)
(let ((enable-connection-local-variables t))
(hack-connection-local-variables-apply
`(:application dired
:protocol ,(file-remote-p default-directory 'method)
:user ,(file-remote-p default-directory 'user)
:machine ,(file-remote-p default-directory 'host))))))
(with-eval-after-load 'dired
(tramp-compat-funcall
'connection-local-set-profiles
'(:application dired)
'tramp-connection-local-default-dired-switches)
(add-hook
'dired-mode-hook
#'tramp-dired-connection-local-variables-apply))
```
---
Tags: dired, tramp, ssh, remote, emacs27
--- |
thread-64045 | https://emacs.stackexchange.com/questions/64045 | Is there an easy way to use thing-at-point to initialize interactive read string (interactive "sfoo:") | 2021-03-22T16:22:59.943 | # Question
Title: Is there an easy way to use thing-at-point to initialize interactive read string (interactive "sfoo:")
Is there an easy way to use `thing-at-point` to initialize the contents of an `interactive` string reading?
I have a function the looks something like this:
```
(defun foo (string)
(interactive "sString:")
;; does something with string
)
```
But I'd really like it if when I did `M-x foo`, that it filled the minibuffer with the `thing-at-point`. In this case `(thing-at-point 'word)`.
Is the only way to get that to use an explicit list argument to `interactive`, something like:
```
(defun foo (string)
(interactive (list (read-from-minibuffer
"String:" ;; prompt
(thing-at-point 'word) ;; initial value
) ) ) ; interactive
;; does something with string
)
```
And if I do so, do my own history list etc?
# Answer
Yes, use `interactive` with a Lisp sexp, not a literal string. You can't specify particular defaulting with a literal string arg.
You can use `read-from-minibuffer`, `read-string`, or `completing-read`.
Provide the value returned by `(thing-at-point 'word)` as the `DEFAULT-VALUE` argument to one of those functions, not the `INITIAL-CONTENTS` argument.
(You can use the initial-contents/input arg if you like, but Emacs convention prefers that you use the default-value arg nowadays.)
As for the input *history* list: you can provide your own history variable, or you can just use the default history list, `minibuffer-history`. If you use your own then the only entries on it will be previous inputs to minibuffer-input reads that use your own history variable. That can mean less noise interactively, but it can also be handy to not be so specific. It's up to you.
> 1 votes
---
Tags: minibuffer, interactive, read
--- |
thread-64043 | https://emacs.stackexchange.com/questions/64043 | Org-export: How to filter table of contents entities | 2021-03-22T14:20:38.853 | # Question
Title: Org-export: How to filter table of contents entities
This is a follow-up question from this: Replace \LaTeX command in HTML export
Consider following org-mode file:
```
* Text about exporting from org-mode to \LaTeX
text
* Text about exporting from org-mode to HTML
another text
```
If I export this file to HTML and also use filter to replace "\LaTeX" in heading with simple "LaTeX", I end up with table of contents entries that still contain "\LaTeX" as a string, instead of the replacement "LaTeX."
I should also add that I am using Doom Emacs and I am running Emacs in non-interactive session through `makefile` (I am doing multiple exports to multiple export formats).
Looking to org-manual about TOC, I could use property `ALT_TITLE` (org TOC), but because I am exporting also to LaTeX, that would mean I would lost formatting in there.
I reused filter fom linked question:
```
(require 'ox)
(require 'ox-html)
(defun my-latex-filter-example (text backend info)
"Replace \LaTeX with \"LaTeX\" in HTML output."
(when (org-export-derived-backend-p backend 'html)
(replace-regexp-in-string "\\\\LaTeX" "LaTeX" text)))
(add-to-list 'org-export-filter-link-functions
'my-latex-filter-example)
```
According to optons listed in manual: Advanced Export I have also tryied `plain-text` and `options` `org-export-filter-functions`, but none were able to remove string "\LaTeX" from HTML table of contents.
Is there a way to target with filter functions links generated by TOC in HTML?
# Answer
You can use a macro that expands differently in the two cases:
```
#+MACRO: latex @@latex:\LaTeX@@ @@html:LaTeX@@
* Something about {{{latex}}}
{{{latex}}} is cool.
```
Check out the section in the manual on macros with `C-h i g (org)macro` and the various sections on quoting constructs, e.g. `C-h i g (org)quoting latex` for latex and similar ones for the other exporters.
> 1 votes
---
Tags: org-mode, org-export
--- |
thread-64011 | https://emacs.stackexchange.com/questions/64011 | Generate a new table out of old one with sorting | 2021-03-21T02:27:56.167 | # Question
Title: Generate a new table out of old one with sorting
Here is a table where scores are calculated at last row with a formula. How to generate a new table `TotalResults` with 1 and last columns? Can we even sort the last column in the process?
```
#+NAME: ScoreCard
| team | 1st round | 2nd round | total |
|------+-----------+-----------+-------|
| A | 7 | 9 | 16 |
| B | 3 | 5 | 8 |
#+TBLFM: $4=vsum($2..$3)
```
Like this one
```
#+NAME: ScoreCard
| team | total |
|------+-------|
| B | 8 |
| A | 16 |
```
# Answer
Hope this function will do the trick
```
(defun generate-a-new-table-out-of-old-one-with-sorting (ref)
" Inserts an Org table at point copied from an existing table REF.
only first and last colums are copied and the table is sorted by following the last column "
(interactive (list (read-from-minibuffer "Table name to proceed :" "ScoreCard")))
(let ((fline (concat "|"
(org-table-get-remote-range ref "@<$<") "|"
(org-table-get-remote-range ref "@<$>") "|\n"))
(fcol (org-table-get-remote-range ref "@<<$<..@>$<") )
(lcol (org-table-get-remote-range ref "@<<$>..@>$>"))
)
(insert "\n#+TBLNAME: TotalResults\n")
(insert fline)
(seq-mapn (lambda(x y) (insert "|" x "|" y "|\n"))fcol lcol)
(org-table-goto-line 1)
(org-table-insert-hline)
(org-table-analyze)
(org-table-goto-field "@2$2")
(org-table-sort-lines nil ?n)
(orgtbl-ctrl-c-ctrl-c nil)))
```
You can sort the results in descending order by replacing ?n by ?N in the sort command. For my own that is what i would done.
## PS:
To activate this function, first evaluate it (The simplest is C-x C-e after the last parenthesis, but you can evaluate it in a source block like you did it).
Next evaluate it like any elisp function (the resulting table will be inserted at point)
```
M-x generate-a-new-table-out-of-old-one-with-sorting
```
Obviously you can change the name of the function for a shorter.
If you find it handy and use it frequently, you can save my code in your init file and (eventually) bind it to some keystrokes.
## ps 2:
If you prefer the code to be evaluated in an org-mode block I had adapted it :
```
#+begin_src emacs-lisp :var ref="ScoreCard" :results value raw
(let ((fline (concat "|"
(org-table-get-remote-range ref "@<$<") "|"
(org-table-get-remote-range ref "@<$>") "|\n"))
(fcol (org-table-get-remote-range ref "@<<$<..@>$<") )
(lcol (org-table-get-remote-range ref "@<<$>..@>$>"))
)
(with-temp-buffer
(org-mode)
(insert "\n#+TBLNAME: TotalResults\n")
(insert fline)
(seq-mapn (lambda(x y) (insert "|" x "|" y "|\n"))fcol lcol)
(org-table-goto-line 1)
(org-table-insert-hline)
(org-table-analyze)
(org-table-goto-field "@2$2")
(org-table-sort-lines nil ?n)
(orgtbl-ctrl-c-ctrl-c nil)
(buffer-string))
)
#+end_src
```
> 1 votes
---
Tags: org-mode, org-table
--- |
thread-41703 | https://emacs.stackexchange.com/questions/41703 | Fold the immediate outer section in org-mode | 2018-05-29T08:53:34.353 | # Question
Title: Fold the immediate outer section in org-mode
I can un/fold a section in org-mode by calling `org-cycle`. However, the cursor has to stay on the heading in order for that to work. What can I do to collapse the section in which I am currently stationed?
Example:
```
* Section 1
** Section 1.1
** Section 1.2
lots of lines
information [] <-- cursor somewhere here
lots of lines
** Section 1.3
```
----\> fold outer
```
* Section 1
** Section 1.1
** Section 1.2 [] <--- cursor somewhere here
** Section 1.3
```
----\> fold outer
```
* Section 1 [] <--- cursor somewhere here
```
I feel like there should be a way to do this by jumping to the first heading of the outer level and calling `org-cycle`, but making this jump seems to require some dev knowledge of org-mode, so I am here to ask for help.
# Answer
> 3 votes
You can try this function. (surely not perfect)
```
(defun org-fold-outer ()
(interactive)
(org-beginning-of-line)
(if (string-match "^*+" (thing-at-point 'line t))
(outline-up-heading 1))
(outline-hide-subtree)
)
```
# Answer
> 3 votes
There are some predefined settings available for the behavior of `org-cycle`.
You can play with the settings using
```
M-x customize-variable org-cycle-emulate-tab
```
# Answer
> 3 votes
Here is a simple way to do it without custom keybinds.
**1)** A simple solution for part 1 is to use `org-previous-visible-heading` which is bound to `C-c C-p`. This will take you to to the heading you are working under, at which point you can hit `TAB` to collapse it.
Taken together `C-c C-p TAB` will navigate to the heading you are working under and collapse it.
Note: There is also the handy `C-c C-n` for going to the next visible org header (we are just prefixing the next and previous line commands with `C-c` to get this behaviour)
**2)** Use `outline-up-heading` (`C-c C-u`) to navigate to the parent heading, then hit tab to collapse it's children.
`C-c C-u TAB`
This is very similar to `C-c C-p` except it is guaranteed to go to the *parent* heading whereas `C-c C-p` will go to the previous *visible* heading. So in example 2 `C-c C-p` will go to Section 1.1 while `C-c C-u` will go to Section 1.
---
Tags: org-mode
--- |
thread-63757 | https://emacs.stackexchange.com/questions/63757 | Return receipt in mu4e | 2021-03-05T20:45:17.420 | # Question
Title: Return receipt in mu4e
How can I use "return receipt" (Message disposition notifications) in mu4e. For composing as well as receiving messages?
For composing I tried to add a "RRT" field in the header, but receiving this mail with thunderbird didn't result in a "return receipt" pop up.
Vice versa I don't know how to make mu4e ask me for Message disposition notification if I receive such an email with mu4e.
# Answer
Have you tried `C-c M-n` while writing the message? This at least should cover part of the answer. Regarding the visibility of the return receipt pop-up in mu4e, according to this thread such functionality does not exist at the moment
> 1 votes
---
Tags: mu4e
--- |
thread-46602 | https://emacs.stackexchange.com/questions/46602 | How execute sqlite query? | 2018-12-14T18:28:30.743 | # Question
Title: How execute sqlite query?
windows 10, emacs 26.1
I has file `my_test.sql`. This file content `SQLite` query. Is it possible to execute this sql query and get results?
1. I has `sqlite` db file `test.db`
2. It has table `notification_invoice`
3. I create file my\_test.sql with one sql query:
*select * from notification\_invoice order by notificationDate*
So here my steps:
1. Open `my_test.sql`
2. `M-x sql-set-product` RET `sqlite`
3. `sql-product-interactive`
4. in the sql-mode buffer) to call `sql-send-buffer`
As you can see I not get sql result.
What is wrong with my steps?
# Answer
* Open `my_test.sql` (this buffer is in `sql-mode`; aka "SQL")
* `M-x` `sql-set-product` `RET` `sqlite`
* `C-c``TAB` to call `sql-product-interactive` to connect to the database (this new buffer is in `sql-interactive-mode`; aka "SQLi")
* `C-c``C-b` (in the `sql-mode` buffer) to call `sql-send-buffer`, sending the whole buffer as a query
Use `C-h``m` in the `sql-mode` buffer to see the other `sql-send-*` commands and key bindings for sending queries.
> 3 votes
# Answer
I think something is wrong with SQL-mode, sqlite3 and Emacs on Windows. As seen in your screenshot, you can't see the `sqlite>` prompt, and the same happens for me when I run sql-mode with sqlite3 on Windows. From what I can see the sql querys are sent to the sql-process but the output from sqlite3 is not shown.
I found the following solution. What you need to add is:
```
(setq sql-sqlite-options '("-interactive")))
```
> 2 votes
---
Tags: sqlite
--- |
thread-64048 | https://emacs.stackexchange.com/questions/64048 | Best package for SVN (Subversion) | 2021-03-22T17:09:01.920 | # Question
Title: Best package for SVN (Subversion)
Emacs 26.1.
To work with Git I use package **magit**. It's very nice package.
But I also need package to work with SVN. Has analog of magit but to work with SVN ?
# Answer
> 2 votes
SVN is supported by Emacs' built-in version control system.
I don't think there's anything comparable to magit for SVN, partly because git is much more capable than SVN, and partly because fewer and fewer people have been using SVN since git came along.
# Answer
> 2 votes
The Foundation I work for also uses Subversion exclusively, since quite a few features they need would not be handled as easily using git (some of them: huge monorepos, centralised workflow, excellent TortoiseSvn client).
Some of the engineers use dsvn. Some use psvn. I personally use the built in Emacs VC system.
See also Subversion on EmacsWiki.
---
Tags: svn
--- |
thread-64054 | https://emacs.stackexchange.com/questions/64054 | How do I populate tags for C? | 2021-03-23T00:29:04.473 | # Question
Title: How do I populate tags for C?
I hover over stdlib:
```
#include <stdlib.h>
```
I type `M-.` and it asks me:
```
Visit tags table (default TAGS):
```
I don't have one of those. I see a lot of information about TAGS in the emacs documentation: https://www.emacswiki.org/emacs/TagsFile#tags\_file
But what should I use, CTAGS, ETAGS, Universal CTags, Global Tags? Should I set this up in the makefile or in a key binding?
# Answer
I'd use `etags` because it comes with Emacs and is what the default implementation of `M-.` targets.
Given a C project you can use `etags *.c *.h` to generate the `TAGS` file in that directory and select it when prompted by `M-.`. Some C projects already provide a `Makefile` target for that, for example you can run `make tags` in the Emacs sources to generate them for the Lisp and C parts. This is highly useful to jump to the source of a definition.
> 2 votes
---
Tags: c, ctags, tags
--- |
thread-64062 | https://emacs.stackexchange.com/questions/64062 | How to avoid using auth-sources when editing with sudo? | 2021-03-23T09:27:01.190 | # Question
Title: How to avoid using auth-sources when editing with sudo?
When I invoke `crux-sudo-edit`, Emacs hangs forever with the following message:
`Decrypting /home/$USER/.authinfo.gpg...0%`
until I press C-g, then it asks:
`Passphrase for symmetric encryption for /home/$USER/.authinfo.gpg:`
(When finding a file with "/sudo::/path/to/file/", Emacs doesn't hang but still want to decrypt my ~/.authinfo.gpg)
Because I don't save my root password there, I press another "C-g", but annoyingly another window shows up:
```
Error while decrypting with "/usr/bin/gpg2":
gpg: error creating keybox '/home/$USER/.gnupg/pubring.kbx': No such file or directory
gpg: keyblock resource '/home/$USER/.gnupg/pubring.kbx': No such file or directory
gpg: AES.CFB encrypted data
```
And it doesn't disappear even after supplying my root password.
Setting `tramp-completion-use-auth-sources` to `nil` doesn't solve this.
This problem only appears after creating "~/.authinfo.gpg".
Edit: thank to TRAMP's maintainer's suggestion below, I have come to stricter solution that only disables `auth-sources` for local sudos, leaving other remote uses (mostly?) intact:
```
(connection-local-set-profile-variables
'remote-without-auth-sources
'((auth-sources . nil)))
(connection-local-set-profiles
'(:application tramp :protocol "sudo"
:user "root" :machine "localhost")
'remote-without-auth-sources)
```
# Answer
This is the same question as discussed in https://debbugs.gnu.org/46674 In short: Use Tramp 2.5 from GNU ELPA, and apply in your .emacs
```
(connection-local-set-profile-variables
'remote-without-auth-sources '((auth-sources . nil)))
(connection-local-set-profiles
'(:application tramp) 'remote-without-auth-sources)
```
> 2 votes
---
Tags: tramp, gpg, sudo, authinfo, root
--- |
thread-60392 | https://emacs.stackexchange.com/questions/60392 | spacemacs osx layer | 2020-08-30T06:18:50.467 | # Question
Title: spacemacs osx layer
I'm trying spacemacs for the first time.
Since I'm on mac, I'd like to change command key as Meta, so I put the following code, and restarted emacs.
It's not working as expected.
When I do `Command-x` it is recognized as `s-x` I think it is `hyper-x` (although I have not used `hyper` much)
```
(defun dotspacemacs/layers ()
"Configuration Layers declaration.
You should not put any user code in this function besides modifying the variable
values."
(setq-default
;; Base distribution to use. This is a layer contained in the directory
;; `+distribution'. For now available distributions are `spacemacs-base'
;; or `spacemacs'. (default 'spacemacs)
dotspacemacs-distribution 'spacemacs
;; Lazy installation of layers (i.e. layers are installed only when a file
;; with a supported type is opened). Possible values are `all', `unused'
;; and `nil'. `unused' will lazy install only unused layers (i.e. layers
;; not listed in variable `dotspacemacs-configuration-layers'), `all' will
;; lazy install any layer that support lazy installation even the layers
;; listed in `dotspacemacs-configuration-layers'. `nil' disable the lazy
;; installation feature and you have to explicitly list a layer in the
;; variable `dotspacemacs-configuration-layers' to install it.
;; (default 'unused)
dotspacemacs-enable-lazy-installation 'unused
;; If non-nil then Spacemacs will ask for confirmation before installing
;; a layer lazily. (default t)
dotspacemacs-ask-for-lazy-installation t
;; If non-nil layers with lazy install support are lazy installed.
;; List of additional paths where to look for configuration layers.
;; Paths must have a trailing slash (i.e. `~/.mycontribs/')
dotspacemacs-configuration-layer-path '()
;; List of configuration layers to load.
dotspacemacs-configuration-layers
'(
javascript
;; ----------------------------------------------------------------
;; Example of useful layers you may want to use right away.
;; Uncomment some layer names and press <SPC f e R> (Vim style) or
;; <M-m f e R> (Emacs style) to install them.
;; ----------------------------------------------------------------
helm
;; auto-completion
;; better-defaults
emacs-lisp
;; git
;; markdown
;; org
;; (shell :variables
;; shell-default-height 30
;; shell-default-position 'bottom)
;; spell-checking
;; syntax-checking
;; version-control
(osx :variables
osx-command-as 'meta
osx-option-as 'meta
osx-control-as 'control
osx-function-as nil
osx-right-command-as 'left
osx-right-option-as 'left
osx-right-control-as 'left
osx-swap-option-and-command nil)
)
;; List of additional packages that will be installed without being
;; wrapped in a layer. If you need some configuration for these
;; packages, then consider creating a layer. You can also put the
;; configuration in `dotspacemacs/user-config'.
dotspacemacs-additional-packages '()
;; A list of packages that cannot be updated.
dotspacemacs-frozen-packages '()
;; A list of packages that will not be installed and loaded.
dotspacemacs-excluded-packages '()
;; Defines the behaviour of Spacemacs when installing packages.
;; Possible values are `used-only', `used-but-keep-unused' and `all'.
;; `used-only' installs only explicitly used packages and uninstall any
;; unused packages as well as their unused dependencies.
;; `used-but-keep-unused' installs only the used packages but won't uninstall
;; them if they become unused. `all' installs *all* packages supported by
;; Spacemacs and never uninstall them. (default is `used-only')
dotspacemacs-install-packages 'used-only)
)
```
# Answer
You're not giving enough information to help debug: from details of the errors you're seeing to what version of Spacemacs you have installed. I have just installed a clean Spacemacs repo (the `develop` branch), added `osx` layer to `dotspacemacs-configuration-layers` (with no layer variables), and had no problems.
The `osx` layer maps Cmd key to Hyper since commit 2215ffe68 because of various possible issues when using Alt or Super. They also don't recommend mapping it to Meta -- see the commit message for details.
Also note that the layer maps most but not all the standard macOS key bindings: the one that I noticed right away was Cmd-o to open a file. I just bind it to `((kbd-mac-command "o") . counsel-find-file)` in my config.
I'd suggest you give it a another try by checking out the `develop` branch of Spacemacs, but with just `osx` with no layer vars in your `dotspacemacs-configuration-layers`. Report here if you see any errors.
> 1 votes
---
Tags: spacemacs
--- |
thread-64056 | https://emacs.stackexchange.com/questions/64056 | key binding isearch-forward with Greek keyboard | 2021-03-23T05:12:49.383 | # Question
Title: key binding isearch-forward with Greek keyboard
I use Emacs with various languages and have had trouble invoking `isearch-forward` from a keystroke when my keyboard layout (OS-level) is set to Greek. If I try the usual `C-s`, it says there is no binding for `C-σ` (since the 's' key is now the 'σ' key). I tried setting up a new key binding using `global-set-key`, switching to Greek, typing `C-σ`, switching back to English, and then indicating `isearch-forward`. This works fine for the first search, but I want to be able to hit `C-σ` again to search for the next occurrence, the way it works with `C-s` when my keyboard layout is set to English. But this doesn't work. Instead, it prompts me for a new search string. How can I set it up so that `C-σ` works exactly like `C-s`, so that I can hit `C-σ` again to advance to the next occurrence of my (Greek) search string? Of course I also want to do the same thing with `C-ρ` for isearch-backward.
# Answer
Try binding keys also in `isearch-mode-map`. These keys are among those bound there by default, for example:
```
C-r isearch-repeat-backward
C-s isearch-repeat-forward
C-M-r isearch-repeat-backward
C-M-s isearch-repeat-forward
M-r isearch-toggle-regexp
M-s r isearch-toggle-regexp
```
For example:
```
(define-key isearch-mode-map (kbd "C-s") 'isearch-repeat-forward)
```
Instead of `(kbd "C-s")` you would substitute whatever key you also bound globally for Isearch.
---
You can see all of the `isearch-mode-map` key bindings if you load library `help-fns+.el`. Just use `C-h M-k isearch-mode-map`.
> 1 votes
---
Tags: key-bindings, keymap, isearch, keyboard-layout
--- |
thread-64067 | https://emacs.stackexchange.com/questions/64067 | Expand an archived org-mode subtree with just TAB | 2021-03-23T12:46:32.133 | # Question
Title: Expand an archived org-mode subtree with just TAB
I like to use the archive tag just to collapse the subtree automatically on opening the file (and also its gray coloring); I do not see why it should force me to use some esoteric hotkey (which my terminal emulator doesn't support) to expand the archived subtree. Any way to remove this limitation?
# Answer
Yes, you can set the variable `org-cycle-open-archived-trees` to `t` and `org-cycle` (to which `TAB` is bound) will behave with archived trees as it does normally.
If you prefer to keep that variable's default value, you can instead bind a key sequence of your choice to the function `org-force-cycle-archived`, e.g.
```
(define-key org-mode-map (kbd "C-c r") 'org-force-cycle-archived)
```
A third approach (and my preferred one) is to enable org speed keys and add a mapping to `org-speed-commands-user`, like this
```
(setq org-use-speed-commands t)
(add-to-list 'org-speed-commands-user (cons "r" 'org-force-cycle-archived))
```
Then when point is at the very beginning of an archived subtree, pressing `r` will unfold it.
(A disadvantage of allowing `org-cycle` to operate on archived subtrees is that you typically do not want to expand them when point is on a parent heading. That's why I personally like to keep `org-cycle-open-archived-trees` set to `nil`.)
> 1 votes
# Answer
I got what I wanted (folded archive tags on startup but unfoldable by `TAB`) with this config:
```
(setq org-startup-folded 'overview) ; @upstreambug https://github.com/hlissner/doom-emacs/issues/3693
(map!
:map evil-org-mode-map
:n
"TAB" 'org-force-cycle-archived
)
```
> 0 votes
---
Tags: org-mode
--- |
thread-64072 | https://emacs.stackexchange.com/questions/64072 | binding <tab> to company complete | 2021-03-23T14:51:12.120 | # Question
Title: binding <tab> to company complete
I would like to *always* trigger company suggests. When I use:
```
(global-set-key (kbd "<tab>") 'company-complete))
```
It breaks ivy's completion in the minibuffer. How can I prevent this? I would like to set the above key binding globally, even for the scratch buffer, but not to break the current completion used in the minibuffer.
# Answer
> 4 votes
Try putting that binding into `company-mode-map`:
```
(with-eval-after-load 'company
(define-key company-mode-map (kbd "<tab>") 'company-complete))
```
`company-mode` is not active in the minibuffer, so it shouldn't be affected.
---
Tags: key-bindings, completion, ivy, company
--- |
thread-27492 | https://emacs.stackexchange.com/questions/27492 | Batch rename files to numeric sequence in dired? | 2016-10-01T18:16:59.007 | # Question
Title: Batch rename files to numeric sequence in dired?
I have the following files in a directory:
```
CIMG4879.JPG
CIMG4880.JPG
CIMG4881.JPG
...
```
I want to rename them all with a numeric sequence such that:
```
01.jpg
02.jpg
03.jpg
...
```
In bash, I could `convert *.JPG %02d.jpg`, since they're all image files.
**How do I do a batch rename in `dired`?** Assume I have a lot a files, so doing it one by one would be tedious and error-prone.
# Answer
> 10 votes
Firstly, take note of JeanPierre's comment -- you're *not* renaming files by using `convert` like that. You're creating new and different files (lower quality ones, although the difference may or may not matter in practice, depending on your use-cases).
Here are a few different options for renaming files in dired using a number sequence. The first two are general techniques for editing text, which are applicable thanks to the excellent `wdired-mode`. The third combines dired's rename command with keyboard macro counters.
1. With search-and-replace:
* `C-x``C-q` (change to editable dired mode; use `C-c C-k` to cancel the edit if you mess anything up)
* `C-M-%` (call `query-replace-regexp`)
* `CIMG[0-9]+\.JPG` (pattern to match)
* `\,(format "%02d" (1+ \#)).JPG` (replacement)
* `!` (replace all; or else you could confirm the replacements individually)
* `C-c``C-c` (to return to normal dired mode, writing the changes)
`\,(...)` calls an elisp function and uses the result in the replacement text; here we are calling `format` on the replacement counter, to which we are first adding one (as it counts from zero).
(It's a shame that `dired-do-rename-regexp` doesn't support that, but not a big deal when you're familiar with `wdired-mode`.)
2. Once again in editable dired mode, mark the filenames as a rectangle, delete the rectangle, then use `rectangle-number-lines` to insert new contents:
* `C-u``C-x``r``N` call `rectangle-number-lines` with extended argument input
* Start from 1
* Use `%02d` as the replacement, being sure to remove the default trailing space (or you could use `%02d.JPG`, depending on what you actually deleted)
3. With keyboard macros, in normal dired:
* `C-x``C-k``C-f` `%02d` (set kmacro counter format)
* `M-1``F3` (start recording, initialising counter to 1)
* `R` (dired rename)
* `F3` (insert the current kmacro counter value; the counter then increments)
* `.JPG` `RET` (remainder of the new filename)
* `C-n` (next line)
* `F4` (repeatedly; first to end recording, and then to repeat the macro)
You can use `M-0``F4` to repeat the macro as many times as possible.
# Answer
> 2 votes
> In dired I do not know the regexp
Why bother with dired's regex-replacement? Just enter wdired-mode (which I bind to `w` in dired, but default=`C-x C-q`), edit the filenames like regular text, then exit back to normal dired with `C-c C-c`.
# Answer
> 1 votes
```
(defun rename-files-numeric-sequence ()
(interactive)
(let ((sequence 1)
(files (directory-files-recursively default-directory "")))
(while files
(rename-file (car files)
(format "%s%03d.%s"
(file-name-directory (car files))
sequence
(file-name-extension (car files))))
(setq files (cdr files))
(setq sequence (1+ sequence)))))
```
---
Tags: dired
--- |
thread-64081 | https://emacs.stackexchange.com/questions/64081 | How to get the PATH from the SHELL | 2021-03-24T01:04:18.553 | # Question
Title: How to get the PATH from the SHELL
When launched at system start-up, the Emacs daemon doesn't pick up modifications to the `PATH` introduced by shell initialization scripts.
Emacswiki suggests to use this function to update Emacs' PATH,
```
(defun set-exec-path-from-shell-PATH ()
"Set up Emacs' `exec-path' and PATH environment variable to match
that used by the user's shell.
This is particularly useful under Mac OS X and macOS, where GUI
apps are not started from a shell."
(interactive)
(let ((path-from-shell (replace-regexp-in-string
"[ \t\n]*$" "" (shell-command-to-string
"$SHELL --login -i -c 'echo $PATH'"
))))
(setenv "PATH" path-from-shell)
(setq exec-path (split-string path-from-shell path-separator))))
(set-exec-path-from-shell-PATH)
```
but it returns some errors:
```
bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
stty: 'standard input': Inappropriate ioctl for device
```
As far as I understand (my main reference), since I want to run Bash in interactive mode (so that it loads `~/.bashrc`) I should use `start-file-process`(`-shell-command`) to invoke the shell process. However, I can't figure out how to store the output of the command in a string when I do so.
# Answer
> 8 votes
No, you don’t want to use `-i` because you’re not launching an interactive shell. That is, this shell will not be connected to a terminal that the user can type in. It is instead going to be connected to a pipe so that Emacs can read whatever it prints. Removing the `-i` option will prevent Bash from trying to use inappropriate ioctls on the stdout and stdin, and thus eliminate the error messages.
If your `PATH` is only configured by your `~/.bashrc` file, then you’ve misconfigured Bash. You should ensure that at least your `PATH` is set up consistently in both interactive and non—interactive shells. Most distros do this by making the default `~/.bash_profile` source `~/.bashrc` for you. Configuring this correctly will ensure that you get the correct `PATH` value.
---
Tags: shell, emacsclient, linux, bash, environment
--- |
thread-64084 | https://emacs.stackexchange.com/questions/64084 | Top-level variables, local variables, variable scoping and the difference between set and setq | 2021-03-24T07:32:40.190 | # Question
Title: Top-level variables, local variables, variable scoping and the difference between set and setq
I've been reading about emacs dynamic and lexical bindings. While I generally get the difference between the two types, there is one example that is not clear to me. I've checked this question and I think I understand why the second example prints nil instead of `t` (I've read about `set` and `setq` when `lexical-binding: t`
```
;; -*- lexical-binding: t -*-
(let ((a nil))
(setq a t)
(print a))
(let ((a nil))
(set 'a t)
(print a))
```
From the elisp manual I've read that when lexical-binding is in effect `set` affects the *dynamic* value of a variable where as `setq` affects its current lexical value. However from the following example it looks like `(setq a 5)` sets the dynamic value of a since later (set 'a t) changes top level `a`.
```
;;; -*- lexical-binding: t; -*-
(setq a 5)
(let ((a nil))
(setq a t)
(print a)) ;; prints t
(let ((a nil))
(set 'a t)
(print a)) ;; prints nil
a ;; prints t (I've expected this to be unchanged i.e. 5)
```
My question is when lexical-binding is on, what is the binding for the top level variables ?
# Answer
Looking at Using Lexical Binding it appears that `a` needs to be defined special which in using `setq` it is not. Modifying your example to use `defvar` gives the answers expected.
```
;;; -*- lexical-binding: t; -*-
(defvar b 5)
(let ((b nil))
(setq b t)
(print b)) ;; prints t
(print b) ;; prints 5
(let ((b nil))
(set 'b t)
(print b)) ;; prints t
(print b) ;; prints 5
```
> 2 votes
---
Tags: lexical-scoping, setq, dynamic-scoping
--- |
thread-63906 | https://emacs.stackexchange.com/questions/63906 | Error enabling Flyspell mode (Error: No word lists can be found for the language "en_US") | 2021-03-15T12:20:21.857 | # Question
Title: Error enabling Flyspell mode (Error: No word lists can be found for the language "en_US")
I recently saw my emacs (GNU Emacs 27.1 running on Arch Linux) throw this error:
```
Error enabling Flyspell mode:
(Error: No word lists can be found for the language "en_US".)
```
when I visited a markdown file. My emacs is configured to use the latest commit on the develop branch of spacemacs. Any idea how I can allow Flyspell to find a word list?
I tried the solution from Error: No word lists can be found for the language "en\_US", which was to simply install `aspell`, but it doesn't fix the problem.
# Answer
One needs to install additional dictionaries used either by ispell or, in your case, aspell programs: there are corresponding packages for them (looks like this, I'm not on arch, so can not speak for this).
You can see what kind of languages are available using `M-x spell-checking/change-dictionary`.
> 5 votes
---
Tags: spacemacs, flyspell
--- |
thread-63705 | https://emacs.stackexchange.com/questions/63705 | Toggling off all settings in python and julia to get bare setup | 2021-03-03T13:48:31.670 | # Question
Title: Toggling off all settings in python and julia to get bare setup
since recently I am using LSP for python, tex and julia on macos with spacemacs develop. To some extend this is great, but it is something awefully slow using a gui... and it seems that it is not only LSP.
So in these times it would be great to toggle off all additional python/julia 'add-ons' and just keep the basic keybindings and e.g. just the syntax highlighting for python/julia.
I was thinking about using an enhance fundamental-mode with font-locking for the mentioned modes.
Do you have a hint how to achieve this? Or is there maybe a better way to get a fast emacs in gui... in a terminal the navigation is quite fast even with all fancy settings turned on.
Maybe there is a special mode like tiny-python or something similar...
Thank you in advance! Fab
# Answer
> 0 votes
You can switch off the gui parts by customizing variables `lsp-ui-*` as described here. For python-mode you can use non-lsp based backend, the anaconda-mode
```
(python :variables python-backend 'anaconda)
```
see here.
The same for julia: if lsp layer is installed, all languages get lsp backend by default, unless it is specified to be another backend or e.g. `nil`.
Further, you can see, which modes are activated using `C-h m` and switch them off as well. Mode activations e.g. autocompletion are happening in the mode hooks, i.e. you can remove some functions in `python-mode-hook` etc.
---
Tags: spacemacs, python, lsp
--- |
thread-59529 | https://emacs.stackexchange.com/questions/59529 | How Shall I Understand org-mode Habits Graph Colors? | 2020-07-08T15:30:22.290 | # Question
Title: How Shall I Understand org-mode Habits Graph Colors?
The org-mode documentation has following to say about the colors in the habits graph:
* **Blue**: If the task was not to be done yet on that day.
* **Green**: If the task could have been done on that day.
* **Yellow**: If the task was going to be overdue the next day.
* **Red**: If the task was overdue on that day.
I have the following graphs:
The habits repeat daily and are defined like this: `<2020-07-09 Thu 12:00 .+1d>`
In this example I fail to understand what the documentation means? It’s pretty clear that the evening habit was never done in the past (hence everything is red and there is no star). But how should I read the first and second column for “Morning” and “Afternoon”? Why are they blue? When I hover over the first column, I don’t get a tooltip. When I hover over the second blue column (which has a star) the tooltip shows **2020-06-18**. But when I take a look at this day, I see that I completed this particular habit at 13:21, after it was meant to be done on that day.
To me this looks like a bug and I would expect everything to be green with stars for the first two habits, but I’m probably missing something?
# Answer
> 1 votes
The colors are relative to the emacs theme selected. As I understand it, the two first cells are blue since the task was then overdue (OR org-habit-preceding-days is set to show days prior to the first schedule), and the second cell is blue since, even when you marked the task as done, it was already overdue.
---
Tags: org-mode, org-agenda, org-habit
--- |
thread-61060 | https://emacs.stackexchange.com/questions/61060 | How to make email in emacs work with an Oauth2 requirement? | 2020-10-08T00:56:38.360 | # Question
Title: How to make email in emacs work with an Oauth2 requirement?
I have been using gnus for my various email accounts for years, but now my university has moved to outlook.office365 which requires oauth2. I can see that there is an oauth2 package for emacs, but no examples on its use nor how one might combine with gnus. And while I can see some online examples of people using offlineimap oauth2 with gmail I have not seen it for MS o365. Apparently Thunderbird can use oauth2. Has anyone had success with any of the emacs email applications (but gnus preferred)? If so, can you give some suggestions please? If not, any ideas how to figure out what Thunderbird is doing so that it might be emulated in gnus. Even a simple walkthrough the oauth2 package would be helpful.
# Answer
> 1 votes
Please see the gnus-o365-oauth2 module i just posted. I'll quote the intro from the comments below.
It works, but far from perfectly, `oauth2/plstore/gnupg` stores the access tokens retrieved in an encrypted file but either the setting to have `plstore` cache the passphrase for the encrypted file doesn't work or `gnupg` keeps inventing new keys to store the access tokens under or something along those lines, whatever the cause the result is that `oauth2/plstore/gnupg` causes recurring popups to inquire about a passphrase a few times per hour. Answer something you can type quickly and tick the box to save it for the least possible inconvenience.
---
Here's the intro to the module:
# Prerequisites
`oauth2` tweaked to accept an optional function argument `read-authorization-string` for the functions that invoke `browse-url`, see this repo for now.
# Commentary
1. Obtain Office 365 tenant id:
See:
2. Set tenant id:
```
(setq gnus-o365-oauth2-tenant-id "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
```
3. Obtain client identifier:
The client-secret may very well not be called for. Ask your Exchange administrator or someone else that has access to the "App registrations experience in the Azure portal", see:
4. Set client identifier(s):
```
(setq gnus-o365-oauth2-client-id "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
(setq gnus-o365-oauth2-client-secret "xxxx")
```
5. Set custom authenticator:
```
(require 'oauth2)
(require 'gnus-o365-oauth2) ; must be loaded *after* (setq gnus-o365-oauth2-*)
(advice-add 'nnimap-login :before-until #'gnus-o365-oauth2-imap-authenticator)
```
6. Configure `plstore` (optional):
`oauth2` uses `plstore` to save access tokens in `~/emacs.d/oauth2.plstore`, which is gpg-encrypted. This allows the gpg passphrase to be cached during the Emacs session:
```
(setq plstore-cache-passphrase-for-symmetric-encryption t)
```
# Answer
> -1 votes
I have had success with gnus with the following configuration.
```
(setq message-send-mail-function 'smtpmail-send-it
smtpmail-default-smtp-server "smtp.office365.com"
smtpmail-smtp-server "smtp.office365.com"
user-mail-address "<your mail address>"
smtpmail-smtp-service 587
smtpmail-stream-type 'starttls
)
```
`(setq smtpmail-stream-type 'tls)` does not work.
I was led to try this configuration based on this info.
---
Tags: gnus, email
--- |
thread-64038 | https://emacs.stackexchange.com/questions/64038 | How to use multiple backends in priority for company-mode | 2021-03-22T08:43:56.917 | # Question
Title: How to use multiple backends in priority for company-mode
If I do
```
(setq company-backends '(company-tabnine company-capf company-yasnippet))
```
Then `company` will try `company-tabnine` to give me completions. If tabnine fails, it will try capf. If instead I do
```
(setq company-backends '((company-tabnine company-capf company-yasnippet)))
```
Then `company` will yield completions from all of the backends at once, which is what I want. I think it has some internal guidelines for how to order the completions: which appear at the top. But I want completions from tabnine always to be prioritized; at the top. Any way to achieve that?
# Answer
> 1 votes
Try using the `:separate` keyword:
```
(setq company-backends '((company-tabnine :separate company-capf company-yasnippet)))
```
---
Tags: company-mode
--- |
thread-64101 | https://emacs.stackexchange.com/questions/64101 | Table-capture doesn't handle new line | 2021-03-25T00:14:09.983 | # Question
Title: Table-capture doesn't handle new line
I'm trying to `table-capture` this in an org file
```
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
```
but I keep getting this
```
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 2| 3| 5| 7| 11| 13| 17| 19| 23|29 31|
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 37| 41| 43| 47| 53| 59| 61| 67|71 73| 79|
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 83| 89| 97| 101| 103| 107| 109| 113| 131| 137|
| | | | | | | | 127| | |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 139| 149| 151| 157| 163| 167| 173| 181| 191| 193|
| | | | | | | 179| | | |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 197| 199| 211| 223| 227| 229| 239| 241| 251| 257|
| | | | | | 233| | | | |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 263| 269| 271| 277| 281| | | | | |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
```
So at every new line, it's not recognizing the return/new line. When it asks for row delimiter I just hit enter, which is no doubt my problem. What should I give for row delimiter -- or what else am I doing wrong?
# Answer
> 2 votes
You need to specify a NEWLINE as the row delimiter regexp: you do that by typing `C-q C-j` \- the `C-q` quotes the subsequent character so that it loses its special meaning; `C-j` is a newline (the end-of-line delimited on Unix/Linux - you may have to do something different on Windows).
This is explained in the "Inserting text" section of the Emacs manual: you can get to it with `C-h i g(emacs)inserting text`.
---
Tags: org-mode, org-table
--- |
thread-64103 | https://emacs.stackexchange.com/questions/64103 | How to write documentation for saved keyboard macros? | 2021-03-25T02:52:50.050 | # Question
Title: How to write documentation for saved keyboard macros?
I have recently defined a keyboard macro using `C-x (` and `C-x)`. I then gave the keyboard macro a name using `M-x name-last-kbd-macro RET defined-kbd-macro`. And saved it to a file using `M-x insert-kbd-macro`. When I used `C-h f RET defined-kbd-macro`, under documentation it simply stated that it was a keyboard macro. Is there a way to include a doc string in `fset` command?
# Answer
As the Elisp manual describes, you can also put the documentation string into the `function-documentation` property of the symbol of the macro.
Example:
```
(fset 'defined-kbd-macro
(kmacro-lambda-form [?I ? ?a ?m ? ?a ? ?m ?a ?c ?r ?o ?.] 0 "%d"))
(put 'defined-kbd-macro 'function-documentation "My own documentation.")
```
> 4 votes
---
Tags: keyboard-macros
--- |
thread-64102 | https://emacs.stackexchange.com/questions/64102 | How to prompt to save the modified buffer before switching? | 2021-03-25T00:21:54.693 | # Question
Title: How to prompt to save the modified buffer before switching?
Vim prompts to save the buffer before switching if no other window is holding it. In other words, it prompts to save the buffer before putting it in background. How can I get the same behavior in Emacs?
A related question is about automatically saving the buffer.
# Answer
```
(defun tst-nohidden (&optional orig-fn buffer-or-name &rest _)
(let ((to-buffer (if (eq (type-of buffer-or-name) 'string) buffer-or-name (buffer-name buffer-or-name))))
;; Check if switching to or from a non-file buffer
(unless (or (equal (buffer-name) to-buffer)
(string-prefix-p "*" (string-trim-left (buffer-name)))
(if buffer-or-name (string-prefix-p "*" (string-trim-left to-buffer)) nil))
(when (and
(buffer-modified-p)
(= 1 (length (get-buffer-window-list (buffer-name) nil t)))
(y-or-n-p (format "Save %s?" (buffer-name)))
(save-buffer))))))
;; Switching buffer in current window
(advice-add 'doom-run-switch-buffer-hooks-a :before 'tst-nohidden)
;; Closing current buffer
(advice-add '+workspace/close-window-or-workspace :before 'tst-nohidden)
(defun tst-nohidden-max (&optional arg)
(dolist (buf (buffer-list))
(when (and (get-buffer-window buf 'visible) (not (eq buf (current-buffer))))
(with-current-buffer buf (tst-nohidden)))))
;; While closing other buffers
(advice-add 'doom/window-maximize-buffer :before 'tst-nohidden-max)
```
> 0 votes
---
Tags: buffers, saving
--- |
thread-64108 | https://emacs.stackexchange.com/questions/64108 | How to prompt for function use be used within a function? | 2021-03-25T10:47:02.967 | # Question
Title: How to prompt for function use be used within a function?
Consider the following example function
```
(defun simple-function ()
(dotimes (counter 10)
(input-function)))
```
This requires `input-function` to be hard coded within the definition of `simple-function`. How can I have `simple-function` prompt the user for the function that they would want to use in place of `input-function`?
# Answer
> 3 votes
One way is to use an interactive code to prompt you for the function.
```
(defun simple-function (input-function)
(interactive "aInput function: ")
(dotimes (counter 10)
(funcall input-function)))
```
then you can write your own input like this perhaps, even using the counter variable from your loop.
```
(defun myfunc ()
(message "%s: %s" counter
(read-string "string: ")))
```
To use these, type `M-x simple-function` then you should be prompted for a function name. type `myfunc`, and press Enter (`RET`), and it should prompt you 10 times for a string.
---
Tags: functions, interactive, prompt
--- |
thread-63884 | https://emacs.stackexchange.com/questions/63884 | emacs crashes at least 10 times a day | 2021-03-13T14:30:12.533 | # Question
Title: emacs crashes at least 10 times a day
9 out of 10 times it happens when invoking magit with `C-x g`.
I noticed (sometimes) pressing 'g' for refresh inside a dired buffer crashes too.
There's no error shown. My `-nw` emacsclient just lands in a corrupted shell prompt, where I have to type `reset` to even start seeing characters I type in to the shell.
```
administrator@Administrators-MacBook-Pro-2$ emacs --version
emacsclient -a -s example -nw --version
emacsclient 27.1
administrator@Administrators-MacBook-Pro-2$ brew upgrade emacs
Warning: emacs 27.1 already installed
administrator@Administrators-MacBook-Pro-2$ uname -a
Darwin Administrators-MacBook-Pro-2.local 19.6.0 Darwin Kernel Version 19.6.0: Sun Jul 5 00:43:10 PDT 2020; root:xnu-6153.141.1~9/RELEASE_X86_64 x86_64
administrator@Administrators-MacBook-Pro-2$
```
What I tried:
```
M-:
(byte-recompile-directory package-user-dir nil 'force)
```
**note** im not shown a backtrace because pretty much i get ejected to the shell.
# Answer
That gdb ninja stuff, I never got around to doing.
In hindsight, I feel I shouldn't have been running emacs 27 when brew makes 28 available.
I did a
```
brew install emacs --HEAD
```
and its been running a day without crashing.
sidenote: use-package broke after the re-install. i had to Meta-: eval some lisp to get it back up.
sidenote: the brew install broke my Postgres, and my `psql -l` shows zero of my local work databases. Instead of trying to rectify this, I'm simply going to re-download databases from a live site.
> -1 votes
---
Tags: debugging, crash
--- |
thread-64096 | https://emacs.stackexchange.com/questions/64096 | Complete a calculation ("2+3=...") inside a buffer | 2021-03-24T19:44:39.927 | # Question
Title: Complete a calculation ("2+3=...") inside a buffer
I have a calculation in my org-mode buffer:
```
7700*1/100 + 18000*2/100
```
I'm looking for the quicker way of completing it, and displaying it like this:
```
7700*1/100 + 18000*2/100 = 437
```
My current way of doing this is a little harassing.
1. do the computation with calc embedded mode: `C-x * e`
2. leave the calc embedded mode: `q`
3. Copy the result
4. Revert the change(`C-x u`), append "=" and paste the result.
What is a quicker way to accomplish the same thing?
# Answer
```
(use-package macro-math
:bind ("\C-x=" . macro-math-eval-region)
("\C-x~" . macro-math-eval-and-round-region))
```
And I have this note in my `emacs.org`:
```
NOTE: Edit macro-math.el and fix:
# ;;(delete-region beg end)
# (goto-char (region-end))
# (insert " = " rounded)
```
And there is an issue to support appending `= <result>` rather than replacing the equation with a result: https://github.com/nschum/macro-math.el/issues/2
> 2 votes
# Answer
I hastily edited a little function that does this job. The expression to be evaluated must be a region containing an expression valid for the syntax of calc. For example 1 + 2 will be evaluated and replaced by 3 and 1 + 2 =\> will be evaluated and replaced by 1 + 2 = 3. Note that Calc's precedence rules impose parentheses in some cases, to return 437 the expression 7700 * 1/100 + 18000 * 2/100 = 437 must be written 7700 * (1/100) + 18000 * (2/100). There are undoubtedly still things to be tweaked.
```
(defun evaluate-in-line (beg end)
"Evaluates the math expression from the region with calc syntax.
The expression can be ended with => or not."
(interactive (list (region-beginning) (region-end)) )
(let ((evaluation(calc-eval(substring(buffer-string) (1- beg)(1- end)))))
(when (stringp evaluation)
(kill-region beg end)
(save-excursion
(insert(with-temp-buffer
(insert evaluation)
(goto-char(point-min))
(when (search-forward "\\evalto" nil t) (replace-match "")
(search-forward "\\to" nil t)
(replace-match "="))
(buffer-string)))))))
```
Evaluate this function with C-x C-e just after the last parentheses, select a region that content an algebraic expression. M-x evaluate-in-line to proceed. If you find it handy, you can save it in your init file and bind this function to some keysstrokes.
> 1 votes
---
Tags: org-mode, calc
--- |
thread-64085 | https://emacs.stackexchange.com/questions/64085 | How to display atime, ctime and mtime of a file in the modeline? | 2021-03-24T07:44:16.310 | # Question
Title: How to display atime, ctime and mtime of a file in the modeline?
The modeline at the bottom already displays valuable information about the current buffer, like the EOL type (LF), the encoding (UTF-8)…
Now when I open a file, I would find it very handy to also display its date-time info (`atime`, `ctime`, `mtime`), preferably in a human format to know at a glimpse if I'm about to edit an old or a recent document.
# Answer
\[Partial answer: how to get the information and turn it into a string. What it does not do (yet?) is add it to the modeline; but I believe (untested and therefore maybe baseless) that this is fundamentally sound\]
The following function can be used e.g. in the `find-file-hook` to retrieve the information needed and turn it into a string - it only does it for `mtime`, but the others can be added without much difficulty (the only problem is that they are relatively long strings, so you may run out of space in the mode line):
```
(defun ndk/file-mtime ()
(let* ((fname (buffer-file-name))
(mtime (file-attribute-modification-time
(file-attributes fname))))
(when mtime
(format-time-string "%Y-%m-%dT%H:%M:%S" mtime))))
```
What remains to be done is to write a function to setq the variable `mode-line-format` to something that includes that information (TBD) - setting that variable makes it buffer-local which is what you want - and then adding the resulting function to `find-file-hook`. There is a section in the Emacs Lisp manual (`C-h i g(elisp)mode line format`) that explains how to set the variable, but it is somewhat complicated and I have not had the time to implement that. Feel free to do so and either submit an edit to this answer, or provide your own answer to complete this one.
> 1 votes
---
Tags: mode-line, time-date
--- |
thread-64114 | https://emacs.stackexchange.com/questions/64114 | How to make query-replace automatically fill what I want to replace with marked text? | 2021-03-25T17:17:41.297 | # Question
Title: How to make query-replace automatically fill what I want to replace with marked text?
I want to select some text somewhere in a buffer, call `query-replace` and then type (or paste from `kill-ring`) only the second argument, `TO-STRING`, (and make the selected text count as `FROM-STRING`).
I want a replacement to be performed within the entire buffer as well.
# Answer
> 2 votes
If you use library Replace+ (`replace+.el`) then you can just customize option `search/replace-region-as-default-flag` to non-`nil`. That gives you the region text as `FROM` text default, so you can just hit `RET` to accept that.
> **`search/replace-region-as-default-flag`** is a variable defined in `replace+.el`.
>
> Its value is `nil`
>
> Documentation:
>
> Non-`nil` means use the active region text as default for search/replace.
>
> That is, if the region is currently active then use its text as the default input. All text properties are removed from the text.
>
> Note that in this case the active region is not used to limit the search/replacement scope. But in that case you can of course just narrow the buffer temporarily to restrict the operation scope.
>
> A non-`nil` value of this option takes precedence over the use of option `search/replace-2nd-sel-as-default-flag`. To give that option precedence over using the active region, you can set this option to nil and use `region-or-non-nil-symbol-name-nearest-point` as the value of option `search/replace-default-fn`.
>
> You can customize this variable.
You can also use command `toggle-search/replace-region-as-default` anytime to toggle the option value.
---
But if you really want not to even have to hit `RET` to accept the region text then you'll need to write a command that uses that as the `FROM` arg to `query-replace` and then interactively reads the other args.
This should do that:
```
(defun my-q-r (from-string to-string
&optional delimited start end backward region-noncontiguous-p)
"Query-replace text of active region with text you're prompted for."
(interactive
(progn
(barf-if-buffer-read-only)
(let* ((from (if (use-region-p)
(buffer-substring (region-beginning) (region-end))
(query-replace-read-from "Query replace" nil)))
(to (if (consp from) (prog1 (cdr from) (setq from (car from)))
(query-replace-read-to from "Query replace" nil))))
(list from to
(or (and current-prefix-arg (not (eq current-prefix-arg '-)))
(and (plist-member (text-properties-at 0 from) 'isearch-regexp-function)
(get-text-property 0 'isearch-regexp-function from)))
(and current-prefix-arg (eq current-prefix-arg '-))))))
(deactivate-mark)
(query-replace from-string to-string delimited start end backward region-noncontiguous-p))
```
# Answer
> 1 votes
```
M-w M-< M-% C-y RET <replacement> RET !
```
does the trick.
---
Tags: region, query-replace
--- |
thread-64079 | https://emacs.stackexchange.com/questions/64079 | Latex preview not working in org-mode | 2021-03-23T22:44:59.523 | # Question
Title: Latex preview not working in org-mode
I'm following instructions on this page: https://orgmode.org/worg/org-tutorials/org-latex-preview.html. I have managed to install `dvipng` and successfully replicated the given example page as a `.png` file. Then, when I try to run `org-latex-preview` by `C-c C-x C-l` in Emacs, I get the following message:
`Creating LaTeX previews in section... done.`
However there no rendering happening anywhere. I'm running Emacs 26.3. on Ubuntu 20.04 LTS.
The value of `org-preview-latex-default-process` is `dvipng` and the value of `org-preview-latex-process-alist` is as follows:
```
Value:
((dvipng :programs
("latex" "dvipng")
:description "dvi > png" :message "you need to install the programs: latex and dvipng." :image-input-type "dvi" :image-output-type "png" :image-size-adjust
(1.0 . 1.0)
:latex-compiler
("latex -interaction nonstopmode -output-directory %o %f")
:image-converter
("dvipng -D %D -T tight -o %O %f"))
(dvisvgm :programs
("latex" "dvisvgm")
:description "dvi > svg" :message "you need to install the programs: latex and dvisvgm." :image-input-type "dvi" :image-output-type "svg" :image-size-adjust
(1.7 . 1.5)
:latex-compiler
("latex -interaction nonstopmode -output-directory %o %f")
:image-converter
("dvisvgm %f -n -b min -c %S -o %O"))
(imagemagick :programs
("latex" "convert")
:description "pdf > png" :message "you need to install the programs: latex and imagemagick." :image-input-type "pdf" :image-output-type "png" :image-size-adjust
(1.0 . 1.0)
:latex-compiler
("pdflatex -interaction nonstopmode -output-directory %o %f")
:image-converter
("convert -density %D -trim -antialias %f -quality 100 %O")))
```
The document I'm trying to render is the example given in the above link:
```
#+BEGIN_SRC latex :tangle latex/example.tex
\documentclass{article}
\begin{document}
\[
e^{i\pi} = -1
\]
\[
\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}
\]
\end{document}
#+END_SRC
```
If I press `C-u C-u C-c C-x C-l`, I receive the same message `Creating LaTeX previews in section... done.` as above and once again no rendering.
# Answer
> 2 votes
I think the example you are working from has mislead you. You can include LaTeX snippets in your org files directly, you don't need to wrap them in a src block. In fact, src blocks are ignored when org tries to preview the LaTeX snippets.
Try this:
```
* Org heading
This is an ordinary org file. The following LaTeX code can be previewed:
\[
e^{i\pi} = -1
\]
\[
\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}
\]
Latex code inside src blocks doesn't get previewed:
#+BEGIN_SRC latex :tangle latex/example.tex
\documentclass{article}
\begin{document}
\[
e^{i\pi} = -1
\]
\[
\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}
\]
\end{document}
#+END_SRC
```
# Answer
> 3 votes
Problem solved! I had to install the `texlive-latex-extra` package as I was missing some `.sty` files.
---
Tags: org-mode, latex
--- |
thread-64118 | https://emacs.stackexchange.com/questions/64118 | Newbie unable to change color scheme | 2021-03-25T21:02:04.017 | # Question
Title: Newbie unable to change color scheme
I'm a new Emacs user and am unable to successfully change the color scheme.
I have followed numerous guides, YouTube videos but have not been able to load any color scheme, some error always pops up. Many of the guides are quite old so may not pertain to the version I'm using, which is version 27.1 running on FreeBSD.
Could someone point me to a simple color scheme which I can download. tell me the correct location and provide a simple `init.el` to load it?
I tried using `http://www.nongnu.org/color-theme/` but this is over 10 years old and maybe no longer relevant
Whatever I do, whenever I run `M-x color-theme-<TAB> RET` I always get `NOT FOUND` which suggests I am unable to get a color theme package in the correct format in the correct location - I have tried many many times without success so far.
Just to stress I'm a NEWBIE and prone to make lots of mistakes.
# Answer
> 1 votes
Library `color-theme.el` is still available and still works fine. You can get a version last updated in 2019 from Emacs Wiki, here.
See Color Themes for info about color themes, including how to install and use them.
You can get existing color themes (in a `themes` folder) from https://www.nongnu.org/color-theme/. But if you use a recent Emacs version then use the version of library `color-theme.el` from Emacs Wiki, not from the `nongnu` URL. (IOW, see that URL for info and to get existing themes, but use the code from Emacs Wiki.)
---
**Color** themes are different from standard Emacs ***custom** themes*. The color-theme library is older, and the themes work differently from custom themes. Both provide support for different color *schemes*. (Yeah, the words *theme* and *scheme* are close.)
See Custom Themes for info about custom themes.
---
Tags: themes
--- |
thread-64125 | https://emacs.stackexchange.com/questions/64125 | how to call `org-attach` from a function? | 2021-03-26T03:08:11.170 | # Question
Title: how to call `org-attach` from a function?
I would like to write a function that attaches files using `org-attach`. Unfortunately, `org-attach` only seems designed to launch a "menu", and not to be used programmatically. Since it does not accept arguments, I can't just do:
```
(defun attempt1 ()
(interactive)
(org-attach "testfile.txt"))
```
I looked through the `org-attach.el` source and found a `org-attach-attach` function, which allows me to do:
```
(defun attempt2 ()
(interactive)
(org-attach-attach "testfile.txt"))
```
This works but *only after* I have called `org-attach` at least once interactively.
How can I feed a file name to `org-attach` inside a function? Alternatively, how can I make sure that `org-attach-attach` is available at startup in a "fresh" emacs session, without manually calling `org-attach` first?
# Answer
> 0 votes
Unsurprisingly, my answer can be found in the elisp manual under "Autoload":
> The autoload facility lets you register the existence of a function or macro, but put off loading the file that defines it. The first call to the function automatically loads the proper library, in order to install the real definition and other associated code, then runs the real definition as if it had been loaded all along.
An easy fix is to simply add a `require` call before my function:
```
(require org-attach)
(defun attempt2 ()
(interactive)
(org-attach-attach "testfile.txt"))
```
This makes the `org-attach-attach` function available on startup, without having to call `org-attach` manually first.
---
Tags: org-attach
--- |
thread-64133 | https://emacs.stackexchange.com/questions/64133 | Storing some text from a buffer into a variable | 2021-03-26T13:43:28.830 | # Question
Title: Storing some text from a buffer into a variable
What is the "standard" way to store some text obtained from a buffer into a variable?
The only way I could think of was to use something along the lines of `(let ((beg (point))) (end-of-line) (copy-region-as-kill beg (point)))` and then store it with something like `(setq var1 (car kill-ring))`.
That feels somehow "hacky" and I was wondering if there is another function to do this, that I overlooked?
# Answer
> 1 votes
See `C-h``i``g` `(elisp)Buffer Contents`
In short, use one of the following:
* `buffer-string`
* `buffer-substring`
* `buffer-substring-no-properties`
---
Tags: buffers, variables, string, kill-ring
--- |
thread-64131 | https://emacs.stackexchange.com/questions/64131 | Beginner - Correct usage of elisp conditionals and when: Improving code readability for org export | 2021-03-26T10:44:32.493 | # Question
Title: Beginner - Correct usage of elisp conditionals and when: Improving code readability for org export
I am exporting from org mode format to LaTeX and HTML formats. To tweak a little plain text in those formats, I am using filter functions.
If I try to use such a form of a filter function:
```
(defun filter-function-html (text backend info)
"Docstring."
(when (org-export-derived-backend-p 'latex)
(regexp-function-1)
(regexp-function-2)
(regexp-function-3)
etc ...
))
```
the same for HTML format, then simply:
```
(add-to-list 'org-export-plain-text-functions
'my-latex-filter-function
'my-html-filter-function)
```
However, this is not working. Only way I could make it work is to define each regexp as separate function and added it separately each time with `add-to-list`.
How can I improve readablity of these functions?
Specific example (lengthy):
```
(defun my-latex-filter-nobreaks (text backend info)
"Ensure \" \" are properly handled in LaTeX export."
(when (org-export-derived-backend-p backend 'latex)
(replace-regexp-in-string " \\([zuioaskvZUIOASKV]\\) " " \\1~" text)))
(defun my-latex-filter-highlightNotes-1 (text backend info)
"Highligh custom notes markup. Notes are surounded by \"%%\" or \"!!\" delimiters."
(when (org-export-derived-backend-p backend 'latex)
(replace-regexp-in-string "!!\\(.*\\)!!" "\\\\highLight[yellow]{\\1}" text)))
(defun my-latex-filter-highlightNotes-2 (text backend info)
"Highligh custom notes markup. Notes are surounded by \"%%\" or \"!!\" delimiters."
(when (org-export-derived-backend-p backend 'latex)
(replace-regexp-in-string "\\\\%\\\\%\\(.*\\)\\\\%\\\\%" "\\\\highLight[red]{\\1}" text)))
(defun my-html-filter-nobreaks (text backend info)
"Ensure \" \" are properly handled in LaTeX export."
(when (org-export-derived-backend-p backend 'html)
(replace-regexp-in-string " \\([zuioaskvZUIOASKV]\\) " " \\1 " text)))
(defun my-html-filter-highlightNotes-1 (text backend info)
"Highligh custom notes markup. Notes are surounded by \"%%\" or \"!!\" delimiters."
(when (org-export-derived-backend-p backend 'html)
(replace-regexp-in-string "!!\\(.*\\)!!" "<span style=\"background-color:yellow\">\\1</span>" text)))
(defun my-html-filter-highlightNotes-2 (text backend info)
"Highligh custom notes markup. Notes are surounded by \"%%\" or \"!!\" delimiters."
(when (org-export-derived-backend-p backend 'html)
(replace-regexp-in-string "%%\\(.*\\)%%" "<span style=\"background-color:red\">\\1</span>" text)))
(add-to-list 'org-export-filter-plain-text-functions
'my-latex-filter-nobreaks)
(add-to-list 'org-export-filter-plain-text-functions
'my-latex-filter-highlightNotes-1)
(add-to-list 'org-export-filter-plain-text-functions
'my-latex-filter-highlightNotes-2)
(add-to-list 'org-export-filter-plain-text-functions
'my-html-filter-nobreaks)
(add-to-list 'org-export-filter-plain-text-functions
'my-html-filter-highlightNotes-1)
(add-to-list 'org-export-filter-plain-text-functions
'my-html-filter-highlightNotes-2)
```
which I would like to shrink to:
```
(defun my-latex-filter-nobreaks (text backend info)
"Ensure \" \" are properly handled in LaTeX export."
(when (org-export-derived-backend-p backend 'latex)
(replace-regexp-in-string " \\([zuioaskvZUIOASKV]\\) " " \\1~" text)
(replace-regexp-in-string "!!\\(.*\\)!!" "\\\\highLight[yellow]{\\1}" text)
(replace-regexp-in-string "\\\\%\\\\%\\(.*\\)\\\\%\\\\%" "\\\\highLight[red]{\\1}" text)))
(defun my-html-filter-nobreaks (text backend info)
"Ensure \" \" are properly handled in LaTeX export."
(when (org-export-derived-backend-p backend 'html)
(replace-regexp-in-string " \\([zuioaskvZUIOASKV]\\) " " \\1 " text)
(replace-regexp-in-string "!!\\(.*\\)!!" "<span style=\"background-color:yellow\">\\1</span>" text)
(replace-regexp-in-string "%%\\(.*\\)%%" "<span style=\"background-color:red\">\\1</span>" text)))
(add-to-list 'org-export-filter-plain-text-functions
'my-latex-filter-nobreaks
'my-html-filter-nobreaks)
```
File for testing:
```
* Test for code readability improving
This is a test. A beginner here. !!Custom yellow markup.!! %%Custom red markup.%%
```
# Answer
The problem with your code is that you are applying different replacement functions to the *same* original text. The result is, the value returned is just the result of the final replacement applied to the original text. You need to accumulate changes. One way to do this is:
```
(defun my-latex-filter-highlightNotes (text backend info)
"Highligh custom notes markup. Notes are surounded by \"%%\" or \"!!\" delimiters."
(when (org-export-derived-backend-p backend 'latex)
(setq text ;; update the value of text
(replace-regexp-in-string "!!\\(.*\\)!!" "\\\\highLight[yellow]{\\1}" text))
(setq text ;; update the value of text again!
(replace-regexp-in-string "\\\\%\\\\%\\(.*\\)\\\\%\\\\%" "\\\\highLight[red]{\\1}" text))))
```
> 4 votes
---
Tags: org-mode, org-export, latex
--- |
thread-64132 | https://emacs.stackexchange.com/questions/64132 | Using a number in register as prefix argument | 2021-03-26T11:15:09.257 | # Question
Title: Using a number in register as prefix argument
How can I use a number in a register after `C-u` ?
For example my register looks like `1: 24`, and I want to do `C-u 24 x`.
# Answer
This should do the trick.
```
(defun reg-as-pref-arg (register)
"Use numeric register as prefix arg for next command
You are prompted for the register, showing preview of registers."
(interactive (list (register-read-with-preview "Increment register: ")))
(let ((reg-val (get-register register)))
(when (numberp reg-val)
(setq prefix-arg reg-val))))
```
E.g.:
```
C-u 42 C-x r n a ; Put 42 in register `a'
M-x reg-as-pref-arg a X ; Use 42 as prefix arg for command to insert `X': 42 X's
```
Bind it to a key.
```
(global-set-key (kbd "C-o") #'reg-as-pref-arg)
```
Then use it.
```
C-o a X ; Insert 42 X's.
C-o a C-M-f ; Move forward 42 words.
```
> 1 votes
---
Tags: prefix-argument, registers
--- |
thread-64136 | https://emacs.stackexchange.com/questions/64136 | Flymake colouring? | 2021-03-26T14:32:47.320 | # Question
Title: Flymake colouring?
I've recently updated my Emacs from 26 to 27, and now the Flymake error indicators are very hard to see - they're now in a very pale rose instead of crimson red. How can I change the colour back? I've searched the documentation and also looked at the code a little (I'm no Lisp programmer, though), but could not find it. So far, the two affected regions are the margin with the error indicators, and the status bar which also displays the buffer name, editing mode etc.
# Answer
1. Put your cursor on (just before) a character that has the colored text, and use `C-u C-x =` (command `what-cursor-position`).
2. Near the bottom of the `*Help*` buffer you'll see the name of the face(s) used on that character.
3. `M-x customize-face` and enter then name of the face. Customize it to change the foreground or background color etc. Save your customizations.
`C-h k C-x =` tells us:
> **`C-x =`** runs the command `what-cursor-position` (found in `global-map`), which is an interactive compiled Lisp function in `simple.el`.
>
> It is bound to `C-x =`.
>
> `(what-cursor-position &optional DETAIL)`
>
> Print info on cursor position (on screen and within buffer).
>
> Also describe the character after point, and give its character code in octal, decimal and hex.
>
> For a non-ASCII multibyte character, also give its encoding in the buffer's selected coding system if the coding system encodes the character safely. If the character is encoded into one byte, that code is shown in hex. If the character is encoded into more than one byte, just "..." is shown.
>
> In addition, **with prefix argument, show details about that character in `*Help*` buffer.** See also the command `describe-char`.
You later commented that the chars are displayed in an area (e.g. margin) where you can't put the cursor. In that case, you can try visually matching their face against the faces you see in `M-x list-faces-display`. That's usually sufficient.
Otherwise, look in the flymake Lisp code to see what faces it defines and what their default appearances are.
> 0 votes
---
Tags: faces, help, flymake, customize-face
--- |
thread-17622 | https://emacs.stackexchange.com/questions/17622 | How can I walk an org-mode tree? | 2015-10-24T05:47:03.873 | # Question
Title: How can I walk an org-mode tree?
### Background
I'm writing a presentation mode for Emacs. I'd like the input to be org files, as org files are great for data.
### Problem
I have to convert the org mode file into a list of "slide" data structures that I can iterate through. To do this, I'd like to take something like the following org-mode file:
```
* this is the first headline, with a title property and no contents
* this is the second headline, with contents
- dash list nested under the second headline
- further nested
** nested headline
```
and be able to walk it. I've tried `(org-element-parse-buffer)`, and that does give me a list of elements, but it's hard to figure out how to walk further in them. For example, calling `(org-element-map (org-element-parse-buffer) 'headline #'identity)` gives a list of *three* elements; the last one represents the "nested headline". I want "nested headline" to be a child of "this is the second headline, with contents".
### Avoiding the XY problem
I'm certainly open to other ways of converting an org-mode file into an Elisp data structure. I don't *think* org-export is the right tool for me, because I don't want to end up with a new file containing the results, but a data structure I can iterate through. My naive way is something like "give me all the top-level headlines, and then I can get their properties and contained elements (e.g., plain text or nested lists -- whether further headlines or dash lists)".
# Answer
> 8 votes
I had a similar problem, so maybe this will help - I'm not very familiar with org export or org internals, but I couldn't find anything that would parse an org file to a tree structure. But given a buffer like
```
* england
** london
** bristol
* france
```
it will give you
```
(org-get-header-tree) => ("england" ("london" "bristol") "france")
```
and can include other information from the tree as well.
---
So given a flat list of levels we need to produce a tree, e.g. (1 1 2 3 1) =\> (1 1 (2 (3)) 1). I couldn't find a function that would do this either so wrote one after much drawing of cons cells - I'm sure there's a better way of doing this but it works. The function `unflatten` takes a flat list and couple of functions to extract the information you want from the list and the item levels and produces a tree structure.
In `org-get-header-list` you could add more information you want to extract from each item with calls to `org-element-property`, and then in `org-get-header-tree` you could include functions to extract the information from the list.
As it stands this doesn't include handling for dash lists, but maybe it could be adapted to handle those also without too much trouble...
```
(defun unflatten (xs &optional fn-value fn-level)
"Unflatten a list XS into a tree, e.g. (1 2 3 1) => (1 (2 (3)) 1).
FN-VALUE specifies how to extract the values from each element, which
are included in the output tree, FN-LEVEL tells how to extract the
level of each element. By default these are the `identity' function so
it will work on a list of numbers."
(let* ((level 1)
(tree (cons nil nil))
(start tree)
(stack nil)
(fn-value (or fn-value #'identity))
(fn-level (or fn-level #'identity)))
(dolist (x xs)
(let ((x-value (funcall fn-value x))
(x-level (funcall fn-level x)))
(cond ((> x-level level)
(setcdr tree (cons (cons x-value nil) nil))
(setq tree (cdr tree))
(push tree stack)
(setq tree (car tree))
(setq level x-level))
((= x-level level)
(setcdr tree (cons x-value nil))
(setq tree (cdr tree)))
((< x-level level)
(while (< x-level level)
(setq tree (pop stack))
(setq level (- level 1)))
(setcdr tree (cons x-value nil))
(setq tree (cdr tree))
(setq level x-level)))))
(cdr start)))
; eg (unflatten '(1 2 3 2 3 4)) => '(1 (2 (3) 2 (3 (4))))
(defun org-get-header-list (&optional buffer)
"Get the headers of an org buffer as a flat list of headers and levels.
Buffer will default to the current buffer."
(interactive)
(with-current-buffer (or buffer (current-buffer))
(let ((tree (org-element-parse-buffer 'headline)))
(org-element-map
tree
'headline
(lambda (el) (list
(org-element-property :raw-value el) ; get header title without tags etc
(org-element-property :level el) ; get depth
;; >> could add other properties here
))))))
; eg (org-get-header-list) => (("pok" 1) ("lkm" 1) (("cedar" 2) ("yr" 2)) ("kjn" 1))
(defun org-get-header-tree (&optional buffer)
"Get the headers of the given org buffer as a tree."
(interactive)
(let* ((headers (org-get-header-list buffer))
(header-tree (unflatten headers
(lambda (hl) (car hl)) ; extract information to include in tree
(lambda (hl) (cadr hl))))) ; extract item level
header-tree))
; eg (org-get-header-tree) => ("pok" "lkm" ("cedar" "yr") "kjn")
```
# Answer
> 1 votes
Parsing an Org-mode file requires knowing two things: the structure of the OrgNode, and how to recursively walk a tree. OrgNodes come in two forms:
1. `(element-type (plist-of-properties) (child-1 OrgNode) (child-2 OrgNode) ... (child-n OrgNode))`
or
2. `#("secondary-string" beg end (plist) ...)`
The `org-element.el` function `org-element-parse-buffer` returns an OrgNode root, `org-data`, which can be recursively walked. To do this, use the `org-element.el` function `org-element-contents` to return a list of child OrgNodes which can be iterated through very easily.
The difficulty in getting values out of an OrgNode is knowing that sometimes it is an OrgNode and sometimes a secondary string. If you don't test for the string, your code will often throw an error.
This code has three parts:
1. Obtain an OrgNode and parse some of its contents
2. Print some of the contents
3. Recurse though the OrgNode child nodes using the Preorder Traversal algorithm
You can of course obtain whatever values out of the OrgNode you specifically need and print them however you want. The Preorder Traversal algorithm is straight out of a textbook, but requires that you check for a list so as not to try to recurse into a secondary string, which will simply throw an error.
Once you see how an OrgTree is constructed, and the OrgNodes look, then the `org-element.el` mapping function `org-element-map` becomes easy to use.
> ```
> (defun org-tree-traversal (org-node level)
> "Call this function with ORG-NODE being a completely parsed buffer
> from org-element-parse-buffer and LEVEL being 0 (zero)."
>
> ;; I. PARSE AN ORG-NODE CONTENTS
>
> (let*
> ((type (org-element-type org-node))
> (class (org-element-class org-node))
> (contents (org-element-contents org-node))
> (props ; must be careful not to parse into a secondary string here
> (if (consp org-node)
> (second org-node) ; the properties exist and are a plist
> org-node)) ; the org-node is a secondary string
> (value (or (plist-get props :raw-value)
> (plist-get props :value)
> (and (stringp props) ; now get the string value for string
> (string-trim props))))
> (key (when
> (and (consp props) ; make sure props is a plist, not a string
> (not (null value)))
> (let ((key (plist-get props :key)))
> (setf value (format "%s: %s" (if key key "VALUE") value)))))
> (level-indent (make-string level 32))
> (level-indent-dot (make-string level ?.)))
>
> ;; II. PRINT THE ORG-NODE CONTENTS
>
> (princ
> (format "%2d]%s%s (%s) %s\n"
> level
> level-indent-dot
> type
> class
> (unless
> (stringp props)
> (_prop-keys props)))) ; this is a utility function that prints
> ; all of the keys from the plist as a
> ; string; it can be omitted.
> (when value
> (princ (format " %s%s\n" level-indent value)))
> (terpri)
>
> ;; III. RECURSE THROUGH THE ORG-NODE CHILD NODES
>
> (if (listp contents) ; don't try to recurse into a secondary string
> (let ((child (first contents))
> (children (rest contents)))
> (while child
> (org-tree-traversal child (1+ level)) ; recurse
> (setf child (first children))
> (setf children (rest children))))))
>
> t) ; RETURN TRUE WHEN DONE
>
> ```
> ```
> (defun walk-org-tree (org-buf)
> "Walk an OrgTree from the Org buffer `ORG-BUF'.
> Default is the current buffer."
>
> (interactive "bBuffer to parse: ")
> (with-temp-buffer-window "*OrgTree*" nil nil
> (org-tree-traversal
> (parse-org-buffer org-buf) 0)))
>
> ;; USAGE: (walk-org-tree "<org-buffer>.org")
> ;; or
> ;; M-x walk-org-tree <RET> [<org-buffer>.org] | <RET> for current buffer
>
> ```
# Answer
> 0 votes
I made a very simple minor-mode for 'walking' through an org file. It doesn't require parsing the buffer at all, it just provides some shortcuts for moving from one narrowed subtree to the next/previous subtree.
```
(defun tws-present ()
(interactive)
(org-narrow-to-subtree))
(defun tws-present-next (ARG)
(interactive "p")
(beginning-of-buffer)
(widen)
(outline-forward-same-level ARG)
(org-narrow-to-subtree))
(defun tws-present-previous (ARG)
(interactive "p")
(beginning-of-buffer)
(widen)
(outline-backward-same-level ARG)
(org-narrow-to-subtree))
(defvar org-demo-minor-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-<down>") 'tws-present-next)
(define-key map (kbd "C-<up>") 'tws-present-previous)
(define-key map (kbd "C-c C-s") 'tws-present)
(define-key map (kbd "C-c C-q") 'org-demo-minor-mode)
map))
(define-minor-mode org-demo-minor-mode
"A minor mode for presenting org files as slides.
Very basic - narrows to current subtree, and provides navigation keys for
moving forwards and backwards through the file. Should probably also allow
for increasing font size?"
nil nil
:lighter " DEMO"
(if org-demo-minor-mode
(org-narrow-to-subtree)
(widen))
)
```
---
Tags: org-mode
--- |
thread-64145 | https://emacs.stackexchange.com/questions/64145 | Showing full (unabbreviated) Python output in Org Mode | 2021-03-26T20:08:07.273 | # Question
Title: Showing full (unabbreviated) Python output in Org Mode
The result of a certain Python (statsmodel module) code in org-mode is abbreviated:
```
#+BEGIN_SRC python
import pandas as pd
import statsmodels.api as sm
auto_df=pd.read_csv('Auto.csv', usecols= ['mpg', 'horsepower'], na_values= ['?'])
auto_df['horsepower'] = pd.to_numeric(auto_df['horsepower'])
auto_df.dropna(inplace=True)
X = auto_df['horsepower']
X = sm.add_constant(X)
olsmod = sm.OLS(auto_df['mpg'], X)
olsres = olsmod.fit()
pred = olsres.get_prediction([1,98])
return(pred.summary_frame())
#+END_SRC
#+RESULTS:
: mean mean_se ... obs_ci_lower obs_ci_upper
: 0 24.467077 0.251262 ... 14.809396 34.124758
:
: [1 rows x 6 columns]
```
I'm referring to the ellipses in the table below `#+Results`.
How can I see the full results table?
A comment suggested this could be a a pandas issue, but I don't think so since the output is from a statsmodels function.
And I don't think it's because of statsmodels because here, the full is `pred.summary_frame()` results table is shown:
```
#+BEGIN_SRC python
import pandas as pd
import statsmodels.api as sm
import numpy as np
nsample = 50
sig = 0.25
X = np.linspace(0, 20, nsample)
X = sm.add_constant(X)
beta = [5., 0.5]
y_true = np.dot(X, beta)
y = y_true + sig * np.random.normal(size=nsample)
olsmod = sm.OLS(y, X)
olsres = olsmod.fit()
pred = olsres.get_prediction([1,17])
return(pred.summary_frame())
#+END_SRC
#+RESULTS:
: mean mean_se mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper
: 0 13.559089 0.0522 13.454134 13.664043 13.069874 14.048303
```
One more note, the abbreviate one, from my first example, shows fully in the python shell.
# Answer
> 1 votes
This is almost certainly a pandas "feature" and has nothing to do with Org mode, as pointed out in a comment. The following modification to the code produces untruncated output for me:
```
#+BEGIN_SRC python
import pandas as pd
import statsmodels.api as sm
import numpy as np
# tell pandas to not worry about truncation
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
# and to not worry about the width of the "screen"
pd.set_option('display.width', None)
nsample = 50
sig = 0.25
X = np.linspace(0, 20, nsample)
X = sm.add_constant(X)
beta = [5., 0.5]
y_true = np.dot(X, beta)
y = y_true + sig * np.random.normal(size=nsample)
olsmod = sm.OLS(y, X)
olsres = olsmod.fit()
pred = olsres.get_prediction([1,17])
return(pred.summary_frame())
#+END_SRC
#+RESULTS:
: mean mean_se mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper
: 0 13.406873 0.049386 13.307576 13.50617 12.944031 13.869715
```
The alignment however is bad: org-babel takes the result, stringifies it and writes it to a temporary file. Since it's just a string, it just gets printed out.
EDIT: I can get good alignment too with a `:results drawer` header:
```
#+BEGIN_SRC python :results drawer
... no changes to the program ...
#+END_SRC
#+RESULTS:
:results:
mean mean_se mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper
0 13.439094 0.049308 13.339955 13.538234 12.976986 13.901202
:end:
```
---
Tags: org-mode, python
--- |
thread-64109 | https://emacs.stackexchange.com/questions/64109 | TODO item for paying credit card bill 3 weeks after statement date | 2021-03-25T12:43:49.120 | # Question
Title: TODO item for paying credit card bill 3 weeks after statement date
My credit card bill is due 3 weeks after the statement date. The statement date is always the 20th of the month. Due to the variable lengths of months, the due date is not always on the same day.
I'd like to have a TODO item with a time stamp on the credit card bill's due date. How can I do this in org? I know that I could enter 12 different entries for a year. I'm after a single TODO entry with a +1m indicating to roll the rule over to the next month, every month.
# Answer
> 1 votes
I'll hazard a guess what you mean and show one simple way of getting answers to your problem in an org-mode buffer.
Put your statement dates in an org-mode table like below. The dates have to be in a format that org-mode recognises. Here they are inactive dates without time string. Place the cursor in the formula line under the table and press `C-c C-c` to calculate the due dates 20 days later.
```
| Statement date | Due date |
|------------------+----------|
| [2021-04-20 Tue] | |
| [2021-05-20 Thu] | |
| [2021-06-20 Sun] | |
#+TBLFM: $2=$1+20;
```
---
Tags: org-mode, time-date
--- |
thread-63895 | https://emacs.stackexchange.com/questions/63895 | Switching default locale of Orgmode-generated output | 2021-03-14T13:51:35.560 | # Question
Title: Switching default locale of Orgmode-generated output
Suggestions for a better title are welcome.
Essentially, I want to use Org to write in Ukrainian.
Yet, when I export it (pdf or odt) I get:
> Figure 1: Контекстна діаграма
How can I customize Emacs to get the output, so that I could get Рисунок written instead of Figure ?:
> Рисунок 1: Контекстна діаграма
or, to go even further, to get:
> Рисунок 1 - Контекстна діаграма
True, I can do manual "replace all" in LibreOffice, but this is inconvenient and does not account for other cases when I need to influence Org export behavior. I am fairly new to Org mode (haven't read the whole manual yet), but which support does Org provide for other languages / locales?
Could you point me to where this is documented?
# Answer
You need to add an entry to `org-export-dictionary`.
Down below you see a list of entries for russian language. (I chose russian because the ukrainian word for figure--Рисунок--matches with the russian word for it).
If you are happy with existing russian entries, the easiest way out for you will be to use `#+LANGUAGE: ru`.
```
(("Author"
:html "Автор"
:utf-8 "Автор")
("Continued from previous page"
:html "(Продолжение)"
:utf-8 "(Продолжение)")
("Continued on next page"
:html "(Продолжение следует)"
:utf-8 "(Продолжение следует)")
("Created")
("Date"
:html "Дата"
:utf-8 "Дата")
("Equation"
:html "Уравнение"
:utf-8 "Уравнение")
("Figure"
:html "Рисунок"
:utf-8 "Рисунок")
("Figure %d:"
:html "Рис. %d.:"
:utf-8 "Рис. %d.:")
("Footnotes"
:html "Сноски"
:utf-8 "Сноски")
("List of Listings"
:html "Список распечаток"
:utf-8 "Список распечаток")
("List of Tables"
:html "Список таблиц"
:utf-8 "Список таблиц")
("Listing"
:html "Распечатка"
:utf-8 "Распечатка")
("Listing %d:"
:html "Распечатка %d.:"
:utf-8 "Распечатка %d.:")
("References")
("See figure %s")
("See listing %s")
("See section %s"
:html "См. раздел %s"
:utf-8 "См. раздел %s")
("See table %s")
("Table"
:html "Таблица"
:utf-8 "Таблица")
("Table %d:"
:html "Таблица %d.:"
:utf-8 "Таблица %d.:")
("Table of Contents"
:html "Содержание"
:utf-8 "Содержание")
("Unknown reference"
:html "Неизвестная ссылка"
:utf-8 "Неизвестная ссылка"))
```
I generated the above list using
```
(progn
(require 'cl-lib)
(let ((lang "ru"))
(cl-loop for (string . entry) in (cdr org-export-dictionary)
collect (cons string (assoc-default lang entry)))))
```
Here is a list of English strings that may have to be translated to ukraininan
```
(
"Author"
"Continued from previous page"
"Continued on next page"
"Created"
"Date"
"Equation"
"Figure"
"Figure %d:"
"Footnotes"
"List of Listings"
"List of Tables"
"Listing"
"Listing %d:"
"References"
"See figure %s"
"See listing %s"
"See section %s"
"See table %s"
"Table"
"Table %d:"
"Table of Contents"
"Unknown reference"
)
```
I generated above list with
```
(progn
(require 'cl-lib)
(cl-loop for (string . entry) in (cdr org-export-dictionary)
collect string))
```
The code you are looking for is in `ox.el`. See https://github.com/emacsmirror/org/blob/49364f904b793513112fb8f71dd6b7f6274171cf/lisp/ox.el#L5720
If you are uncomfortable with Emacs Lisp, no need to worry. You can proceed intuitively.
Do the following
1. `C-h v org-export-dictionary`. And click on `ox.el` link in the resulting help buffer.
2. Copy-paste the "ru" lines and modify the russian strings to ukranian ones, and remembering to replace "ru" with "uk". (You may have to change the `read-only` status of `ox.el` file.). To keep things simpler, you don't have to add new ukraininan lines. Just modify the russian strings to your taste.
3. Once you have done that do `M-x load-library ox.el`.
4. Export your file.
5. If you are happy with results, you can do `C-x C-f ox.el` and `M-x byte-compile-file`, and then restart Emacs.
If you provide me ukrainian translation for above English strings, I can give you a Elisp recipe for modifying `org-export-dictionary` with ukrainian entries. You can add this recipe to your `.emacs`.
Regarding using a hyphen instead of a colon in captions, I *believe*--I haven't looked at the code. The docstring of the variable is not that helpful--you need to alter the first entry in `org-export-dictionary` or provide a ukrainian one for it.
```
("%e %n: %c"
("fr":default "%e %n : %c"
:html "%e %n : %c"))
```
> 0 votes
# Answer
Here is the recipe for adding a custom language.
```
(defun org-export-dictionary--add-language (lang data)
(unless (boundp 'org-export-dictionary)
(require 'ox))
(cl-loop for (string . entry) in data do
(let ((current-entry (assoc string org-export-dictionary))
(new-entry (when entry (cons lang (if (stringp entry) (list :default entry) entry)))))
(when (and new-entry current-entry)
(nconc (cdr current-entry) (list new-entry))))))
```
Here I add a custom language called `custom2`. The translation strings here are quite elaborate.
```
(org-export-dictionary--add-language
"custom2"
'(("%e %n: %c" :default "%e %n : %c" :html "%e %n : %c")
("junk" :default "test")
("Author" :default "Auteur")
("Continued from previous page" :default "Suite de la page précédente")
("Continued on next page" :default "Suite page suivante")
("Created")
("Date")
("Equation" :ascii "Equation" :default "Équation")
("Figure")
("Figure %d:" :default "Figure %d :" :html "Figure %d :")
("Footnotes" :default "Notes de bas de page")
("List of Listings" :default "Liste des programmes")
("List of Tables" :default "Liste des tableaux")
("Listing" :default "Programme" :html "Programme")
("Listing %d:" :default "Programme %d :" :html "Programme %d :")
("References" :ascii "References" :default "Références")
("See figure %s" :default "cf. figure %s" :html "cf. figure %s" :latex "cf.~figure~%s")
("See listing %s" :default "cf. programme %s" :html "cf. programme %s" :latex "cf.~programme~%s")
("See section %s" :default "cf. section %s")
("See table %s" :default "cf. tableau %s" :html "cf. tableau %s" :latex "cf.~tableau~%s")
("Table" :default "Tableau")
("Table %d:" :default "Tableau %d :")
("Table of Contents" :ascii "Sommaire" :default "Table des matières")
("Unknown reference" :ascii "Destination inconnue" :default "Référence inconnue")))
```
Here I add a custom language called `"custom"`. The translation strings are simple. The snippet below is what you want to use. Replace, `"custom"` with `"uk"` and `"FIGURE"` with `"Рисунок"`. Add translations for other entries.
```
(org-export-dictionary--add-language
"custom"
'(("%e %n: %c" . "%e %n - %c")
("Author" . "AUTHOR")
("Continued from previous page" . "CONTINUED FROM PREVIOUS PAGE")
("Continued on next page" . "CONTINUED ON NEXT PAGE")
("Created" . "CREATED")
("Date" . "DATE")
("Equation" . "EQUATION")
("Figure" . "FIGURE")
("Figure %d:" . "FIGURE %d:")
("Footnotes" . "FOOTNOTES")
("List of Listings" . "LIST OF LISTINGS")
("List of Tables" . "LIST OF TABLES")
("Listing" . "LISTING")
("Listing %d:" . "LISTING %d:")
("References" . "REFERENCES")
("See figure %s" . "SEE FIGURE %s")
("See listing %s" . "SEE LISTING %s")
("See section %s" . "SEE SECTION %s")
("See table %s" . "SEE TABLE %s")
("Table" . "TABLE")
("Table %d:" . "TABLE %d:")
("Table of Contents" . "TABLE OF CONTENTS")
("Unknown reference" . "UNKNOWN REFERENCE"))
)
```
For your specific query, here is the snippet in it's simplest form.
I obtained this snippet by replacing `"custom"` above with `"uk"`, `"FIGURE"` with `"Рисунок"` and `"%e %n: %c"` with `"%e %n - %c"`. I have also removed other entries you(?) don' care about. Note that `colon` is replaced with `hyphen` in the caption format.
```
(org-export-dictionary--add-language
"uk"
'(("%e %n: %c" . "%e %n - %c")
("Figure" . "Рисунок"))
)
```
Now when I export this snippet, I get the desired behaviour in ODT export.
```
#+LANGUAGE: uk
# #+LANGUAGE: custom
This is some text
#+CAPTION: My Profile Photo
[[./photo.png]]
#+CAPTION: My Test Scores
| Physics | 50 |
| Chemistry | 70 |
```
For the sake of completion, here is a list of strings used *exclusively* by ODT exporter.
```
(delete-dups
`("Table of Contents"
;; List of CATEGORY-NAMEs
,@(cl-loop for x in org-odt-category-map-alist collect (nth 3 x))
;; List of format specifiers in LABEL-STYLEs
,@(apply 'append (cl-loop for label-style in
(cl-loop for x in org-odt-category-map-alist
collect (nth 2 x))
collect (list (nth 1 (assoc-string label-style org-odt-label-styles t))
(nth 3 (assoc-string label-style org-odt-label-styles t)))))))
```
which gives the following list
```
("Table of Contents" "Table" "Figure" "Equation" "Listing" "%e %n: %c" "%n" "%c" "(%n)")
```
FWIW, ODT uses `:utf-8` entries for translation.
---
*A word of caution regarding `org-export-dictionary--add-language`*: This will work when adding a *new* language. But you may run in to problems when you want to *override* the entries for a *existing* language or you want to *augment* an existing entry for a language. Read on for what this comments means ...
This is what the snippet does to value of `org-export-dictionary`
```
--- a.el 2021-03-27 13:52:11.108743913 +0530
+++ b.el 2021-03-27 13:52:47.721764029 +0530
@@ -1,5 +1,8 @@
(("%e %n: %c"
- ("fr" :default "%e %n : %c" :html "%e %n : %c"))
+ ("fr" :default "%e %n : %c" :html "%e %n : %c")
+ ("custom2" :default "%e %n : %c" :html "%e %n : %c")
+ ("custom" :default "%e %n - %c")
+ ("uk" :default "%e %n - %c"))
("Author"
("ar" :default "تأليف")
("ca" :default "Autor")
@@ -27,7 +30,9 @@
("sv" :html "Författare")
("uk" :html "Автор" :utf-8 "Автор")
("zh-CN" :html "作者" :utf-8 "作者")
- ("zh-TW" :html "作者" :utf-8 "作者"))
+ ("zh-TW" :html "作者" :utf-8 "作者")
+ ("custom2" :default "Auteur")
+ ("custom" :default "AUTHOR"))
("Continued from previous page"
("ar" :default "تتمة الصفحة السابقة")
("cs" :default "Pokračování z předchozí strany")
@@ -41,7 +46,9 @@
("pt_BR" :html "Continuação da página anterior" :ascii "Continuacao da pagina anterior" :default "Continuação da página anterior")
("ro" :default "Continuare de pe pagina precedentă")
("ru" :html "(Продолжение)" :utf-8 "(Продолжение)")
- ("sl" :default "Nadaljevanje s prejšnje strani"))
+ ("sl" :default "Nadaljevanje s prejšnje strani")
+ ("custom2" :default "Suite de la page précédente")
+ ("custom" :default "CONTINUED FROM PREVIOUS PAGE"))
("Continued on next page"
("ar" :default "التتمة في الصفحة التالية")
("cs" :default "Pokračuje na další stránce")
@@ -55,13 +62,16 @@
("pt_BR" :html "Continua na próxima página" :ascii "Continua na proxima pagina" :default "Continua na próxima página")
("ro" :default "Continuare pe pagina următoare")
("ru" :html "(Продолжение следует)" :utf-8 "(Продолжение следует)")
- ("sl" :default "Nadaljevanje na naslednji strani"))
+ ("sl" :default "Nadaljevanje na naslednji strani")
+ ("custom2" :default "Suite page suivante")
+ ("custom" :default "CONTINUED ON NEXT PAGE"))
("Created"
("cs" :default "Vytvořeno")
("nl" :default "Gemaakt op")
("pt_BR" :default "Criado em")
("ro" :default "Creat")
- ("sl" :default "Ustvarjeno"))
+ ("sl" :default "Ustvarjeno")
+ ("custom" :default "CREATED"))
("Date"
("ar" :default "بتاريخ")
("ca" :default "Data")
@@ -88,7 +98,8 @@
("sv" :default "Datum")
("uk" :html "Дата" :utf-8 "Дата")
("zh-CN" :html "日期" :utf-8 "日期")
- ("zh-TW" :html "日期" :utf-8 "日期"))
+ ("zh-TW" :html "日期" :utf-8 "日期")
+ ("custom" :default "DATE"))
("Equation"
("ar" :default "معادلة")
("cs" :default "Rovnice")
@@ -108,7 +119,9 @@
("ru" :html "Уравнение" :utf-8 "Уравнение")
("sl" :default "Enačba")
("sv" :default "Ekvation")
- ("zh-CN" :html "方程" :utf-8 "方程"))
+ ("zh-CN" :html "方程" :utf-8 "方程")
+ ("custom2" :ascii "Equation" :default "Équation")
+ ("custom" :default "EQUATION"))
("Figure"
("ar" :default "شكل")
("cs" :default "Obrázek")
@@ -127,7 +140,9 @@
("ro" :default "Imaginea")
("ru" :html "Рисунок" :utf-8 "Рисунок")
("sv" :default "Illustration")
- ("zh-CN" :html "图" :utf-8 "图"))
+ ("zh-CN" :html "图" :utf-8 "图")
+ ("custom" :default "FIGURE")
+ ("uk" :default "Рисунок"))
("Figure %d:"
("ar" :default "شكل %d:")
("cs" :default "Obrázek %d:")
@@ -148,7 +163,9 @@
("ru" :html "Рис. %d.:" :utf-8 "Рис. %d.:")
("sl" :default "Slika %d")
("sv" :default "Illustration %d")
- ("zh-CN" :html "图%d " :utf-8 "图%d "))
+ ("zh-CN" :html "图%d " :utf-8 "图%d ")
+ ("custom2" :default "Figure %d :" :html "Figure %d :")
+ ("custom" :default "FIGURE %d:"))
("Footnotes"
("ar" :default "الهوامش")
("ca" :html "Peus de pàgina")
@@ -176,7 +193,9 @@
("sv" :default "Fotnoter")
("uk" :html "Примітки" :utf-8 "Примітки")
("zh-CN" :html "脚注" :utf-8 "脚注")
- ("zh-TW" :html "腳註" :utf-8 "腳註"))
+ ("zh-TW" :html "腳註" :utf-8 "腳註")
+ ("custom2" :default "Notes de bas de page")
+ ("custom" :default "FOOTNOTES"))
("List of Listings"
("ar" :default "قائمة بالبرامج")
("cs" :default "Seznam programů")
@@ -192,7 +211,9 @@
("pt_BR" :html "Índice de Listagens" :default "Índice de Listagens" :ascii "Indice de Listagens")
("ru" :html "Список распечаток" :utf-8 "Список распечаток")
("sl" :default "Seznam programskih izpisov")
- ("zh-CN" :html "代码目录" :utf-8 "代码目录"))
+ ("zh-CN" :html "代码目录" :utf-8 "代码目录")
+ ("custom2" :default "Liste des programmes")
+ ("custom" :default "LIST OF LISTINGS"))
("List of Tables"
("ar" :default "قائمة بالجداول")
("cs" :default "Seznam tabulek")
@@ -213,7 +234,9 @@
("ru" :html "Список таблиц" :utf-8 "Список таблиц")
("sl" :default "Seznam tabel")
("sv" :default "Tabeller")
- ("zh-CN" :html "表格目录" :utf-8 "表格目录"))
+ ("zh-CN" :html "表格目录" :utf-8 "表格目录")
+ ("custom2" :default "Liste des tableaux")
+ ("custom" :default "LIST OF TABLES"))
("Listing"
("ar" :default "برنامج")
("cs" :default "Program")
@@ -231,7 +254,9 @@
("ro" :default "Lista")
("ru" :html "Распечатка" :utf-8 "Распечатка")
("sl" :default "Izpis programa")
- ("zh-CN" :html "代码" :utf-8 "代码"))
+ ("zh-CN" :html "代码" :utf-8 "代码")
+ ("custom2" :default "Programme" :html "Programme")
+ ("custom" :default "LISTING"))
("Listing %d:"
("ar" :default "برنامج %d:")
("cs" :default "Program %d:")
@@ -249,7 +274,9 @@
("pt_BR" :default "Listagem %d:")
("ru" :html "Распечатка %d.:" :utf-8 "Распечатка %d.:")
("sl" :default "Izpis programa %d")
- ("zh-CN" :html "代码%d " :utf-8 "代码%d "))
+ ("zh-CN" :html "代码%d " :utf-8 "代码%d ")
+ ("custom2" :default "Programme %d :" :html "Programme %d :")
+ ("custom" :default "LISTING %d:"))
("References"
("ar" :default "المراجع")
("cs" :default "Reference")
@@ -260,7 +287,9 @@
("nl" :default "Bronverwijzingen")
("pt_BR" :html "Referências" :default "Referências" :ascii "Referencias")
("ro" :default "Bibliografie")
- ("sl" :default "Reference"))
+ ("sl" :default "Reference")
+ ("custom2" :ascii "References" :default "Références")
+ ("custom" :default "REFERENCES"))
("See figure %s"
("cs" :default "Viz obrázek %s")
("fr" :default "cf. figure %s" :html "cf. figure %s" :latex "cf.~figure~%s")
@@ -268,14 +297,18 @@
("nl" :default "Zie figuur %s" :html "Zie figuur %s" :latex "Zie figuur~%s")
("pt_BR" :default "Veja a figura %s")
("ro" :default "Vezi figura %s")
- ("sl" :default "Glej sliko %s"))
+ ("sl" :default "Glej sliko %s")
+ ("custom2" :default "cf. figure %s" :html "cf. figure %s" :latex "cf.~figure~%s")
+ ("custom" :default "SEE FIGURE %s"))
("See listing %s"
("cs" :default "Viz program %s")
("fr" :default "cf. programme %s" :html "cf. programme %s" :latex "cf.~programme~%s")
("nl" :default "Zie programma %s" :html "Zie programma %s" :latex "Zie programma~%s")
("pt_BR" :default "Veja a listagem %s")
("ro" :default "Vezi tabelul %s")
- ("sl" :default "Glej izpis programa %s"))
+ ("sl" :default "Glej izpis programa %s")
+ ("custom2" :default "cf. programme %s" :html "cf. programme %s" :latex "cf.~programme~%s")
+ ("custom" :default "SEE LISTING %s"))
("See section %s"
("ar" :default "انظر قسم %s")
("cs" :default "Viz sekce %s")
@@ -291,7 +324,9 @@
("ro" :default "Vezi secțiunea %s")
("ru" :html "См. раздел %s" :utf-8 "См. раздел %s")
("sl" :default "Glej poglavje %d")
- ("zh-CN" :html "参见第%s节" :utf-8 "参见第%s节"))
+ ("zh-CN" :html "参见第%s节" :utf-8 "参见第%s节")
+ ("custom2" :default "cf. section %s")
+ ("custom" :default "SEE SECTION %s"))
("See table %s"
("cs" :default "Viz tabulka %s")
("fr" :default "cf. tableau %s" :html "cf. tableau %s" :latex "cf.~tableau~%s")
@@ -299,7 +334,9 @@
("nl" :default "Zie tabel %s" :html "Zie tabel %s" :latex "Zie tabel~%s")
("pt_BR" :default "Veja a tabela %s")
("ro" :default "Vezi tabelul %s")
- ("sl" :default "Glej tabelo %s"))
+ ("sl" :default "Glej tabelo %s")
+ ("custom2" :default "cf. tableau %s" :html "cf. tableau %s" :latex "cf.~tableau~%s")
+ ("custom" :default "SEE TABLE %s"))
("Table"
("ar" :default "جدول")
("cs" :default "Tabulka")
@@ -314,7 +351,9 @@
("pt_BR" :default "Tabela")
("ro" :default "Tabel")
("ru" :html "Таблица" :utf-8 "Таблица")
- ("zh-CN" :html "表" :utf-8 "表"))
+ ("zh-CN" :html "表" :utf-8 "表")
+ ("custom2" :default "Tableau")
+ ("custom" :default "TABLE"))
("Table %d:"
("ar" :default "جدول %d:")
("cs" :default "Tabulka %d:")
@@ -335,7 +374,9 @@
("ru" :html "Таблица %d.:" :utf-8 "Таблица %d.:")
("sl" :default "Tabela %d")
("sv" :default "Tabell %d")
- ("zh-CN" :html "表%d " :utf-8 "表%d "))
+ ("zh-CN" :html "表%d " :utf-8 "表%d ")
+ ("custom2" :default "Tableau %d :")
+ ("custom" :default "TABLE %d:"))
("Table of Contents"
("ar" :default "قائمة المحتويات")
("ca" :html "Índex")
@@ -363,7 +404,9 @@
("sv" :html "Innehåll")
("uk" :html "Зміст" :utf-8 "Зміст")
("zh-CN" :html "目录" :utf-8 "目录")
- ("zh-TW" :html "目錄" :utf-8 "目錄"))
+ ("zh-TW" :html "目錄" :utf-8 "目錄")
+ ("custom2" :ascii "Sommaire" :default "Table des matières")
+ ("custom" :default "TABLE OF CONTENTS"))
("Unknown reference"
("ar" :default "مرجع غير معرّف")
("da" :default "ukendt reference")
@@ -378,4 +421,6 @@
("ro" :default "Referință necunoscută")
("ru" :html "Неизвестная ссылка" :utf-8 "Неизвестная ссылка")
("sl" :default "Neznana referenca")
- ("zh-CN" :html "未知引用" :utf-8 "未知引用")))
+ ("zh-CN" :html "未知引用" :utf-8 "未知引用")
+ ("custom2" :ascii "Destination inconnue" :default "Référence inconnue")
+ ("custom" :default "UNKNOWN REFERENCE")))
```
As you can see from the diff above,
1. The snippet *appends* new entries.
2. It doesn't merge the plist values for a language. In the diff above, you can see that there are *already* some entries for `"uk"` language.
(1) and (2) will make the snippet *not work* under certain circumstances.
> 0 votes
---
Tags: org-mode
--- |
thread-62399 | https://emacs.stackexchange.com/questions/62399 | the following functions might not be defined at runtime: lsp-format-buffer, lsp-organize-imports function ‘dap-go-setup’ is not known to be defined | 2020-12-21T06:54:02.753 | # Question
Title: the following functions might not be defined at runtime: lsp-format-buffer, lsp-organize-imports function ‘dap-go-setup’ is not known to be defined
I 've below emacs init file config setup
I'm getting below error in the emacs startup. I don't know what might be the root cause of the issue
> the following functions might not be defined at runtime: lsp-format-buffer, lsp-organize-imports the function ‘dap-go-setup’ is not known to be defined.
The emacs file is -
`~/.emacs.d/init.el` file is
```
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
(package-initialize)
(add-to-list 'package-archives
'("melpa-stable" . "https://stable.melpa.org/packages/") t)
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(require 'use-package)
(load "~/.emacs.d/golang.el")
```
My `~/.emacs.d/golang.el` file is -
```
(use-package lsp-mode
:ensure t
:commands (lsp lsp-deferred)
:hook (go-mode . lsp-deferred))
;; Set up before-save hooks to format buffer and add/delete imports.
;; Make sure you don't have other gofmt/goimports hooks enabled.
(defun lsp-go-install-save-hooks ()
(add-hook 'before-save-hook #'lsp-format-buffer t t)
(add-hook 'before-save-hook #'lsp-organize-imports t t))
(add-hook 'go-mode-hook #'lsp-go-install-save-hooks)
;; Optional - provides fancier overlays.
(use-package lsp-ui
:ensure t
:commands lsp-ui-mode
:init)
;; Company mode is a standard completion package that works well with lsp-mode.
(use-package company
:ensure t
:config
;; Optionally enable completion-as-you-type behavior.
(setq company-idle-delay 0)
(setq company-minimum-prefix-length 1))
(use-package company-lsp
:ensure t
:commands company-lsp)
;; Optional - provides snippet support.
(use-package yasnippet
:ensure t
:commands yas-minor-mode
:hook (go-mode . yas-minor-mode))
(use-package dap-mode
;;:custom
;;(dap-go-debug-program `("node" "~/extension/out/src/debugAdapter/goDebug.js"))
:config
(dap-mode 1)
(setq dap-print-io t)
;;(setq fit-window-to-buffer-horizontally t)
;;(setq window-resize-pixelwise t)
(require 'dap-hydra)
(require 'dap-go) ; download and expand vscode-go-extenstion to the =~/.extensions/go=
(dap-go-setup)
(use-package dap-ui
:ensure nil
:config
(dap-ui-mode 1)
)
)
(use-package flycheck-golangci-lint
:ensure t)
(setq lsp-ui-doc-enable nil
lsp-ui-peek-enable t
lsp-ui-sideline-enable t
lsp-ui-imenu-enable t
lsp-ui-flycheck-enable t)
(setq lsp-gopls-staticcheck t)
(setq lsp-eldoc-render-all t)
(setq lsp-gopls-complete-unimported t)
```
My operating system is -
```
$ lsb_release -a
LSB Version: n/a
Distributor ID: ManjaroLinux
Description: Manjaro Linux
Release: 20.2
Codename: Nibia
```
What is the root cause of this issue?
# Answer
> 0 votes
Add `:commands` entries for the relevant functions.
```
(use-package lsp-mode
:ensure t
:commands (lsp lsp-deferred lsp-format-buffer lsp-organize-imports)
:hook (go-mode . lsp-deferred))
(use-package dap-mode
:commands dap-go-setup ; I think :functions will also work
:config
(dap-mode 1)
(setq dap-print-io t)
(require 'dap-hydra)
(require 'dap-go) ; download and expand vscode-go-extenstion to the =~/.extensions/go=
(dap-go-setup)
(use-package dap-ui
:ensure nil
:config
(dap-ui-mode 1)
))
```
---
Tags: debugging, lsp-mode, golang, lsp
--- |
thread-64153 | https://emacs.stackexchange.com/questions/64153 | How to prevent backup for files larger than 3MB? | 2021-03-27T11:48:44.203 | # Question
Title: How to prevent backup for files larger than 3MB?
One of the emacs's nice features is Backup.
But is there any way to prevent backup for files larger than 3MB? Thanks!
# Answer
> 1 votes
I haven't tested this, but here's an example of how you could advise `backup-enable-predicate` so that your size check happens only after the default `backup-enable-predicate` has determined that your file should be backed up:
```
(add-function :after-while backup-enable-predicate
(lambda (file)
;; Back up FILE only if it is smaller than 3 MiB.
(< (file-attribute-size (file-attributes file)) 3145728)))
```
---
Tags: backup
--- |
thread-19713 | https://emacs.stackexchange.com/questions/19713 | How change the storage location of recentf file? | 2016-01-20T15:51:20.113 | # Question
Title: How change the storage location of recentf file?
I looked around, but I couldn't find any answer in the documentation of `recentf` and with `C-h v` `recent`.
My default directory is set with the following:
```
(setq user-emacs-directory "~/home/ReneFroger/"
default-directory "~/home/ReneFroger/")
```
I noticed Emacs saves the recent files that I have visited in the file `recentf`, which will be stored in the `home/ReneFroger/` path. I would like to change the location of `recentf` but I can't find any variable that allows me to do this.
# Answer
You can set it with
```
(setq recentf-save-file (expand-file-name "recentf" <other-directory>))
```
You can usually find settings like this by looking at the help for one of the functions, e.g. `recentf-mode`, then following the link to the source code, and then doing `occur` for `defcustom` to find one that looks like it might be a file storage location - e.g. in this case you'd get
```
23 matches for "defcustom" in buffer: recentf.el
65:(defcustom recentf-max-saved-items 20
72:(defcustom recentf-save-file (locate-user-emacs-file "recentf" ".recentf")
85:(defcustom recentf-save-file-modes 384 ;; 0600
94:(defcustom recentf-exclude nil
111:(defcustom recentf-keep
etc.
```
> 10 votes
# Answer
From the link (https://www.emacswiki.org/emacs/RecentFiles):
```
;; use a different set of recent files
(setq recentf-save-file (recentf-expand-file-name "~/.emacs.d/.recentf"))
```
> 2 votes
---
Tags: recentf
--- |
thread-64156 | https://emacs.stackexchange.com/questions/64156 | Why in sizes of files not show in human-readable format? | 2021-03-27T16:30:05.723 | # Question
Title: Why in sizes of files not show in human-readable format?
Linux Mint 20
Emacs 26.3
I install packaged **dired-k**
And set this param in my init.el
```
'(dired-k-human-readable t)
```
But it not work in dired mode.
Here example
As you can see size of files not show like **KB/MB** (human readable)
If in shell I use
```
ls -alFH
```
The show with human readable format:
```
alexei@alexei-nb:~/.emacs.d$ ls -alFh
total 168K
drwx------ 8 alexei alexei 12K Mar 27 18:22 ./
drwxrwxr-x 55 alexei alexei 4.0K Mar 27 17:54 ../
drwx------ 2 alexei alexei 4.0K Mar 27 19:55 auto-save-list/
-rw-rw-r-- 1 alexei alexei 11K Mar 25 23:37 bookmarks
drwxr-xr-x 2 alexei alexei 4.0K Mar 27 18:31 custom/
-rw-r--r-- 1 alexei alexei 6.2K Mar 27 19:54 dired-history
drwxr-xr-x 62 alexei alexei 4.0K Mar 27 18:00 elpa/
drwx------ 2 alexei alexei 4.0K Mar 16 23:42 eshell/
drwxr-xr-x 9 alexei alexei 4.0K Mar 27 19:54 .git/
-rw-r--r-- 1 alexei alexei 341 Mar 19 21:21 .gitignore
-rw------- 1 alexei alexei 8.6K Mar 27 19:54 history
-rw-rw-r-- 1 alexei alexei 62K Mar 27 19:54 ido.last
-rw-rw-r-- 1 alexei alexei 8.6K Mar 27 19:54 init.el
-rw-r--r-- 1 alexei alexei 50 Mar 19 21:18 README.md
-rw------- 1 alexei alexei 1.6K Mar 27 19:54 recentf
```
But why it's not work in dired mode?
# Answer
I found solution. I customize **dired-listing-switches**.
So here in init.el file:
```
'(dired-listing-switches "-alFh")
```
And in dired mode show size in human readable format:
> 0 votes
---
Tags: dired
--- |
thread-64162 | https://emacs.stackexchange.com/questions/64162 | How to suppress emacsclient --eval output | 2021-03-27T18:53:43.237 | # Question
Title: How to suppress emacsclient --eval output
I am opening a file as follows:
```
$ emacsclient -qt -e '(progn (find-file "'filename.py'"))'
#<buffer filename.py>
```
which outputs `#<buffer filename.py>` in the terminal. Is it possible to suppress that output?
---
I have tried following which didn't help.
```
$ emacsclient -qt -e '(progn (find-file "'Driver.py'"))' 2> /dev/null
```
# Answer
> Is it possible to suppress that output?
In general you can specify the `--suppress-output`/`-u` option:
```
$ emacsclient -e '(1+ 2)'
3
$ emacsclient -ue '(1+ 2)'
$
```
In your particular `find-file` examples you don't need the `--eval`/`-e` option:
```
$ emacsclient -t filename.py Driver.py
```
See `(info "(emacs) emacsclient Options")` for more.
> 2 votes
---
Tags: emacsclient
--- |
thread-64147 | https://emacs.stackexchange.com/questions/64147 | how to make `C-l` override `centered-cursor-mode`? | 2021-03-27T07:06:19.203 | # Question
Title: how to make `C-l` override `centered-cursor-mode`?
I love centered-cursor-mode. It keeps my cursor in the center of the screen always.
However, on rare occasions, I need to use `C-l` `recenter-top-bottom` to "scroll" in order to view text lower than the center position allows.
In the meantime, I am forced to disable `centered-cursor-mode` and than use `recenter-top-bottom`, but I'd really prefer if there was a way to make `C-l` override `centered-cursor-mode`
# Answer
Just customize option `ccm-ignored-commands`, adding `recenter-top-bottom` to the list of commands that `centered-cursor-mode` lets happen without kicking in afterward.
---
How I found this:
I never heard of `centered-cursor-mode`. I followed your link, downloaded the source file, and looked through its options, to start with. Saw this option, tried it.
> 2 votes
---
Tags: scrolling, centering
--- |
thread-64159 | https://emacs.stackexchange.com/questions/64159 | How to change projectile-bookmarks.eld saving path? | 2021-03-27T17:47:59.900 | # Question
Title: How to change projectile-bookmarks.eld saving path?
`emacs` keeps generating file called `projectile-bookmarks.eld` in home directory.
How could I make it to save that file under `~/.emacs.d/tmp` or a different path?
---
I also keep seeing `Reverting buffer ‘projectile-bookmarks.eld’.` whenever I open a new buffer.
---
As solution I have been told that:
> you can modify the variable projectile-known-projects-file
I have done: `(setq projectile-known-projects-file "~/.emacs.d/tmp/projectile-bookmarks.eld")`
Now the file is generated under `~/` and `~/.emacs.d/tmp/`. How can I prevent it to saved under the home directory?
# Answer
Set the following variables.
```
(setq projectile-cache-file (expand-file-name "projectile.cache"
user-emacs-directory)
projectile-known-projects-file (expand-file-name "projectile-known-projects.eld"
user-emacs-directory))
```
You can customize your desired name and path in the above snippet. Note that I have also included a second variable that controls another temporary file created by `projectile`.
Another nice way to keep your `.emacs.d` clean is to use the `no-littering` package.
```
(use-package no-littering
:ensure t)
```
You can look up the description of the `no-littering` package here.
> 2 votes
---
Tags: projectile, bookmarks
--- |
thread-64143 | https://emacs.stackexchange.com/questions/64143 | File-specific TeX compiling options? | 2021-03-26T19:47:43.420 | # Question
Title: File-specific TeX compiling options?
I have TeX files that Aquamacs compiles by default with pdflatex and other files compiled by default with latex (so I get a dvi).
If I make a copy of file that Aquamacs compiles with latex, that copy is compiled with latex. Similarly, a copy of a "pdflatex file" will be compiled with pdflatex.
I can't see where there could be some metadata of my TeX files that could tell Aquamacs with which engine it has to compile.
I have `setq-default TeX-global-PDF-mode t` in my .emacs
What determines which compilation is done?
# Answer
AUCTeX, used by Aquamacs for tex files, when the option `TeX-parse-self` is `t` parses the document preamble, and if it finds some package that requires the creation of dvi (e.g. pstricks) uses latex instead of pdflatex.
> 1 votes
---
Tags: latex, aquamacs, compile-mode
--- |
thread-64171 | https://emacs.stackexchange.com/questions/64171 | Set font for Devanagari Characters in Doom Emacs | 2021-03-28T11:51:42.733 | # Question
Title: Set font for Devanagari Characters in Doom Emacs
Running Doom Emacs 2.0.9 on Emacs 27.1.
I want to always display Devanagari characters in a specific font (Sarpanch). This font is installed on my computer and I can use it in all other applications like Libre Office, etc.
How do I achieve this?
# Answer
`(set-fontset-font t 'devanagari "Noto Sans Devanagari")`
does the job. Of course, replace 'Noto Sans Devanagari' with whatever font you prefer (and ensure that it is installed on your system).
> 0 votes
---
Tags: fonts
--- |
thread-61624 | https://emacs.stackexchange.com/questions/61624 | .m file become read only when debugging in matlab-mode | 2020-11-08T04:10:51.343 | # Question
Title: .m file become read only when debugging in matlab-mode
Is it possible to add a hook or set a configuration variable such that the `.m` file I am debugging remains in edit mode when debugging starts. I don't want to switch out of read-only mode to interactively debug and code.
It seems this behavior is relatively new since older versions did not enforce this.
# Answer
I had the same question. After reading through the matlab-shell-gud.el and playing around with code, I got the following to work:
```
(add-hook 'matlab-shell-prompt-appears-hook
(lambda ()
(global-matlab-shell-gud-minor-mode 0)))
```
Now it starts in edit mode and `C-x C-q` switches into debug mode.
> 0 votes
---
Tags: gud, matlab
--- |
thread-64172 | https://emacs.stackexchange.com/questions/64172 | What is this area for and why the content inside it isn't showing correctly? | 2021-03-28T13:32:53.497 | # Question
Title: What is this area for and why the content inside it isn't showing correctly?
I'm using GNU Emacs with Doom. When using, I noticed an area placed before the line numbers. ~~I don't know the name of the area.~~ It is called "fringe". It is used by `vi-tilde-fringe-mode`, `magit` and `dap-mode`. However, the content inside it isn't rendered properly in GUI, and the area is not shown in the terminal.
The image: (see the characters appearing before `Head` and `Recent`, looks like `>` and `v`)
Is it normal is a problem? If it is a problem, how can I fix it?
I'm using:
* Emacs: 27.1
* Doom: 2.0.9
# Answer
> 2 votes
Welcome to EmacsSE. This area is called the *fringe* and looks a little odd if it is not wide enough. The default is 8 pixels and can be achieved simply by putting
```
(fringe-mode)
```
in your init file. Check the docs for `fringe-mode` to learn more or search the manual for `Window Fringes`.
# Answer
> 0 votes
I have figured out a way to fix the problem. @FranBurstall's answer is correct, but it breaks when `:ui vc-gutter` module is enabled. A workaround is to set `+vc-gutter-default-style` to `nil`, which disables the optional UI enhancements. So I had to add this to my `config.el`:
```
(setq +vc-gutter-default-style nil)
(fringe-mode nil)
```
However, I missed the icons shown by the module on the fringe. So I added this to my `config.el` as well: (optional)
```
(after! git-gutter-fringe
(setq-default fringes-outside-margins t)
(define-fringe-bitmap 'git-gutter-fr:added [224] nil nil '(center repeated))
(define-fringe-bitmap 'git-gutter-fr:modified [224] nil nil '(center repeated))
(define-fringe-bitmap 'git-gutter-fr:deleted [128 192 224 240] nil nil 'bottom))
```
---
Tags: fringe
--- |
thread-64181 | https://emacs.stackexchange.com/questions/64181 | How do I change the value of author name in org-publish? | 2021-03-28T19:40:03.010 | # Question
Title: How do I change the value of author name in org-publish?
Can I specify the value of author used in org-publish?
So far I can see that it is possible to exclude it but how do I change it?
```
(setq org-publish-project-alist
'(("org-project"
...
:with-author nil
...)))
```
Update: I can see that it comes from the `user-full-name` variable. If I edit that then the name will change. Is it possible to do this in any other way instead?
# Answer
> 2 votes
You could try
```
#+author: name you choose
```
or let-bind the user-full-name in a src block. Something like this should work.
```
(let ((user-full-name "name you choose"))
;; publish commands here
(org-publish "org-project"))
```
---
Tags: org-publish
--- |
thread-64177 | https://emacs.stackexchange.com/questions/64177 | How do I copy the content of a cell in org-mode table? | 2021-03-28T18:12:07.517 | # Question
Title: How do I copy the content of a cell in org-mode table?
Is there a command to copy the content of a cell in a single keystroke?
When I have cursor at \[x\] (see below), I have to do: `M-a` (goes to the beginning of the cell), `C-<SPC>`, `M-e` (goes to the end of the cell), and `M-w`. There should be an easier way!
```
| Title 1 | Title 2 |
|--------------------+----------------|
| This is [x] a cell | This is a cell |
| | |
```
# Answer
I suggest this bind to \`C-c y' (or whatever key you want)
```
(bind-key (kbd "C-c y")
(lambda()(interactive)
(when (org-at-table-p)
(kill-new
(string-trim
(substring-no-properties(org-table-get-field))))
(message "copied cell: @%d$%d"
(org-table-current-line)
(org-table-current-column) )))
org-mode-map)
```
> 5 votes
# Answer
I am surprised that `org-mark-element` doesn't do what I would call "the right thing" here. This short function seems to copy a cell when your cursor is in a cell, and otherwise the element around the cursor.
```
(defun copy-element ()
(interactive)
(let* ((oec (org-element-context))
(begin (org-element-property :begin oec))
(end (org-element-property :end oec)))
(kill-new
(cond
;; for a cell the end includes the trailing | so we don't count that.
((eq 'table-cell (car oec))
(buffer-substring begin (1- end)))
(t
(buffer-substring begin end))))))
```
> 1 votes
# Answer
NickD provides in his comment a method that solves 90 % of the use cases - those where we need to copy a cell to another cell of the table.
Just do `S-RET` to copy the cell to the cell below, and then move the copied cell to its desired location by pressing Shift plus any of the arrow key (`S-<up>`, `S-<down>`, `S-<left>` and `S-<right>`).
> 0 votes
---
Tags: org-mode, org-table
--- |
thread-64190 | https://emacs.stackexchange.com/questions/64190 | Can font faces be dynamically assigned with font-lock-add-keywords? | 2021-03-29T08:27:00.630 | # Question
Title: Can font faces be dynamically assigned with font-lock-add-keywords?
In all the examples of `font-lock-add-keywords` I've seen, the font face is static.
That is, there is a regex or a matcher function and a literal font face identifier.
Is it possible to set the face dynamically? So the font face used can be selected using code that interacts with the matches for example?
Otherwise I would have to register multiple matchers, one for each face used.
# Answer
Yes, you can. See the Elisp manual, node Search-based Fontification.
`font-lock-keywords` (which you set using `font-lock-keywords`, e.g. `font-lock-add-keywords`) can use a `FACESPEC` expression, which is *evaluated* to provide the face to use.
> `FACESPEC` is an expression whose value specifies the face to use for highlighting. In the simplest case, `FACESPEC` is a Lisp variable (a symbol) whose value is a face name.
>
> ```
> ;; Highlight occurrences of ‘fubar’,
> ;; using the face which is the value of ‘fubar-face’.
> ("fubar" . fubar-face)
>
> ```
>
> However, `FACESPEC` can also evaluate to a list of this form:
>
> ```
> (face FACE PROP1 VAL1 PROP2 VAL2...)
>
> ```
>
> to specify the face `FACE` and various additional text properties to put on the text that matches. If you do this, be sure to add the other text property names that you set in this way to the value of `font-lock-extra-managed-props` so that the properties will also be cleared out when they are no longer appropriate. Alternatively, you can set the variable `font-lock-unfontify-region-function` to a function that clears these properties. \*Note Other Font Lock Variables::.
> 1 votes
---
Tags: faces, font-lock, variables
--- |
thread-64199 | https://emacs.stackexchange.com/questions/64199 | How to check a regular expression is valid without using it for a search? | 2021-03-30T02:05:08.323 | # Question
Title: How to check a regular expression is valid without using it for a search?
I would like to write a package that uses user defined regular expressions.
Is there a way to validate a regular expression is valid without having to perform a search, showing a helpful message when it's not?
# Answer
> 3 votes
If you want to check it interactively:
```
(defcustom foo "" "foo" :type 'regexp :group 'emacs)
```
Try giving it an invalid regexp and setting it, and it will raise an error.
---
Or if you want to test it programmatically, this predicate returns `t` for valid and `nil` for invalid, and when invalid it shows a message with the error type.
```
(defun regexp-valid-p (string)
"Return nil if STRING is not a valid regexp."
(condition-case err
(prog1 t (string-match-p string ""))
(error (message (error-message-string err))
nil)))
```
This works because `string-match-p` and `string-match` return either `nil` or non-`nil` for any valid regexp, and they raise an error for an invalid regexp. The `condition-case` just captures the error, converts its message to an ordinary `message` instead, and returns `nil` for invalid and `t` for valid.
This solution comes almost directly from the definition of function `widget-regexp-match` (or function `widget-regexp-validate`) in standard library `wid-edit.el`.
In other words, I started from knowing that Customize checks validity of a field of `:type regexp`, and looked for the code that checked that.
---
Another programmatic solution, also found by looking in the Elisp source code: use function `mh-index-parse-search-regexp`, defined in standard library `mh-search.el`.
Example:
```
(mh-index-parse-search-regexp "\\(ab") ;; Raises an invalid-regexp error.
```
That function depends on these functions being defined:
* `mh-replace-string` ; Defined in `mh-utils.el`.
* `mh-index-add-implicit-ops` ; Defined in `mh-search.el`.
* `mh-index-evaluate` ; Defined in `mh-search.el`.
---
**Moral:** If what you want to do seems like something that would be useful generally, there's a good chance it's already been done, and a good place to start looking is the source Lisp code provided with Emacs.
# Answer
> 1 votes
You can test a regular expression on a document with `M-x re-builder` and build it interactively. Faulty parts are highlighted.
---
Tags: regular-expressions
--- |
thread-64197 | https://emacs.stackexchange.com/questions/64197 | Avoiding warnings of undefined functions while compiling | 2021-03-29T20:31:58.643 | # Question
Title: Avoiding warnings of undefined functions while compiling
I have a lot of code in my init file like this:
```
(when library-is-available
;; Code that use that uses functions from library
)
```
However, I get warnings that the functions that I am using are not known to be defined. What is an easy way to avoid these warnings? Can I perhaps ignore these code parts and not include them in the compiled file?
# Answer
> 3 votes
Node Warning Tips of the Elisp manual tells us:
> • To avoid a compiler warning about an undefined function that you know *will* be defined, use a `declare-function` statement (see Declaring Functions).
>
> • If you use many functions, macros, and variables from a certain file, you can add a `require` (see require: Named Features) for that package to avoid compilation warnings for them, like this:
>
> ```
> (require 'foo)
>
> ```
>
> If you need only *macros* from some file, you can require it only at compile time (see Eval During Compile). For instance,
>
> ```
> (eval-when-compile
> (require 'foo))
>
> ```
---
Tags: byte-compilation, warning
--- |
thread-64204 | https://emacs.stackexchange.com/questions/64204 | How to open sourcegraph files directly in Emacs on Linux | 2021-03-30T06:40:23.027 | # Question
Title: How to open sourcegraph files directly in Emacs on Linux
There's the open-in-editor extension on `sourcegraph`, which
> Adds a button at the top of files in both Sourcegraph app and code hosts like GitHub (when the Sourcegraph browser extension is installed) that will open the current file in your editor of choice.
It supports `vscode`, `sublime`, and `idea` out of box, but other editors needs to be manually configured. I'd like to open files in my `emacs`. How?
# Answer
The relevant settings on `sourcegraph` is as below:
```
{
"extensions": {
"sourcegraph/open-in-editor": true
},
"openineditor.editor": "custom",
"openineditor.customUrlPattern": "emacs://open?file=%file&line=%line&column=%col"
}
```
The custom URL pattern supports three placeholders. Obviously, `%line` and `%column` expands to line number and column numbers.
`%file` expands to a local file path which should be an absolute path of a file on your local file system to be opened.
Suppose, there's a file `foo/bar.txt` in the repository `baz/xyz` (username/repository-name), the 'relative' path to the file is `xyz/foo/bar.txt` (with username stripped out). Then, there's another configuration option not shown above, `openineditor.basePath`, which is an absolute path which is the local directory that contains all copies of your local repositories. It's appended to the 'relative' path and becomes the full path of the file to be opened.
---
Next, you need to create a custom x-scheme handler, which would accept the `emacs` scheme.
Based on palswim's answer to the question of creating custom x-scheme handler, I've made the following scripts that registers and handles such an `emacs` x-scheme.
---
First create a desktop file:
```
[Desktop Entry]
Type=Application
Name=Emacs Scheme Handler
Exec=emacs-scheme-handler.py %u
StartupNotify=false
MimeType=x-scheme-handler/emacs;
```
In my case I put it in `~/.local/share/applications/emacs-scheme-handler.desktop`.
---
Then create the companion Python script:
```
#!/usr/bin/env python3
import sys
from urllib.parse import urlparse, parse_qs
from subprocess import Popen
query = parse_qs(urlparse(sys.argv[1]).query)
filename, line, column = [query[k][0] for k in ("file", "line", "column")]
command = f"emacslient -c -a=emacs +{line}:{column} {filename}"
Popen(
[
"/usr/bin/env",
"emacsclient",
"-c",
'-a="/usr/bin/env emacs',
f"+{line}:{column}",
filename,
],
stdin=None,
stdout=None,
stderr=None,
close_fds=True,
)
```
It would spawn a new process which works the same as the following shell command:
```
/usr/bin/env emacsclient -c -a="/usr/bin/env emacs" +${line}:${column} ${filename}
# | | |
# | | + Go to the line and column position
# | |
# | + If no emacs server is running, starts a new emacs instance
# |
# + Open the file in a new frame
```
---
You can use and share the above scripts as you like. I declare that these are in public domain.
> 1 votes
---
Tags: emacs-daemon, integration
--- |
thread-31631 | https://emacs.stackexchange.com/questions/31631 | Gray-out preprocessor conditionals | 2017-03-22T15:01:48.310 | # Question
Title: Gray-out preprocessor conditionals
Is there a package that will gray out or hide the false portion of a c preprocessor macro?
```
#define ENABLE 1
#if ENABLE
bool hide = false;
#else
bool hide = true;
#endif
```
In the above example, I want `bool hide = true;` to be grayed out or hidden.
I've looked at Hide If Def, but it doesn't produce my desired effect. Executing `M-x hide-ifdefs` hides `bool hide = false;`, but I would expect `bool hide = true;` to be hidden.
The functionality I am looking for would be similar to what NetBeans does.
# Answer
Sorry that I didn't see this earlier. This should only happen in older hide-ifdef-mode in Emacs v24 or earlier. For any Emacs version newer than **25.1** (released 2016/09/17), the aforementioned Hide If Def that I rewrote is built-in and replace the old implementation, which did have the problem of not being able to evaluate preprocessor macros properly. In newer Emacs, you should see something like this by performing `C-c @ h` (`M-x hide-ifdefs`):
By marking the "`ENABLE`" and press `C-c @ e` (`M-x hif-evaluate-macro`) you can see the value of `ENABLE` shown in the echo area.
However, I am not sure why Hide If Def was not working at the time this question was asked (2017/3/22). Before I submitted it into Emacs source trunk (2014/07/07) it has been working for Emacs v24 or even v23. Now I can no longer access Emacs24 or 23 therefore can't reproduce the issue. Anyway, please be sure to try newer (above v25) Emacs.
(By the way, if you really like the texts to be "grayed" out, try `C-c @ C-w` (`M-x hide-ifdef-toggle-shadowing`), then the hidden texts will really be "grayed" out.)
Hope this helps!
> 3 votes
# Answer
'hide-ifdef-mode' hides, but it doesn't do the preprocessor evaluation, since that can come from multiple places, most of which aren't available to an Emacs mode which is just looking at a single file.
You enter `hide-ifdef-mode`, then tell the mode what things are defined and are not, using `hide-ifdef-define`/`hide-ifdef-undef`. Then `hide-ifdefs` will do what you want. You can save lists of these definitions and toggle them (`hide-ifdef-set-define-alist`/`hide-ifdef-use-define-alist`). `hif-evaluate-macro` might be pretty valuable for you to handle more involved macrology.
It is simple to use but tedious if you have a lot of complex preprocessor defs that depend on others etc.
Might be some more project-aware packages that wrap this to make this easier, not sure.
> 2 votes
---
Tags: faces, syntax-highlighting, c++, c
--- |
thread-31786 | https://emacs.stackexchange.com/questions/31786 | Can Ibuffer show buffers last viewing time? | 2017-03-30T00:30:18.343 | # Question
Title: Can Ibuffer show buffers last viewing time?
I was wondering if it is possible to have a column in `Ibuffer` that shows the last viewing time.
In the default view I can see these columns:
```
MR Name Size Mode Filename/Process
-- ---- ---- ---- ----------------
```
And with `s v` the buffers are sorted by last viewing time.
I would be interested in having a column with the value of last viewing/editing time, for example: `20secs`, `14min`, `1h 23min`, `1day 2h 34min`, etc...
# Answer
> 1 votes
(In case someone wants the sorting, without the column, the built-in `s v` will sort by "recency" and should (roughly, see below) do the trick.)
I wanted something like this as well, so I put the above comments to work.
First create the actual column, via `define-ibuffer-column`. `buffer-display-time` is a local variable, hence `with-current-buffer` sets the context. I've formatted it here with my preferred display style (`YYYY-MM-DD HH:MM`) but that can obviously be changed; see the the docs on `format-time-string`. If you want it relative, you'll have to come up with a more involved, custom function (the definitions of `org-evaluate-time-range` and `calendar-count-days-region` may provide a jumping off point).
```
(define-ibuffer-column last-viewed
(:name "Last-viewed" :inline t)
(with-current-buffer buffer
(format-time-string "%Y-%m-%d %R" buffer-display-time)))
```
Then we need to actually insert the column where you want it in `ibuffer-formats`. Here's what I've done, YMMV:
```
(setq ibuffer-formats
'((mark modified read-only locked " "
(name 18 18 :left :elide)
" "
(size 9 -1 :right)
" "
(mode 16 16 :left :elide)
" "
(last-viewed 18 -1 :left)
" " filename-and-process)
(mark " "
(name 16 -1)
" " filename)))
```
That's it — the column should appear, and you should be able to sort with `s v`!
There's something weird about that "recency" sorting I can't quite figure out — I *think* it's that it derives the list from `buffer-list`, so it interacts poorly with `ibuffer-auto-mode`? Regardless, it doesn't seem to reliably sort by `buffer-display-time`, so I also created a custom sorter function to override that:
```
(define-ibuffer-sorter last-viewed
"Sort the buffers by last viewed time."
(:description "last-viewed")
(string-lessp (with-current-buffer (car a)
(format-time-string "%Y-%m-%d %R" buffer-display-time))
(with-current-buffer (car b)
(format-time-string "%Y-%m-%d %R" buffer-display-time))))
(define-key ibuffer-mode-map (kbd "s v") 'ibuffer-do-sort-by-last-edited)
```
---
Tags: time-date, ibuffer, column
--- |
thread-64211 | https://emacs.stackexchange.com/questions/64211 | Close org todo with all subtasks | 2021-03-30T17:41:56.443 | # Question
Title: Close org todo with all subtasks
I have a task with multiple subitems in different states, and I would like to have a binding to switch the task and all its subtasks to the same state (DONE). I know that I can ignore state blocking, but that isn't what I want.
Do I have to iterate over all the subtasks for that, and if so how?
# Answer
> 1 votes
I adapted the function from this answer to a similar question, which works fantastically and even respects selections :)
```
(defun org-todo-region ()
(interactive)
(let ((scope (if mark-active 'region 'tree))
(state (org-fast-todo-selection))
(org-enforce-todo-dependencies nil))
(org-map-entries (lambda () (org-todo state)) nil scope)))
```
---
Tags: org-mode, todo
--- |
thread-61773 | https://emacs.stackexchange.com/questions/61773 | Cannot open .gpg file in emacs after upgrading to 27.1 | 2020-11-16T12:31:31.713 | # Question
Title: Cannot open .gpg file in emacs after upgrading to 27.1
I was upgraded from RHEL 7.6 to 7.8 last week. After upgrade my emacs (v25.3) was broken and I got the following error:
> error while loading shared libraries: libMagickWand.so.5: cannot open shared object file: No such file or directory
I could not figure out a solution (partly, I think, because our RHN server is down) so I downloaded/installed emacs 27.1. Now, I cannot open a gpg file. I get the following error in emacs:
> GPG error: "no usable configuration", OpenPGP
I tried solutions offered here and here, but nothing has worked so far.
One solution suggested adding this line to .emacs
```
(custom-set-variables '(epg-gpg-program "/usr/local/bin/gpg2"))
```
However, adding that results in the following error: "Wrong type argument: arrayp, nil"
I did not blow away the old emacs install prior to installing 27.1, but I doubt that is the problem.
Any help on resolving this is appreciated.
# Answer
> 2 votes
As Martin mentioned, this is due to a version problem of the `gpg` binaries RHEL/CENTOS provides. For this to work, you need to convince emacs that your version is acceptable.
Find the `.../share/emacs/27.2/lisp` directory and open the `epg-config-el.gz` file. I found mine by running `find-name-dired` and searching for `*epg-config*`. Once opened, change the line from
```
(defconst epg-gpg2-minimum-version "2.1.6")
```
to
```
(defconst epg-gpg2-minimum-version "2.0.22")
```
or whatever matches your current gpg2 version.
Then byte compile the file using `byte-compile-file`, restart emacs, and it should work correctly.
# Answer
> 1 votes
I stumbled across the same problem, when my employer forced me to switch to CentOS instead of Debian with Emacs 27.1 installed. The problem comes from the gnupg version, that CentOS and RedHat ship. Both gpg and gpg2 are version 2.0.22 on CentOS 7, but Emacs now requires version 2.1.6 at least. The gpg configuration worked in older versions of Emacs, because the corresponding check in epg-config.el was buggy and has been fixed. I had opened a bug report for Emacs (#42845), but the author did not see this as a regression. I ended up hacking epg-config.el to allow 2.0.22 to be accepted, which works without problems.
---
Tags: init-file, gpg
--- |
thread-64217 | https://emacs.stackexchange.com/questions/64217 | Start emacs with Global TODO list along with default org file | 2021-03-30T21:05:01.517 | # Question
Title: Start emacs with Global TODO list along with default org file
How can I open the global `TODO` list along side my default Org file.
Even with Desktop Save mode is on, whenever I open Emacs, only the org file reopens, and not the buffer with the global `TODO` list.
# Answer
Add something like the following code at the end of your init file:
```
(setq inhibit-splash-screen t)
(find-file "/path/to/my/default.org")
(org-agenda nil "t")
```
I had to inhibit the splash screen, otherwise it hid the global TODO list.
> 1 votes
---
Tags: org-mode, org-agenda, start-up, todo
--- |
thread-64220 | https://emacs.stackexchange.com/questions/64220 | How to change the "Figure" text created when exporting a LaTeX file with org-mode. I want it to say "Figura" as I speak Spanish | 2021-03-31T03:38:07.377 | # Question
Title: How to change the "Figure" text created when exporting a LaTeX file with org-mode. I want it to say "Figura" as I speak Spanish
When I export all the images get the "figure" and the number of the image with the caption. When I export I want it to say "figura" instead of the English word.
# Answer
> 1 votes
Theoretically, all you have to do is add a header:
```
#+LANGUAGE: es
```
Don't forget to either close and reopen the file, or do `C-c C-c` on the header so that the setup will be refreshed.
That seems to work e.g. for text and HTML export, but LaTeX export does not work for me: it seems to require additional setup that I have not figured out yet.
EDIT: just to close the loop, for LaTeX, Org mode requires some help. First, the relevant LaTeX babel language package needs to be installed. This varies with the distro - on my Fedora 33 system, I had to do:
```
sudo dnf install texlive-babel-spanish
```
Then the header had to be augmented:
```
#+LANGUAGE: es
#+LATEX_HEADER: \usepackage[AUTO]{babel}
...
```
Not sure why the latex exporter does not do that automatically.
---
Tags: org-mode, latex, translation
--- |
thread-36463 | https://emacs.stackexchange.com/questions/36463 | Specifying python version in run-python | 2017-10-28T18:33:31.333 | # Question
Title: Specifying python version in run-python
I'm trying to figure out how to specify which version of python to run when calling "run-python" (C-c C-p) in python-mode, and I've run into the following problem. These are the first few lines of the definition of run-python:
> (defun run-python (cmd &optional dedicated show)
>
> "Run an inferior Python process. Input and output via buffer named after \`python-shell-buffer-name'. If there is a process already running in that buffer, just switch to it.
>
> With argument, allows you to define CMD so you can edit the command used to call the interpreter and define DEDICATED, so a dedicated process for the current buffer is open. When numeric prefix arg is other than 0 or 4 do not SHOW.
I would like to specify the CMD argument so as to specify "python2" or "python3." For example, I've tried things like
> M-: (run-python python2)
>
> M-: (run-python (shell-command "/usr/bin/python2"))
but nothing works.
Edit: I figured out that if I supply 0 as a numeric argument, then there is a prompt where I can specify the python version. I would still like to know why neither of my attempts to specify CMD in the actual function call did not work though.
# Answer
> 3 votes
according to the contents of python.el (the source file of python mode) run-python's `cmd` defaults to a function which returns the path and parameters of the system's default python version, and in turn runs this via `python-shell-make-comint`, so simply setting an unquoted name (a nonexistant variable as ELisp sees it) or trying to run a shell command directly won't work.
What works, however, is `M-: (run-python "python3")`, using double quotes in comparison to your first variant. It opens a new buffer with a python prompt, but does not necessarily get it to the front (ie., use `C-x C-b` and select the python buffer from the list). You can see that it worked if „Shell native completion is enabled” appears in the status line.
Depending on which python version you usually run, it is even easier to set it in your `~/.emacs.d/init.el` and run it via `C-c C-p`, or to add those two variables as file-locals in a comment block at the end of a python file (excerpt from python.el's header):
```
;; … . You can change
;; your default interpreter and commandline arguments by setting the
;; `python-shell-interpreter' and `python-shell-interpreter-args'
;; variables. This example enables IPython globally:
;; (setq python-shell-interpreter "ipython"
;; python-shell-interpreter-args "-i")
```
# Answer
> 8 votes
Put `(setq python-shell-interpreter "python3")` into your `.emacs`.
# Answer
> 0 votes
For recent Python versions (3.3 or newer), I would advise you use the pylauncher `py`, instead of calling directly Python with `python` or `python3`. The pylauncher does exactly the same, but lets you specify which version you want to use amongst those installed on your system.
You can test it inside a terminal, by typing `py -3.9` to launch version 3.9 of python, `py -3.7` to launch its version 3.7, and so on. Of course, this will only work if you installed both versions on your system.
For Emacs run-python, this translates in using the following:
```
(setq python-shell-interpreter "py")
(setq python-shell-interpreter-args "-3.9")
```
For Microsoft Windows users, that would be something along thoses lines:
```
(setq python-shell-interpreter "py")
(setq python-shell-interpreter-args "-3.9 -i c:/Users/YOUR_PROFILE_NAME/AppData/Local/Continuum/anaconda3/Scripts/ipython-script.py")
```
If you run a dedicated run process (`C-u C-c C-p`), you can also choose dynamically which version of Python you want to run for the buffer. That makes it very easy to use Python 3.7 (which currently supports tensorflow) on a particular file, while using 3.9 (which currently doesn't) on all the others.
Source: How to run multiple Python versions on Windows
---
Tags: python
--- |
thread-3618 | https://emacs.stackexchange.com/questions/3618 | Launch emacs with ediff-files (of ediff-directories) from command line | 2014-11-16T22:11:18.440 | # Question
Title: Launch emacs with ediff-files (of ediff-directories) from command line
I would like to launch emacs to ediff either files or directories. For example, I'd like something like:
```
emacs -f ediff-files file1 file2
```
But when I do this, it doesn't take file1 and file2 as the two files to diff. Rather, emacs prompts me for the files to difference.
Does anyone know how to do this in one command line?
# Answer
> 15 votes
I'm pretty sure there are other solutions, but you can do this using `--eval` instead of `-f` (`--funcall`):
```
emacs --eval '(ediff-files "file1" "file2")'
```
In fact, the Emacs manual on "Command Line Arguments for Emacs Invocation" says that `-f function` and `--funcall function`
> Call Lisp function *function*. If it is an interactive function (a command), **it reads the arguments interactively** just as if you had called the same function with a key sequence. Otherwise, it calls the function with no arguments.
This explains why you can not get the behavior you want with `-f`/`--funcall`.
---
`ediff-directories` takes three arguments, so the command shown above changes to
```
emacs --eval '(ediff-directories "dir1" "dir2" "regexp")'
```
e.g. to compare everything in both directories (i.e. unfiltered) use .\* as a regexp:
```
emacs --eval '(ediff-directories "dir1" "dir2" ".*")'
```
As explained here, `ediff-directories` causes Emacs to enter `ediff-meta-mode`, so you'll be dropped into the "Ediff Session Group Panel" first. From the Ediff manual on Session Groups:
> Several major entries of Ediff perform comparison and merging on directories. On entering `ediff-directories`, `ediff-directories3`, \[...\] the user is presented with a Dired-like buffer that lists files common to the directories involved along with their sizes. \[...\] We call this buffer *Session Group Panel* because all Ediff sessions associated with the listed files will have this buffer as a common focal point. \[...\]
>
> In directory comparison or merging, a session group panel displays only the files common to all directories involved. The differences are kept in a separate directory difference buffer and are conveniently displayed by typing `D` to the corresponding session group panel. \[...\]
So to display the actual diff, just hit `D` (`ediff-show-dir-diffs`).
# Answer
> 6 votes
I use the following script: it checks in advance if there are differences, and in case there are, it opens Emacs with the appropriate function evaluated. With the `-d` option, it assumes the items provided are directories, and `ediff-directories` instead of `ediff-files` is used; otherwise it checks if they are directories or files, and sets the function to use accordingly.
```
#!/bin/sh
EMACS=$(which emacs)
if [ $# -lt 2 ] ; then
echo "Usage:: " `basename $0` " [ -d ] item1 item2"
exit 1
fi
dir="no"
if [ "$1" = "-d" ]; then
dir="yes"
item1="$2"
item2="$3"
else
if [ -d "$1" -a -d "$2" ]; then
dir="yes"
fi
item1="$1"
item2="$2"
fi
if [ "$dir" = "no" ]; then
# Check that files do exist
if [ ! -f "$item1" ] ; then
printf "File %s not found.\n" "$item1"
exit 2
fi
if [ ! -f "$item2" ] ; then
printf "File %s not found.\n" "$item2"
exit 2
fi
# Check whether files are identical or not
diffdata=`diff "$item1" "$item2"`
if [ "_" = "_$diffdata" ] ; then
printf "%s and %s are identical.\n" "$item1" "$item2"
exit 3
fi
fi
diff_fn="ediff-files"
if [ "$dir" = "yes" ]; then
diff_fn="ediff-directories"
opt="\"\""
fi
# Run Emacs with ediff-files function
printf "Comparing files %s and %s . . . " "$item1" "$item2"
$EMACS -q -nw -eval "($diff_fn \"$item1\" \"$item2\" $opt)" && echo done.
exit 0
```
Since it checks if there are differences in advance, I find it very handy when comparing lots of files in different folders, from the command line, instead of running one single diff session in the parent folders. For example for comparing folders A and B, and copying non-existing files from the first to the other...
# Answer
> 0 votes
If you are using emacs with package manager(ie.**use-package**) then add this snipped to the init.el file
```
(use-package ediff
:config
(setq ediff-split-window-function 'split-window-horizontally)
(setq ediff-window-setup-function 'ediff-setup-windows-plain)
(defun my/command-line-diff (switch)
(setq initial-buffer-choice nil)
(let ((file1 (pop command-line-args-left))
(file2 (pop command-line-args-left)))
(ediff file1 file2)))
;; show the ediff command buffer in the same frame
(add-to-list 'command-switch-alist '("-diff" . my/command-line-diff)))
```
From the command line **$ emacs -diff /path/to/file1 /path/to/file2** will launch files with diff in ediff mode
---
Tags: ediff, invocation, command-line-arguments
--- |
thread-308 | https://emacs.stackexchange.com/questions/308 | Tracking when variables get updated | 2014-09-26T11:00:13.027 | # Question
Title: Tracking when variables get updated
I have a problem with `org-mode`'s agenda view. While I've set `org-agenda-files` to `'("~/org/")` invariably when I finally spin up `M-x` `org-agenda` I find that `org-agenda-files` just points to one org-file. Obviously something is deciding just to include the last org-file I viewed but I'm having trouble working out what. Is there any way to trap when this variable is changed and display or log some sort of backtrace?
# Answer
In this situation, I find that the best way to figure out what's going on into is to visit my `~/.emacs.d/` and run `rgrep`.
## Searching your configs
The following snippet, taken from here, makes sure that `rgrep` doesn't go into the `elpa/` subdir (since you're sure to find dozens of useless hits in there).
```
(eval-after-load 'grep
'(progn
(add-to-list 'grep-find-ignored-directories "auto")
(add-to-list 'grep-find-ignored-directories "elpa")))
```
Then I just run
```
M-x rgrep RET org-agenda-files RET *.el RET ~/.emacs.d/
```
which will find any reference to `org-agenda-files` in my configuration. If it's a problem with my configs, this will find it.
## Searching Elsewhere
If the above doesn't find anything, it means there's an Elpa package causing trouble. So I do
```
M-x rgrep RET org-agenda-files RET *.el RET ~/.emacs.d/elpa/
```
This will usually yield **a lot** of results, but there are ways to go through them quickly. For instance, it's very unlikely that org-mode itself is causing this problem. So it's safe to ignore all hits that come from inside org-modes installation directory.
> 6 votes
# Answer
Another option you have is to track the value of this variable throughout the execution of `org-agenda`, that *has* to tell you where the problem is.
1. Evaluate the following code:
```
(global-set-key [f1] (lambda () (interactive) (message "%s" org-agenda-files)))
```
2. Visit the function with `M-x find-function RET org-agenda`.
3. Edebug it with `C-u C-M-x`.
4. Call the function, `M-x org-agenda`.
5. Gradually step through it by pressing `n`, and monitor the value of the variable by hitting `F1`.
At some point inside the `org-agenda` function, you'll hit `F1` and the value of `org-agenda-files` will have changed. That will tell you where to look.
> 3 votes
# Answer
Since 26.1, you can use `add-variable-watcher` to track the variable where and how be changed.
```
Function: add-variable-watcher symbol watch-function
```
Because the `watch-function` will be called with 4 arguments: `symbol`, `newval`, `operation`, and `where`, you can simply add a watcher in your `init.el`, for example,
```
(add-variable-watcher 'tab-width (lambda (&rest x) (message "Oops! tab-width changed: %S" x)))
```
which gives you some messages like
```
Oops! tab-width changed: (tab-width 2 set #<buffer xxx.el>)
```
> 3 votes
# Answer
Are you ever using `C-c [` (`org-agenda-file-to-front`) or `C-c ]` (`org-remove-file`) while in an `org` file?
These overwrite the current `org-agenda-files` with a hardcoded list of files that will no longer use your defined `~/org/` as a source.
Also if you are setting it to `~/org/` please ensure that the agenda files you want are in that folder with `.org` for the extension. Otherwise they will not be detected.
> 2 votes
---
Tags: org-mode, org-agenda, variables, variable-watchers
--- |
thread-64216 | https://emacs.stackexchange.com/questions/64216 | .svg not exported through org-export + paragraphs not separated after newline | 2021-03-30T20:31:09.933 | # Question
Title: .svg not exported through org-export + paragraphs not separated after newline
I have been constantly trying to render a `logo.svg` found in my custom title-page (included in `#LATEX:`) to match our university title-page for academic writings, but have unfortunately not had success doing so. I have since yesterday been trying to render the `.svg` files included in my `.org` writing, but unfortunately arrived at no solution..
*Note that the following list includes methods I have attempted in a doom-emacs enivronment to resolve the issue while having inkscape, libsvg and imagemagick installed on my system.*
What I have tried by far:
1. Used different formats (`.png`, `.pdf` and `.svg`), but failed to display any image through both `\includegraphics` and `\includesvg`. Keep arriving at: "cannot find file" and I do not know how to resolve this issue. I have tried to use both full/relative paths, but couldn't produce the desired output.
2. `.svg` files located inside `.org` files are not exported through org-export even after including `#+LATEX_HEADERS: \usepackage{svg}`. I suspect that this could be the issue, but I am not certain.
3. `pdflatex -shell-escape file.tex` returns the same issue as org-export does, which is the `.svg` images not being displayed.
Another issue that I am facing is paragraphs not being created for lines separated by a newline between them. Because of this, my text currently looks like one mash of text without any separation, which is in my opinion looking hideous.
If you know how to resolve this issue, please do help me since dropping emacs because of this is in my personal opinion not a wise choice. Not to mention that I am really comfortable in my doom-emacs environment and would prefer it over writing my academic work in google-docs. :/
# Answer
> 2 votes
Solution:
1. Paragraph spacing: add `#+OPTION: \n:t`.
2. Fix svg rendering issue: add --shell-escape to `config.el` (doom-emacs):
```
(setq org-latex-pdf-process
'("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
```
3. Source `logo.svg` in `file.org` based on the relative path of `logo.svg` from `file.org`. In my case the relative path is `src/logo.svg`, which results in: `\includesvg{src/logo.svg}`
Appreciate the help both @ryan\_c\_scott and @hpd from `org-mode` matrix server have provided me and wish that this will be useful to someone else facing the same issue!
---
Tags: org-mode, org-export, latex, linux
--- |
thread-64230 | https://emacs.stackexchange.com/questions/64230 | How to copy one register to another? | 2021-03-31T14:29:53.893 | # Question
Title: How to copy one register to another?
In vim `:let @"=@*` will *copy* the content of`*` register to the `"` register. How can it be done with evil?
# Answer
> 1 votes
This code should do that.
```
(set-register ?" (get-register ?*))
```
If you want that in a command:
```
(defun foo ()
(interactive)
(set-register ?" (get-register ?*)))
```
Or if you want a command that reads the register names:
```
(defun copy-register-to-register (from to)
(interactive
(list (register-read-with-preview "From register: ")
(register-read-with-preview "To register: ")))
(set-register to (get-register from)))
```
(Emacs registers are not particular to Evil, so Evil is, I think irrelevant to your question. Evil may be how you interact with registers, but setting them with Elisp should independent of Evil.)
# Answer
> 0 votes
```
(evil-set-register ?\" (evil-get-register ?*))
```
---
Tags: evil, registers
--- |
thread-64233 | https://emacs.stackexchange.com/questions/64233 | Can I use jump? | 2021-03-31T15:16:24.927 | # Question
Title: Can I use jump?
I found this package for the bash shell that lets you quickly jump between commonly used folders: https://github.com/gsamokovarov/jump
I use it all the time now.
> Jump uses fuzzy matching to find the desired directory to jump to. This means that your search terms are patterns that match the desired directory approximately rather than exactly. Typing 2 to 5 consecutive characters of the directory name is all that jump needs to find it.
Is there a way to use this from inside of Emacs or something equivalent? One option would be to jump to a folder in the shell, then open emacs in that directory. However, it seems like a lot of people just leave emacs open all the time and navigate to files within emacs.
Edit: Thanks! I didn't realize you could do fuzzy matching in Emacs.
By jump I mean, say I have two folders
/home/user/python/space/satellite\_plotter/
/home/user/c\_programs/games/pacman/
In bash with jump, if I am working in the first folder I can just type "j pac" and it will navigate to the second folder. It keeps track of often visited folders and then performs fuzzy matching on this list. I just don't know of a way to do this as quickly in Emacs.
# Answer
What do you mean by jump to a folder (directory), in Emacs?
Do you mean just change the value of `default-directory`? Do you mean open Dired on that directory? For the former, just use `M-x cd` (or bind it to a key). For the latter, just use `C-x d`.
You can use fuzzy matching for any or all inputs you type to Emacs. Even in vanilla Emacs there is now a completion style (option `completion-styles`) called `flex` that provides a simple kind of fuzzy matching.
---
UPDATE after your comment:
* For jumping among recently visited files (and directories), use library `recentf`.
* For jumping among buffers in the current session, just use `C-x b`.
* For jumping among specific places in buffers or files, use Emacs bookmarks. If you use Bookmark+ then you can quickly bookmark positions without needing to name them, and the bookmarks can be temporary (not persist across Emacs sessions), if you like.
> 0 votes
---
Tags: navigation, directories
--- |
thread-64234 | https://emacs.stackexchange.com/questions/64234 | how to include instructions within the enumerate in orgmode latex export? | 2021-03-31T16:07:25.107 | # Question
Title: how to include instructions within the enumerate in orgmode latex export?
I can't seem to find this case in the documentation and it doesn't seem to fit the `LATEX_ATTR` options. How can I get orgmode latex export to produce the following (note the setlength statements WITHIN the enumerate block)?
```
\begin{enumerate}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}}
\item first
\item second
\item third
\end{enumerate}
```
# Answer
> 1 votes
Something like this seems to work as you want:
```
* list
#+ATTR_LATEX: :options \setlength{\itemsep}{1pt} \setlength{\parsep}{0pt} \setlength{\parskip}{0pt}
1. first
2. second
3. third
```
Make sure there is no empty line between the `#+ATTR_LATEX` line and the first list item.
---
Tags: org-mode, org-export, latex
--- |
thread-64235 | https://emacs.stackexchange.com/questions/64235 | bookmark+: The bookmark specific jump handlers don't work: `(wrong-type-argument listp bmkp-dired-history)` | 2021-03-31T16:13:23.483 | # Question
Title: bookmark+: The bookmark specific jump handlers don't work: `(wrong-type-argument listp bmkp-dired-history)`
I have `bookmark+` Version: 2020.12.29
When I try to jump to a dired bookmark (`bmkp-dired-jump`), I get the error:
```
In ‘bmkp-dired-jump History’ source: ‘#[0 \304\302\300\305\303$\211\205\0\306\307\310\301""\207
[nil nil bmkp-dired-history t helm-comp-read-get-candidates nil delete helm-cr-default] 6]’
(wrong-type-argument listp bmkp-dired-history)
```
When I change the expression:
```
(list (bmkp-read-bookmark-for-type "Dired" alist nil nil 'bmkp-dired-history)
current-prefix-arg)
```
to
```
(list (bmkp-read-bookmark-for-type "Dired" alist nil nil nil)
current-prefix-arg)
```
in the function `bmkp-dired-jump`, it works as expected. I don't understand the use of the symbol `'bmkp-dired-history` since it doesn't seem to be bound anywhere?
Is this a problem of my setup or a problem with `bookmark+` and how can I solve it?
# Answer
I don't see what you report. For me, it just works.
(But you might want to try the latest version of Bookmark+, which is `2021.03.04`, not `2020.12.29`. Download the latest version from Emacs Wiki Elisp Area.)
Do you see the same thing if you start Emacs using `emacs -Q` (no init file), and loading only Bookmark+? If not, bisect your init file to find the culprit.
(If you need to try to debug something, or want to see a better backtrace for `debug-on-error`, then load the *source* files, `*.el`, not byte-compiled files, `*.elc`.)
Symbol `bmkp-dired-history` is passed as the optional arg `HIST`, which is for an Emacs history variable. It is passed to `bookmark-completing-read`, which in turn ultimately passes it to standard Emacs function `completing-read`.
The symbol passed for a history argument need not be bound; that is, it need not yet exist as a variable that has a value. As you enter inputs to calls that specify a given history variable (such as `bmkp-dired-history`) they are added to the list value of that variable. The first time you do so, since the variable is not yet bound Emacs creates it, and binds it to a singleton list with just the value you entered.
This is all standard Emacs behavior.
If you encounter this problem (or some other) when starting Emacs with `emacs -Q` then please report it using `M-x bmkp-send-bug-report`.
> 1 votes
---
Tags: bookmarks
--- |
thread-63900 | https://emacs.stackexchange.com/questions/63900 | How auto set "diredc" mode when start Emacs? | 2021-03-14T18:30:17.733 | # Question
Title: How auto set "diredc" mode when start Emacs?
Linux Mint 20.1
Emacs 26.3
I install package "**diredc**". https://github.com/Boruch-Baum/emacs-diredc
To start in I use: `M-x diredc`
Nice. It's work fine.
But problem is when I restart Emacs I need again execute `M-x diredc` to switch it diredc mode.
Is it possible to autoset diredc mode when run Emacs?
# Answer
> 1 votes
It should be no different than auto-starting any other emacs package, so you should be able to add a snippet to your emacs' init file to do what you want:
1. The "old" way would be to use elisp command `require` to force loading of the package, and then maybe add commands to assign key-bindings, and maybe start an instance of it;
2. The fashionable "new" way that all the cool kids have started using would be to use elisp package `use-package` and go to town with all its features for configuring and and assigning keybindings and and what-not.
---
Tags: dired
--- |
thread-64222 | https://emacs.stackexchange.com/questions/64222 | Insert link to a heading with ID | 2021-03-31T04:14:08.717 | # Question
Title: Insert link to a heading with ID
Running Doom Emacs 2.0.9 on Emacs 27.1.
In an org file, I have:
```
* First heading
:PROPERTIES:
:ID: 89f7215b-60b1-45c8-8262-b0e10db18f4c
:END:
* Second heading
```
I got that ID by using `org-id-store-link` function.
Now, I want to insert a link to that heading. So, I did `org-insert-link` and it displayed various options. I was looking forward to some kind of auto-completion --- I start typing Firs.. and it suggests the correct link.
But that does not seem to be happening.
How do I get that behavior?
# Answer
> 6 votes
You need to enable ID links by customizing the option `org-id-link-to-org-use-id`. The doc string of the variable says:
> Non-nil means storing a link to an Org file will use entry IDs.
>
> The variable can have the following values:
>
> t
>
> ```
> Create an ID if needed to make a link to the current entry.
>
> ```
>
> create-if-interactive
>
> ```
> If ‘org-store-link’ is called directly (interactively, as a user
> command), do create an ID to support the link. But when doing the
> job for capture, only use the ID if it already exists. The
> purpose of this setting is to avoid proliferation of unwanted
> IDs, just because you happen to be in an Org file when you
> call ‘org-capture’ that automatically and preemptively creates a
> link. If you do want to get an ID link in a capture template to
> an entry not having an ID, create it first by explicitly creating
> a link to it, using ‘C-c l’ first.
>
> ```
>
> create-if-interactive-and-no-custom-id
>
> ```
> Like create-if-interactive, but do not create an ID if there is
> a CUSTOM_ID property defined in the entry.
>
> ```
>
> use-existing
>
> ```
> Use existing ID, do not create one.
>
> ```
>
> nil
>
> ```
> Never use an ID to make a link, instead link using a text search for
> the headline text.
>
> ```
I'd start by setting it to `use-existing` and go from there.
---
Tags: org-mode, org-link
--- |
thread-60437 | https://emacs.stackexchange.com/questions/60437 | How to improve ‘jedi‘ package's load time | 2020-09-01T21:35:39.910 | # Question
Title: How to improve ‘jedi‘ package's load time
When I try to use jedi package I get following message in the minibuffer.
```
This feature requires the ‘jedi‘ package to be installed. Please check ‘elpy-config‘ for more information.
```
---
```
Elpy Configuration
Emacs.............: 26.3
Elpy..............: 1.34.0
Virtualenv........: venv (/home/alper/venv)
Interactive Python: python3 3.7.5 (/home/alper/venv/bin/python3)
RPC virtualenv....: rpc-venv (/home/alper/.emacs.d/elpy/rpc-venv)
Python...........: python 3.7.5 (/home/alper/.emacs.d/elpy/rpc-venv/bin/python)
Jedi.............: 0.17.2
Rope.............: 0.16.0
Autopep8.........: 1.5.3 (1.5.4 available)
Yapf.............: 0.29.0 (0.30.0 available)
Black............: 19.10b0 (20.8b1 available)
Syntax checker....: flake8 (/home/alper/venv/bin/flake8)
```
---
After few minutes it starts working or when I restart `emacs` there are some cases that it starts working right way. So its behavior is random for its load time to start.
**=\>** Is there anything I can do to prevent this error to force `jedi` to start right away? or is this a normal behavior of `jedi`?
Please note that I had similiar question (elpy - This feature requires the ‘jedi‘ package to be installed), but it was not related to `jedi` package's load time.
# Answer
While switching configurations I've came across this issue yet again and I believe I have a workaround for this if you're still interested.
The steps I do to reproduce:
* start fresh emacs,
* `venv-workon` to activate a virtualenv,
* open a python buffer,
* try `elpy-goto-definition`, receive the same error message you did.
* (`elpy-config` confirms everything is ok)
Now, I was under the impression that `elpy-goto-definition` will just utilize the same mechanism as `xref-find-definitions`, but apparently that's not exactly the case. If I try to run the latter, something else happens the first time around (which might be triggering the connection to rpc) and I get a different error message. But the second time around it is already connected and I can use it at will.
This is assuming that `xref-backend-functions` includes `elpy-xref-backend`.
Please let me know if this solves the issue and if you have dug deeper to explain the reasoning behind the bug.
> 1 votes
---
Tags: performance, load, jedi
--- |
thread-64242 | https://emacs.stackexchange.com/questions/64242 | Is there toggle-syntax package for parens, brackets, brokets, braces? | 2021-03-31T22:21:45.983 | # Question
Title: Is there toggle-syntax package for parens, brackets, brokets, braces?
I rely on toggle-quotes (to switch between single and double quotes), but I'm not finding any available packages that can do the same for switching between pairs of `( [ { <`. I'd expect it to cycle between the four (and maybe `/`). Does it exist (yet)?
# Answer
> 1 votes
This is a simplistic way to accomplish it for lisp modes (for the limited cases I just tried), using some smartparens functions:
```
(defun toggle-parens ()
"Toggle parens, braces, brackets."
(interactive)
(save-excursion
(when (not (string-match-p (regexp-quote (char-to-string (char-after))) "([{<"))
(sp-backward-up-sexp)
(when (eq ?\" (char-after)) ; up again if inside string
(sp-backward-up-sexp)))
(progn
(sp-wrap-with-pair
(case (char-after)
(?\( "[")
(?\[ "{")
(?\{ "(")
;; smartparens can't wrap with <
;; (?\< "(")
))
(forward-char)
(sp-splice-sexp))))
(global-set-key (kbd "C-c S") 'toggle-parens)
```
---
Tags: delimiters
--- |
thread-64245 | https://emacs.stackexchange.com/questions/64245 | Need to make a function that uses &rest and sums the rest of parameters together | 2021-04-01T03:09:15.280 | # Question
Title: Need to make a function that uses &rest and sums the rest of parameters together
I am learning ELISP and this function should gather any number of parameters plus N and return the sum. This what I've got so far and I cannot figure out where my error is. Also if a char is in the list it should just skip over and not add that to the value.
```
(defun sum-numbers (n &rest L)
(let (a 0)
(if (not L) n
(dolist (x L result)
(if (integerp x)
(setq a (+ x a)))))
(setq a (+ a n))))
```
# Answer
```
(defun sum-numbers (n &rest L)
(let ((a 0))
(if (not L) n
(dolist (x L a)
(if (integerp x)
(setq a (+ x a))))
(setq a (+ a n)))))
```
an other solution using a sequence function:
```
(defun sum-numbers (n &rest L)
(apply #'+ (cons n (seq-filter #'integerp L))))
```
> 0 votes
---
Tags: functions
--- |
thread-64249 | https://emacs.stackexchange.com/questions/64249 | Where does my key bind so I can unbind it in major mode | 2021-04-01T11:06:54.607 | # Question
Title: Where does my key bind so I can unbind it in major mode
I changed my key bindings with this lines in my `.init.d`:
`(global-set-key "\C-i" 'previous-line)`
It works normally, but when I change to `markdown-mode`, key rebinds to something else, how can I disable that binding and keep this original one.
# Answer
> 2 votes
Markdown has defined the key `C-i` in it's own keymap. This keymap is named `markdown-mode-map`. Markdown's mode-map has a higher priority than your global binding and therefore it shadows you global binding.
You can verify this, by pressing `C-h k C-i` in markdown-mode.
If you want your global keybinding not shadowed, then you have to remove the keybinding from Markdowns's mode-map. You do that by setting the value `nil` to that keybinding:
```
(define-key markdown-mode-map (kbd "C-i") nil)
```
---
Tags: key-bindings, major-mode
--- |
thread-58463 | https://emacs.stackexchange.com/questions/58463 | project.el: override project root with dir-local var? | 2020-05-12T14:26:32.530 | # Question
Title: project.el: override project root with dir-local var?
I have a situation where `(project-current)` gets the project root "wrong", i.e. not what I want it to be - specifically the project is part of a larger project that `project.el` doesn't know about. Is there any way to override that, using perhaps a dir-local variable or some other method?
# Answer
I ran into this, too, and published the `project-find-functions` hook I use on https://michael.stapelberg.ch/posts/2021-04-02-emacs-project-override/:
```
;; Returns the parent directory containing a .project.el file, if any,
;; to override the standard project.el detection logic when needed.
(defun zkj-project-override (dir)
(let ((override (locate-dominating-file dir ".project.el")))
(if override
(cons 'vc override)
nil)))
(use-package project
;; Cannot use :hook because 'project-find-functions does not end in -hook
;; Cannot use :init (must use :config) because otherwise
;; project-find-functions is not yet initialized.
:config
(add-hook 'project-find-functions #'zkj-project-override))
```
Hope this helps :)
> 3 votes
# Answer
No buffer-local vars available as an option, but you can add your own element to `project-find-functions` which would call `project-current` in some parent directory.
> 2 votes
---
Tags: project
--- |
thread-64253 | https://emacs.stackexchange.com/questions/64253 | Unable to set gofmt-args in Go mode | 2021-04-01T18:43:41.377 | # Question
Title: Unable to set gofmt-args in Go mode
I am unable to set gofmt arguments to consume the following arguments
`-tabs=false -tabwidth=2 -w=true`
When I set the variable gofmt-args, I get the following error **Invalid read syntax: "Trailing garbage following expression"**.
If I give just one argument such as `-tabwidth=2`, I get the error **Value ‘-tabwidth=2’ does not match type repeat of gofmt-args**
Any suggestions on how to fix this?
# Answer
> 2 votes
Based on the error, it looks like you tried passing an unquoted string to set `gofmt-args`. `gofmt-args`'s type is a list of strings, so that is what you need to give it. You can set it like this:
```
(setq gofmt-args '("-tabs=false" "-tabwidth=2" "-w=true"))
```
If you are setting it interactively, its probably easiest to use `M-x customize-variable RET gofmt-args RET`. That will give you an interactive UI for adding and removing elements from the list and you don't need to worry about quoting.
---
Tags: formatting, golang
--- |
thread-64218 | https://emacs.stackexchange.com/questions/64218 | mark-whole-region and pbcopy without losing current point/region | 2021-03-31T01:13:12.140 | # Question
Title: mark-whole-region and pbcopy without losing current point/region
I wrote a hydra today (I think my very first one) - I always do `Meta-| pbcopy` after doing a `C-x h`, so why not let hydra help out:
```
(global-set-key
(kbd "C-x h")
(defhydra hydra-my-mark-whole-buffer
(:body-pre (mark-whole-buffer))
"hydra-my-mark-whole-buffer"
("h" mark-whole-buffer "this was not needed")
("p" my-pbcopy "Meta-| pbcopy")))
;; https://emacs.stackexchange.com/a/13177
(defun my-pbcopy (beg end)
(interactive "r")
(message (if (zerop (shell-command-on-region beg end "pbcopy")) "copied" "copy failed")))
```
(btw I'm always in `emacsclient -nw` mode)
Anyway, I'd like two more things:
* not lose the point/position
* if a region was marked before calling the hydra, if should stay that way after `pbcopy` has been done.
How can I tweak my code to do that?
# Answer
> 0 votes
In general, if you want to run a command but maintain the initial point, you would wrap the function in `(save-excursion ...)`
From the documentation: https://www.gnu.org/software/emacs/manual/html\_node/eintr/save\_002dexcursion.html:
> In Emacs Lisp programs used for editing, the save-excursion function is very common. It saves the location of point, executes the body of the function, and then restores point to its previous position if its location was changed. Its primary purpose is to keep the user from being surprised and disturbed by unexpected movement of point.
---
Tags: hydra
--- |
thread-64262 | https://emacs.stackexchange.com/questions/64262 | How to use mouse click to the right or to the left of the text to move cursor to this line? | 2021-04-02T10:28:54.113 | # Question
Title: How to use mouse click to the right or to the left of the text to move cursor to this line?
On a mouseclick to one side of the text, it can be convenient to make the cursor jump to:
1. the beginning of the line (when clicking left of the text)
2. the end of the line (when clicking right of the text)
This is the default behaviour of most text editors (also the one used for editing this very entry), so it can help to make emacs more beginner (user?) friendly.
Currently, the cursor either doesn't move (1.) or it jumps to the beginning of the next line (2.). Most people probably use `C-E` instead, but it would be good to be able to leave that out.
# Answer
> 1 votes
This should do it. Bind commands to keys `[left-fringe mouse-l]` and `[right-fringe mouse-l]`. The commands pick up the click position and move point to the beginning or end of the text for that line.
```
(defun mouse-goto-bol (click)
"Move to beginning of line for mouse-1 click in left fringe."
(interactive "e")
(mouse-goto-line click 'left))
(defun mouse-goto-eol (click)
"Move to beginning of line for mouse-1 click in left fringe."
(interactive "e")
(mouse-goto-line click 'right))
(defun mouse-goto-line (click left/right)
"Helper for `mouse-goto-(bol|eol)'."
(let* ((posn (event-start click))
(click-pt (posn-point posn))
(window (posn-window posn))
(buf (window-buffer window))
(clicks (if (eq mouse-selection-click-count-buffer buf)
(event-click-count click)
0)))
(when (= clicks 1) ; No-op if not single-click.
(with-current-buffer buf
(goto-char click-pt)
(if (eq 'left left/right)
(line-beginning-position)
(line-end-position))))))
(global-set-key [left-fringe mouse-1] 'mouse-goto-bol)
(global-set-key [right-margin mouse-1] 'mouse-goto-eol)
;; (global-set-key [right-fringe mouse-1] 'mouse-goto-eol) ; To use the right fringe.
;; (global-set-key (kbd "<mouse-1>") 'mouse-goto-eol) ; Useless, since click in text area does it by default.
```
---
Tags: motion, mouse, cursor, fringe
--- |
thread-64259 | https://emacs.stackexchange.com/questions/64259 | Why does `next-error` change my buffer as keyboard macro, but not in lisp code? | 2021-04-02T05:16:16.483 | # Question
Title: Why does `next-error` change my buffer as keyboard macro, but not in lisp code?
My goal is to use `grep` to find other Org files, use `next-error` to switch to those files, copy the link to the `grep` match, then go back and paste that link.
It worked for a long time as a macro, but when it finally broke I decided to write it as a proper function. But the buffer-switches that worked as macro don't seem to be working as a function. Why?
```
;; Can't use `with-current-buffer' because it's used in `next-error'
(let ((thisbuf (current-buffer)))
;; Unless interactive, this doesn't change `current-buffer', at least not in time for `org-store-link'
(next-error)
;; Message says thisbuf, not the one `next-error' takes me to
(message (concat "Current buffer: " (current-buffer)))
;; Why does it store my link in `thisbuf' instead of the buffer `next-error' goes to?
(org-store-link nil 1)
(switch-to-buffer thisbuf))
```
# Answer
This should do it.
```
(defun foo ()
(interactive)
(add-hook 'next-error-hook 'toto)
(let ((thisbuf (current-buffer)))
(next-error)
(switch-to-buffer thisbuf))
(remove-hook 'next-error-hook 'toto))
(defun toto ()
(message "Current buffer: %s" (current-buffer))
(org-store-link nil))
```
It fixes three problems:
1. `(current-buffer)` returns a buffer, not its name. You can't `concat` a buffer.
2. `org-store-link` accepts only one argument.
3. `next-error` puts you back in the original buffer. You need to use its hook if you want to do something in the source buffer that it moves to.
But this is really all you need for `foo` (see #3 above):
```
(defun foo ()
(interactive)
(add-hook 'next-error-hook 'toto)
(next-error)
(remove-hook 'next-error-hook 'toto))
```
> 2 votes
---
Tags: buffers, org-link, next-error
--- |
thread-44144 | https://emacs.stackexchange.com/questions/44144 | Arabic in Terminal mode | 2018-08-15T19:33:05.220 | # Question
Title: Arabic in Terminal mode
I know that emacs supports Arabic and I have seen many questions on Arabic support but my problem here is specifically with emacs in the terminal.
It can be seen in the image bellow in the left side that the text is shown correctly in the GUI mode. However the problems appear in the terminal in the middle and right frames of the screenshot.
In the middle one, it is just emacs running normally from the terminal. Here the letters are shown in the correct order from right to left but the problem is that the letters are separated.
A classical solution to problems with Arabic in the terminal is BiCon. It works pretty well with programs that are not aware of right to left languages.
In the right of the image emacs can be seen running under BiCon. The letters here are connected, which is good, but it is in the reversed order. I Believe that this is because emacs is already taking care of order and then BiCon is reversing it back.
One last thing to mention is that I tried some different terminals including xterm, gnome-terminal, konsole, and mlterm.
Any suggestions?
# UPDATE:
This is not really a solution but it's workaround.. Using python-arabic-reshaper save this as ar-reshaper.py:
```
import arabic_reshaper
import sys
for line in sys.stdin:
sys.stdout.write(arabic_reshaper.reshape(line))
```
Then:
```
cat INPUTFILE | python3 ar-reshaper.py > OUTPUTFILE
```
The OUTPUTFILE will be the reshaped version of INPUTFILE with the connected Arabic letters and the result on emacs:
But still, an actual solution is needed...
# UPDATE:
Reported as bug and here's a little minor-mode if anyone is interested
# Answer
The solution was simply to disable the bidi in bicon.
THIS fork can achieve that by:
```
bicon.bin --reshape-only emacs -nw
```
> 2 votes
# Answer
See here for an up-to-date version of this guide.
* Install `bicon` (using the fork linked above, or the original)
* Use these wrappers to open emacs:
```
function bicon-emc() {
bicon.bin --reshape-only emacsclient -t "$@"
reset
}
```
Take care not to run this from a shell that is itself running under `bicon`. You need to use this function if you want to do so:
```
biconm () {
BICON_MODE=y bicon.bin "$@"
}
bicon-zsh () {
biconm zsh
reset
}
isBicon () {
test -n "$BICON_MODE"
}
bicon-emc () {
if isBicon
then
{
(
emacsclient -t -e "(progn (setq-default bidi-display-reordering nil) (redraw-display))" "$@"
)
} always {
emacsclient -e "(setq-default bidi-display-reordering t)"
}
return $?
fi
biconm --reshape-only emacsclient -t "$@"
reset
}
```
And it will still not be good for editing RTL text, as Emacs is confused by the bidi reversal that `bicon` does.
Related projects:
> 0 votes
---
Tags: terminal-emacs, right-to-left
--- |
thread-20279 | https://emacs.stackexchange.com/questions/20279 | Mouse pointer between characters and the text cursor misplacement | 2016-02-13T15:11:18.047 | # Question
Title: Mouse pointer between characters and the text cursor misplacement
Mouse cursor position interpretation in emacs drives me nuts.
Why draw the mouse cursor in emacs window with vertical thin bar if you cannot effectively position it between characters?
Selecting text with mouse in emacs is drastically different from all other editors in both X Window and MS Windows.
I mean when the mouse cursor is exactly between two consequent characters, clicking mouse puts the point one character back from the mouse position.
In other words, to put the point somewhere in the text with the mouse you need to click on the character *to the right* of the place of expected point appearance.
If you, by muscle memory acquired from years of work in other editors, click exactly between two characters (or just a single pixel to the left for that matter) you end up with the point one character back from what was intended for it.
In my opinion the correct behavior would be to position the point to the left of the character **only when the mouse cursor is over the *left half* of the character**, and put it to the right otherwise.
An obvious solution to this would be to draw the mouse cursor offset by half a character width to the left from what it is in emacs by default. Or, to shift the mouse cursor hot point to the right for the emacs windows.
Is there an easy way to achieve that?
I suppose I need to clarify that I use a thin cursor of 2-pixel-wide vertical bar (i.e. `(setq-default cursor-type '(bar . 2))`). With a cursor in a traditional terminal style of a full-character rectangle this issue would not be so evident.
# Answer
> 5 votes
First, you are apparently confusing the **mouse pointer** with the **text cursor** (aka cursor). It seems that you mostly talking about the latter, but referring to it as the "cursor".
Second, insertion of a character is *always between characters* (or before the first or after the last character). This is necessarily so, by definition. Even if it were to behave and be conceived as replacing an existing character by the one you want to insert, that insertion would still be between two chars (or before the first or after the last).
Third, as for the *representation* of the (text) cursor: you have a choice. You can use a narrow vertical bar or a box, hollow or solid (on some platforms there might be additional options). If you choose a box cursor then the box is placed on top of the character to the right of the insertion point.
You apparently already know how to change the (text) cursor style, and have opted for a bar. But your rant/question is more about the mouse pointer shape, I think, as it is apparently the pointer position (the part of the pointer shape that matters, determining where a click really is) that is throwing you off.
Fourth, you ask about setting point (the text cursor position) by clicking the mouse (left mouse button, aka `mouse-1`). You say that clicking with the mouse pointer positioned exactly between two chars ends up setting point to the left of the character on the left of the pointer, and not at the pointer (between the two characters).
> clicking mouse puts the point one character back from the mouse position
And:
> Why draw the mouse cursor in emacs window with vertical thin bar if you cannot effectively position it between characters?
I don't see that behavior. I position the I-beam pointer (which is what I think you mean here) between two characters, click it, and get the text insertion position (and the text cursor) between those characters.
If you can reproduce the behavior you describe then it is a bug, I think. Use `M-x report-emacs-bug` to report it.
However, I suspect that the problem is that you are positioning the wrong *part* of your mouse pointer. What you call "*mouse position*" is probably not the position of the part of the pointer that matters.
Just as for text cursor representation, the mouse pointer can be represented in different ways. If it is an arrow of some kind, the pointer position (which sets point when you click `mouse-1`) is often the tip of the arrow. Find out exactly which part of your pointer is used, and then get used to that.
You say that Emacs behaves differently from the other programs you are used to, with respect to the pointer. Maybe your experience is limited? Having used all kinds of programs on lots of different platforms ever since computers had pointers and cursors, I can say that the behavior and representations are variable. And they vary in Emacs too, depending on the platform.
You can also easily change the pointer representation (choose another pointer). See the Elisp manual, node Pointer Shape.
It is also the case that, by default, the pointer shape changes depending on where it is, depending, in fact, on what you can do with it at that position. At a position where you can insert text it is often a vertical I-beam shape (an insertion pointer). At other positions it is often an arrow.
# Answer
> 3 votes
I suggest you file this as a bug or a feature request with `M-x report-emacs-bug`.
It can probably be fixed to some extent in Elisp by tweaking `mouse-set-point` as Vladimir suggested: this function receives as part of its input a "position" information which includes additionally to the character position (the one you think is wrong) both the DX/DY pixel position of the click within this character and the WIDTH/HEIGHT pixel size of the character, so you should be able to pick the next char when DX is more than half of WIDTH.
Making it 100% reliable would likely be a lot more tricky because "the next char" is not nearly as simple as it sounds when you want to account for bidirectional text, invisible text and whatnot, but at least variable char width, scrollbars, fringes, margins etc... should be a non-issue, contrary to what Vladimir seemed to think.
You can read the details of the format of `mouse-set-point`'s argument in the Elisp manual in Command Loop =\> Input Events =\> Click Events.
It'd probably be even better to tweak `posn-set-point` (used internally be `mouse-set-point`). E.g. the patch below seems to work for me:
```
diff --git a/lisp/subr.el b/lisp/subr.el
index 24595e8494..44710c3cb6 100644
--- a/lisp/subr.el
+++ b/lisp/subr.el
@@ -1369,8 +1369,17 @@ posn-set-point
(if (not (windowp (posn-window position)))
(error "Position not in text area of window"))
(select-window (posn-window position))
- (if (numberp (posn-point position))
- (goto-char (posn-point position))))
+ (let ((pos (posn-point position)))
+ (if (numberp pos)
+ (goto-char (if (and (eq 'bar (or (car-safe cursor-type) cursor-type))
+ (< pos (point-max))
+ (consp position)
+ (numberp (car-safe (posn-object-x-y position)))
+ (numberp (car-safe (posn-object-width-height position)))
+ (> (* 2 (car (posn-object-x-y position)))
+ (car (posn-object-width-height position))))
+ (1+ pos)
+ pos)))))
(defsubst posn-x-y (position)
"Return the x and y coordinates in POSITION.
```
# Answer
> 0 votes
I've reported this as a bug. For convenience, here is a version of @Stefan's code that can be added to `.emacs` for a temporary bugfix:
```
(defun posn-set-point (position)
"Move point to POSITION.
Select the corresponding window as well."
(if (not (windowp (posn-window position)))
(error "Position not in text area of window"))
(select-window (posn-window position))
(let ((pos (posn-point position)))
(if (numberp pos)
(goto-char (if (and (eq 'bar (or (car-safe cursor-type) cursor-type))
(< pos (point-max))
(consp position)
(numberp (car-safe (posn-object-x-y position)))
(numberp (car-safe (posn-object-width-height position)))
(> (* 2 (car (posn-object-x-y position)))
(car (posn-object-width-height position))))
(1+ pos)
pos)))))
```
This doesn't cover mouse dragging for selecting text, which has the same problem.
---
Tags: cursor, mouse, point
--- |
thread-64280 | https://emacs.stackexchange.com/questions/64280 | What exactly is ~/org/? | 2021-04-03T19:33:26.173 | # Question
Title: What exactly is ~/org/?
Sorry for the greenness of this question but I am starting with Org mode to replace Markdown and I don't really understand `org/`: what to do with `/` what the `org` directory is?
I looked through some basic tutorials and the Org website but I couldn't find anything concrete. I have a git repo that I store notes in (`.md` files) and I have started adding `.org` files to this repo. Is this alright or do all files have to be in the `org` directory?
# Answer
> 2 votes
Any path starting with a tilde and a slash automatically refers to your home directory. On my computer, `~/org` expands to `/home/db48x/org`; on your computer it will expand to something appropriate for your computer and username.
`org-mode` doesn’t care where the files are though; you can put them wherever you want. `~/org` is just a convenient location for a tutorial to tell you to put them, because it is short and memorable, and the tilde means that it will automatically go into your home directory; the tutorial doesn’t have to know your username or tell you to type in your username.
---
Tags: org-mode
--- |
thread-64282 | https://emacs.stackexchange.com/questions/64282 | Modify the first element of the kill-ring | 2021-04-04T03:38:45.337 | # Question
Title: Modify the first element of the kill-ring
I have stored in my clipboard a path to an image, which I want to paste inside emacs.
I would like to modify the path to change/postpone/prepone some stuff before yanking.
Following my previous question here, I tried
```
(defun replace-in-string (what with in)
(replace-regexp-in-string (regexp-quote what) with in nil 'literal))
(defun paste-image-link ()
(interactive)
(let ((tmp (car kill-ring))))
(setq tmp (replace-in-string "E:\\Dropbox\\JULIEN\\01.Emacs"
"../.."
tmp))
(setq tmp (concat "[[file:" tmp "]]"))
(setq kill-ring (cons tmp (cdr kill-ring)))
(yank)
)
(global-set-key (kbd "M-i") 'paste-image-link)
```
My goal is to change the absolute path to a relative path and add `[[file:` before.
For example, this :
```
E:\Dropbox\JULIEN\01.Emacs\02.Emacs screenshots\2021-04-04_02-23-12_vivaldi.png
```
should become :
```
[[file:../..\02.Emacs screenshots\2021-04-04_02-23-12_vivaldi.png]]
```
I am obviously making trivial mistakes about `let` and `setq`statements because I get instead :
```
[[file:[[file:[[file:[[file:[[file:[[file:[[file:(car kill-ring)]]]]]]]]]]]]]]
```
and the number of `[[file:`before is growing each time i try
what should I do ?
Addendum : *besides* i would like to add a line before to finally get
```
#+ATTR_ORG: :width 300px
[[file:../..\02.Emacs screenshots\2021-04-04_02-23-12_vivaldi.png]]
```
# Answer
Mostly your problem was misplaces parens: too many `)` here:
```
(let ((tmp (car kill-ring))))
```
Use `paren-mode` to see which parens balances which parens.
---
Standard function `kill-new` replaces the head of the `kill-ring` if you give it a second arg of non-`nil`. So `(kill-new "xxx" t)` replaces the head of the `kill-ring` with `xxx`.
So try this:
```
(defun foo ()
(interactive)
(let ((new (format "[[file:%s]]" (replace-in-string
"E:\\Dropbox\\JULIEN\\01.Emacs" "../.."
(car kill-ring)))))
(kill-new new t)))
```
You can add the `yank` or whatever to do that and add whatever other lines you want.
---
But a guess is that maybe you don't really need to change the kill-ring, you just want to be able to grab its head and from that produce a different string to then insert. That you can do directly, using `insert` after getting the head of the ring and from that getting the string you want to insert.
---
Also, it's pretty unusual to modify `kill-ring` entries. Usually it's enough, if you need something on the ring, just to put it there, not caring about what other elements are already on the ring. Use `kill-new` (without second arg) to add a to the front of the ring.
---
Finally, if you're using file names ("paths"), just use `/` always, in Emacs, as the directory separator char, not `\\`, even on MS Windows. Emacs just does the right thing - there's pretty much never any need to use `\\` for that.
> 2 votes
---
Tags: kill-ring, insert, filenames
--- |
thread-64256 | https://emacs.stackexchange.com/questions/64256 | What is the mode for org's LOGBOOK editing window and how can one be created if it doesn't already exist? | 2021-04-02T00:48:17.610 | # Question
Title: What is the mode for org's LOGBOOK editing window and how can one be created if it doesn't already exist?
I want to wrap the LOGBOOK editing window at column width I'm yet to decide.
From another answer here I see need to set something along the lines of `(add-hook 'some-logbook-mode-hook #'auto-fill-mode)` and `(setq fill-column wrap-point)`
Does the `LOGBOOK` window have its own mode, or will I have to create a new mode for it if want to use a hook to set the mode?
# Answer
> 0 votes
Open the logbook and use `C-h m` to find out what the major mode is. You’ll also find there any documentation for the mode, the keybindings that are active, and a link to the source code should you need it.
As a general rule, Emacs is intended to be self–documenting; you can always ask Emacs what is going on, and it always gives you as much information as it can. This includes the source code, with the ability to jump to the definition of any variable, function, mode, keymap, etc.
---
Tags: org-mode, hooks, fill-column
--- |
thread-64277 | https://emacs.stackexchange.com/questions/64277 | How to make two fixes to mouse click positioning work together? | 2021-04-03T13:04:21.207 | # Question
Title: How to make two fixes to mouse click positioning work together?
There are subtle issues with mouse-click cursor positioning which I try to get fixed.
The first patch makes sure that the cursor falls on the correct side of a character when clicked left of right from its center.
The second patch makes sure that when we click left or right of text, the cursor ends up at the beginning or end of the text.
Separately, they work fine. When combined, they lead to an erratic jump-back of the cursor after it had been already placed.
Here is a reproducer:
1. run the combined code below
2. open some text buffer and click into the text in different places
3. observe where exactly the cursor bar ends up with relation to the positon of the mouse click
At some positions, the cursor bar is briefly visible in the correct position, and then jumps back one step. This is the position it would have ended up with out the fix in `posn-set-point`
The question is how to make the cursor end up in the right position always.
Here is the combined code:
```
(setq-default cursor-type 'bar)
(defun posn-set-point (position)
"Move point to POSITION.
Select the corresponding window as well."
(if (not (windowp (posn-window position)))
(error "Position not in text area of window"))
(select-window (posn-window position))
(let ((pos (posn-point position)))
(if (numberp pos)
(goto-char (if (and (eq 'bar (or (car-safe cursor-type) cursor-type))
(< pos (point-max))
(consp position)
(numberp (car-safe (posn-object-x-y position)))
(numberp (car-safe (posn-object-width-height position)))
(> (* 2 (car (posn-object-x-y position)))
(car (posn-object-width-height position))))
(1+ pos)
pos)))))
(defun mouse-goto-bol (click)
"Move to beginning of line for mouse-1 click in left fringe."
(interactive "e")
(mouse-goto-line click 'left))
(defun mouse-goto-eol (click)
"Move to beginning of line for mouse-1 click in left fringe."
(interactive "e")
(mouse-goto-line click 'right))
(defun mouse-goto-line (click left/right)
"Helper for `mouse-goto-(bol|eol)'."
(let* ((posn (event-start click))
(click-pt (posn-point posn))
(window (posn-window posn))
(buf (window-buffer window))
(clicks (if (eq mouse-selection-click-count-buffer buf)
(event-click-count click)
0)))
(when (= clicks 1) ; No-op if not single-click.
(with-current-buffer buf
(goto-char click-pt)
(if (eq 'left left/right)
(line-beginning-position)
(line-end-position))))))
(global-set-key [left-fringe mouse-1] 'mouse-goto-bol)
;;(global-set-key [right-fringe mouse-1] 'mouse-goto-eol)
(global-set-key (kbd "<mouse-1>") 'mouse-goto-eol)
```
The solutions are from:
EDIT: another solution for the correction of the click between characters is here: https://www.emacswiki.org/emacs/DelicateMouseClick It has the same issue that it breaks the click on fringe (cursor jumps to the next beginning of line when on right fringe)
# Answer
Does using `<down-mouse-1>` instead of `<mouse-1>` fix it?
If I use your original code and then use `C-h k` to check the command run by a mouse click, I'm seeing commands running for *both* those events -- which probably explains the odd behaviour.
> 1 votes
---
Tags: mouse, cursor
--- |
thread-27094 | https://emacs.stackexchange.com/questions/27094 | How to make hyperlinks clickable in markdown mode? | 2016-09-15T19:50:54.723 | # Question
Title: How to make hyperlinks clickable in markdown mode?
In an emacs org-mode buffer it is possible to type a hyperlink and then click on the hyperlink with a mouse to open the url in an external browser.
Is there a way for markdown mode to have active hyperlinks as well?
# Answer
> 5 votes
In the current development version of Markdown mode, links are now clickable without requiring any additional libraries. URLs can also be hidden, and you can hover your mouse pointer to see the URL and optional title text.
# Answer
> 9 votes
This isn't easy enough to find, but what you want is goto-address-mode. You can activate it in the current buffer with `M-x goto-address-mode` or you can add it to markdown-mode-hook:
```
(defun turn-on-goto-address-mode ()
(goto-address-mode 1))
(add-hook 'markdown-mode-hook #'turn-on-goto-address-mode)
```
# Answer
> 0 votes
Answering my own question, here's the setup I use now to make clickable hyperlinks in prog-mode (useful for URLs within comments) and text-mode (which includes markdown).
```
(use-package goto-addr
:bind
(:map goto-address-highlight-keymap
("C-c C-o" . goto-address-at-point))
:hook ((prog-mode . goto-address-prog-mode)
(text-mode . goto-address-mode)))
```
# Answer
> -1 votes
> In an emacs org-mode buffer it is possible to type a hyperlink and then click on the hyperlink with a mouse to open the url in an external browser.
**Yes this can be done without any additional code**.
The format in which you have enter URLs in `org-mode` file is `[[http://www.google.co.in][Google India]]`. This will open the webpage (in your default browser) on a click event.
This is how it looks in my org file
Manual reference
---
Tags: org-mode, markdown-mode
--- |
thread-64295 | https://emacs.stackexchange.com/questions/64295 | How can I force a Hebrew font to match the fixed width of Latin text characters in a mono font | 2021-04-05T00:48:57.990 | # Question
Title: How can I force a Hebrew font to match the fixed width of Latin text characters in a mono font
I have setup my Emacs to use Noto Sans Mono everywhere. I did this on the naïve assumption that it was in fact a mono-spaced font, with full coverage of Hebrew and Greek Extended characters. Unfortunately, while it does have that codepoint coverage, the character widths are very different and it is only monospaced for some unicode ranges.
Is there a way to force Emacs to use fixed character widths with a font, despite the font having variable widths?
# Answer
If Emacs did that, the characters would overlap. You’ll want to choose a different font, or to modify the default fontset so that it uses a different font for Hebrew characters. See the function `set-fontset-font`, documented in chapter 22.15 Modifying Fontsets in the Emacs manual (which you can also open inside Emacs with `C-h i`).
> 0 votes
---
Tags: fonts, unicode
--- |
thread-2871 | https://emacs.stackexchange.com/questions/2871 | Keeping my .org files in sync across multiple computers | 2014-10-30T21:34:36.200 | # Question
Title: Keeping my .org files in sync across multiple computers
How can I keep my .org files up to date across several computers, perhaps across multiple platforms(linux/windows)?
I could keep all the .org files in git for example, but that would require me to remember to pull and push to keep the repo updated. Could work with a few scripts to automatically handle the files, as I don't have that many.
I could try using dropbox for this as well. I'd assume dropbox syncs the files often enough to not cause problems.
Does org-mode offer any functionality to help with synchronizing the files across multiple locations?
# Answer
I use git-annex assistant to sync my org files across my computers and even my phone (a jolla so the linux binary works out of the box but there is also an android version).
It works like dropbox in that whenever you save a file it will try to sync it but it is decentralized and free (as in free speech and free beer).
The setup is straightforward if you know git but you need some time to familiarize yourself with all the options.
You can find more at http://git-annex.branchable.com
> 11 votes
# Answer
Org files are just plain text files, so any technique that is able to synchronise plain text files will work fine with org files.
My favourite synchronisation tool is Unison. With the right configuration file, I type
```
unison org
```
and Unison will compare files in my `~/org/` directories on both my machines, let me interactively review its actions, then copy the files that need to be copied and invoke an external merge tool for the files that need merging.
> 9 votes
# Answer
I use Git to synchronize my org-mode files. I have a Bash script that I leave running in the background, which automatically commits the file every minute (by default), and then pushes or pulls as needed.
The pseudo-code version:
1. Commit local changes and update remotes.
2. Find local commit with `git rev-parse @`.
3. Find remote commit with `git rev-parse @{u}`.
4. Find base with `git merge-base @ @{u}`
5. If local commit equals remote commit, then we are done; everything is up-to-date.
6. If local commit equals base, then remote has extra commits, so do `git pull`.
7. If remote commit equals base, then local has extra commits, so do `git push`.
8. Otherwise, both local and remote has extra commits. My script tries to resolve this automatically (with `git pull`), but if it can't, will send a bell and exit for the user to fix manually.
Those 8 steps run in a loop, not stopping until I exit manually with `C-c`, or there is an error.
I use this script on Windows using Cygwin.
> 5 votes
# Answer
Org mode does not provide any syncing functionality itself. You would have to rely on a separate application like Dropbox to sync your files. Dropbox syncs not just often, but immediately when files change, so unless you change a file and immediately shut off your computer, you will keep your files in sync.
> 4 votes
# Answer
I personally have this problem and have been using copy instead of Dropbox to have my files in sync. (I don't use Dropbox because of privacy issues). Just like Dropbox, Copy offers clients for all the major platforms.
Sometimes I forget to save my org buffers, so I have hacked the following functions to save all org files whenever I save some file. Not a great solution, but it serves my purpose.
```
(add-hook 'after-save-hook 'org-save-all-org-buffers)
```
Also, if you hold sensitive data in your org files, I recommend you to take a look at this page. I use org-crypt which is amazing.
> 4 votes
# Answer
As others have said, Org mode doesn't do anything about this itself (nor should it). So it's basically a matter of finding your preferred file sync solution.
I use Dropbox. It functions without effort on my three platforms (macOS, desktop Linux, Android). Also, the mobile Org client I use, Orgzly, supports it out of the box.
> 4 votes
# Answer
I recommend Synchthing https://syncthing.net/
> Syncthing is a continuous file synchronization program. It synchronizes files between two or more computers in real time, safely protected from prying eyes. Your data is your data alone and you deserve to choose where it is stored, whether it is shared with some third party, and how it's transmitted over the internet.
> 4 votes
# Answer
I use Dropbox to synchronize my main `.org` files instead of `rsync`, `git` or the like because using Dropbox you can also use MobileOrg to see your `.org` files from your smartphone.
For me this is very easy and it does an awesome job.
> 3 votes
# Answer
I'm currently using `btsync`, but there are several open (and more cumbersome) alternatives around. It basically watches the directory and syncs it to all other running devices as soon as they get online. A dropbox without the cloud so to speak. Since it uses distributed hash tables and the torrent protocol firewalls aren't an issue either, and there are mobile clients, too. And it transfers everything encrypted.
> 1 votes
# Answer
Dropbox (or any other cloud storage I guess) is the way to go. In addition, this is really handy to synchronize the Emacs setup in `~/.emacs.d` (use `mklink` on Windows).
> 0 votes
---
Tags: org-mode
--- |
thread-64293 | https://emacs.stackexchange.com/questions/64293 | Replacing directory-files-recursively with a list of files newer than 7 days old | 2021-04-04T17:00:21.373 | # Question
Title: Replacing directory-files-recursively with a list of files newer than 7 days old
I currently use the following to get a list of agenda files for org-mode:
`(setq org-agenda-files (directory-files-recursively "~/Org" "\\.org$"))`
I'd like to instead get a list of files that are newer than 7 days old so that Emacs doesn't spend a long time reading and parsing all the org files I have.
I know I have to write a `defun` that takes in a directory and file regex as its 2 parameters, but I'm at a loss with how to then find files newer than 7 days.
# Answer
> 2 votes
You can filter the directory for files newers than 7 days
```
(defun newer-than-7-days(file)
(> 7
(/(float-time(time-subtract
(current-time )
(nth 5 (file-attributes file)) ))
86400)))
(setq org-agenda-files
(seq-filter #'newer-than-7-days
(directory-files-recursively "~/Documents/Org" "\\.org$")))
```
---
Tags: org-mode, org-agenda
--- |
thread-55164 | https://emacs.stackexchange.com/questions/55164 | Org-columns error : The CLOCKSUM property cannot be set with ‘org-entry-put’ | 2020-01-28T10:36:20.840 | # Question
Title: Org-columns error : The CLOCKSUM property cannot be set with ‘org-entry-put’
I would like to have summed up logged time with org-columns in org-mode. Apparently it works very well down to level 3 headers (i.e. headers with 3 asterisk), but when I try to log clock for level 4 headers I encounter the following error upon entering org-columns:
> The CLOCKSUM property cannot be set with ‘org-entry-put’
I get the same error message when I try to set by hand the property CLOCKSUM for level 4 sub-headers. Please see a working example below. Trying to update the first columnview table with :id global or generating org-columns for Goal 3 will reproduce the error while Goal 1 and Goal 2 are fine (they do not have level 4 sub-headers with logged clocks).
Anyone knows how to fix this?
```
#+TITLE: Page planning example
#+PROPERTY: Effort_ALL "" 0:05 0:10 0:20 0:30 1:00 2:00 4:00 6:00 8:00
#+PROPERTY: Estimated_days_ALL "" 1 2 3 4 5 6 7 8 9 10 11
#+COLUMNS: %25ITEM(Details) %25TAGS(Context) %7TODO(To Do) %5Effort(Estimate){:} %6CLOCKSUM{:} %10Budget_day(Daily budget){:} %10Estimated_days(Estimated Days){est+}
#+BEGIN: columnview :hlines 2 :id global :maxlevel 2
#+END
* Goal 1
:PROPERTIES:
:BUDGET_DAY: 6:00
:ID: goal_1
:END:
#+BEGIN: columnview :hlines 3 :id goal_1 :Maxlevel 4
| Details | Context | To Do | Estimate | CLOCKSUM | Daily budget | Estimated Days |
|-----------------+---------+-------+----------+----------+--------------+----------------|
| Goal 1 | | | 1:20 | 3:51 | 6:00 | 11-13 |
|-----------------+---------+-------+----------+----------+--------------+----------------|
| Project 1 | | | 0:20 | 3:51 | 4:00 | 5-7 |
|-----------------+---------+-------+----------+----------+--------------+----------------|
| Task 1 | | TODO | 0:15 | 1:11 | | 4-5 |
| Desired outcome | | | | | | |
|-----------------+---------+-------+----------+----------+--------------+----------------|
| task 2 | | TODO | 0:05 | 0:10 | | 1-2 |
| Desired outcome | | | | | | |
|-----------------+---------+-------+----------+----------+--------------+----------------|
| task 3 | | TODO | | 2:30 | | |
|-----------------+---------+-------+----------+----------+--------------+----------------|
| Project 2 | | | 1:00 | | 2:00 | 6-6 |
|-----------------+---------+-------+----------+----------+--------------+----------------|
| Task 1 | | TODO | 1:00 | | | 6 |
#+END
** Project 1
:PROPERTIES:
:Budget_day+: 4:00
:END:
*** TODO Task 1
:PROPERTIES:
:Estimated_days: 4-5
:Effort: 0:15
:END:
:LOGBOOK:
CLOCK: [2020-01-27 Mon 19:05]--[2020-01-27 Mon 20:16] => 1:01
:END:
**** Desired outcome
*** TODO task 2
:PROPERTIES:
:Effort: 0:05
:Estimated_days: 1-2
:END:
:LOGBOOK:
CLOCK: [2020-01-28 Tue 14:52]--[2020-01-28 Tue 15:02] => 0:10
:END:
**** Desired outcome
*** TODO task 3
:LOGBOOK:
CLOCK: [2020-01-28 Tue 12:22]--[2020-01-28 Tue 14:52] => 2:30
:END:
:DEADLINE: <2020-02-02>
*** COMMENT PROJECT META
**** Desired outcome
Write out outcome of project 1
**** Main folder
** Project 2
:PROPERTIES:
:Budget_day+: 2:00
:END:
*** COMMENT PROJECT META
**** Desired outcome
Write out outcome of project 1
**** Main folder
*** TODO Task 1
:PROPERTIES:
:Effort: 1:00
:Estimated_days: 6
:END:
** COMMENT Meta
*** Description of the goal
*** Desired outcome
Write out outcome of the goal
* Goal 2
:PROPERTIES:
:ID: goal_2
:END:
#+BEGIN: columnview :hlines 2 :id goal_2 :maxlevel 3
| Details | Context | To Do | Estimate | CLOCKSUM | Daily budget | Estimated Days |
|-----------+---------+-------+----------+----------+--------------+----------------|
| Goal 2 | | | 10:20 | 0:01 | 2:49 | 4-14 |
|-----------+---------+-------+----------+----------+--------------+----------------|
| Project 1 | | | 8:20 | 0:01 | 00:49 | 2-12 |
| Task 1 | | TODO | 08:15 | 0:01 | | 1-2 |
| Task 2 | | TODO | 0:05 | | | 1-10 |
|-----------+---------+-------+----------+----------+--------------+----------------|
| Project 2 | | | 2:00 | | 02:00 | 2-2 |
| Task 1 | | TODO | 2:00 | | | 2 |
#+END
** Project 1
:PROPERTIES:
:Budget_day+: 00:49
:END:
*** TODO Task 1
:PROPERTIES:
:Estimated_days: 1-2
:Effort: 08:15
:END:
:LOGBOOK:
CLOCK: [2020-01-27 Mon 19:15]--[2020-01-27 Mon 19:16] => 0:01
:END:
Task body
**** Eventual sub-task 1
**** Desired outcome
*** TODO Task 2
:PROPERTIES:
:Effort: 0:05
:Estimated_days: 1-10
:END:
Task body
**** Desired outcome
*** COMMENT PROJECT META
**** Desired outcome
Write out outcome of project 1
**** Main folder
** Project 2
:PROPERTIES:
:Budget_day+: 02:00
:END:
*** COMMENT PROJECT META
**** Desired outcome
Write out outcome of project 1
**** Main folder
*** TODO Task 1
:PROPERTIES:
:Effort: 2:00
:Estimated_days: 2
:END:
** COMMENT GOAL META
*** Description of the goal
*** Desired outcome
Write out outcome of the goal
* Goal 3
:PROPERTIES:
:ID: goal_3
:END:
#+BEGIN: columnview :hlines 4 :id goal_3 :maxlevel 4
#+END
** Project 1
:PROPERTIES:
:Budget_day+: 00:49
:END:
*** TODO Task 1
:PROPERTIES:
:Estimated_days: 1-2
:EFFORT: 0:05
:END:
:LOGBOOK:
CLOCK: [2020-01-26 18:05]--[2020-01-26 Mon 19:16] => 1:11
:END:
Task body
**** TODO Subtask 1
:PROPERTIES:
:Estimated_days: 1-2
:EFFORT: 0:05
:END:
:LOGBOOK:
CLOCK: [2020-01-28 Tue 15:45]--[2020-01-28 Tue 16:45] => 1:00
:END:
```
# Answer
> 1 votes
I couldn't get the MWE to run, but rewriting `%6CLOCKSUM{:}` as `%6CLOCKSUM` solved the problem for me in a similar situation.
# Answer
> -1 votes
The description of the special property ‘CLOCKSUM’ contains a hint that "\[...\] ‘org-clock-sum’ must be run first to compute the values in the current buffer".
Eval'ing (org-clock-sum) in the buffer solved the issue for me.
---
Tags: org-mode
--- |
thread-64298 | https://emacs.stackexchange.com/questions/64298 | get buffers list to startup state without resorting to M-x kill-emacs | 2021-04-05T02:49:08.233 | # Question
Title: get buffers list to startup state without resorting to M-x kill-emacs
Sometimes, when work is finished on one github/issues, its helpful to "reset" the list of opened files. So far I've been doing M-x kill-emacs and then restart, but that's a bit heavy handed.
I tried this tip , that did kill actual file buffers. I want to to be able to reset things so that this kind of "miscellaneous" buffers aren't laying around:
`*scratch*` can stay, because it was there when emacs first started.
# Answer
> 1 votes
If you use Icicles then you can quickly kill any or all buffers using just `C-x k`. Use one or more patterns (in the minibuffer) to match the buffers you want to kill, then use `C-!` to kill all those that match.
You can thus do this on the fly -- no need to open any special buffer, mark buffers etc. You can match using regexps, use multiple match patterns, etc.
See Act On All Candidates. See also Buffer-Name Input.
# Answer
> 1 votes
Based on your question, I am going to assume you want to kill all buffers except `*scratch*`
This function does that:
```
(defun cpb-kill-all-buffers nil
"Kill all buffers except *scratch*"
(interactive)
(mapcar 'kill-buffer (buffer-list))
;; Kill all other windows otherwise you will have many scratch windows.
;; reamining.
(delete-other-windows))
```
---
Tags: buffer-list
--- |
thread-64208 | https://emacs.stackexchange.com/questions/64208 | Changing font color with Key bindings? | 2021-03-30T13:28:05.960 | # Question
Title: Changing font color with Key bindings?
I've been using Emacs org-mode to primarily take lecture notes for university, and I find that it is remarkably useful and I can usually type everything up fairly quickly.
Recently, I've been wanting to use different font colours to make my notes easier for me to follow. I understand that I can type in different font colours by using dot points (`Control + Enter`), but I'd like to change the font colour without having to use dot points. For example, if I'm writing a paragraph of text and need to draw attention to a specific sentence within that paragraph, I would prefer to change the font colour of that sentence to do so.
Because I'd be changing font colour quite regularly, the ideal solution would let me change the font colour very quickly in 1 or 2 key presses without having to mouse click through context menus or write any lines of code everytime I want to do so.
After doing research, I have stumbled across this article which pretty much describes what I want to do:
https://shallowsky.com/blog/linux/editors/emacs-rich-text-editing.html
However, I have so far struggled to get it working with my setup. The article contains a piece of code (I've attached the code below) which it says to add to the .emacs file, after which it says to switch to Enriched Mode (both of these I have performed).
The issue is that when I select text in emacs, and attempt to press `Control + c` and then `r` , nothing happens (no errors or anything). If I then exit out of Enriched mode, I immediately get the error `Key sequence C-c r starts with non-prefix key C-c`.
If I try key presses `Control + c` and then `r` again in normal org mode, I get the error: `C-c r is undefined`.
In terms of troubleshooting, I have used `C-x C-s` to save the file then `C-x C-v RET` to reload the file and still nothing. I've also tried saving it as both `.org` file and `.txt` file to see if that made any difference and no such luck.
I am aware of this question Colors with enriched-mode however, this isn't exactly what I'm after. The solution there involves having to write a bunch of code every time I want to colour a piece of text `<x-color><param>red</param></x-color>` whereas I would prefer a key binding which can change the font colour quickly.
I'm using Mituharu's Emacs version (aka Railwaycat Homebrew port) on mac OSx
I wouldn't mind a solution in either org mode or enriched mode.
```
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Text colors/styles. You can use this in conjunction with enriched-mode.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; rich-style will affect the style of either the selected region,
;; or the current line if no region is selected.
;; style may be an atom indicating a rich-style face,
;; e.g. 'italic or 'bold, using
;; (put-text-property START END PROPERTY VALUE &optional OBJECT)
;; or a color string, e.g. "red", using
;; (facemenu-set-foreground COLOR &optional START END)
;; or nil, in which case style will be removed.
(defun rich-style (style)
(let* ((start (if (use-region-p)
(region-beginning) (line-beginning-position)))
(end (if (use-region-p)
(region-end) (line-end-position))))
(cond
((null style) (set-text-properties start end nil))
((stringp style) (facemenu-set-foreground style start end))
(t (add-text-properties start end (list 'face style)))
)))
(defun enriched-mode-keys ()
(define-key enriched-mode-map "\C-ci"
(lambda () (interactive) (rich-style 'italic)))
(define-key enriched-mode-map "\C-cB"
(lambda () (interactive) (rich-style 'bold)))
(define-key enriched-mode-map "\C-cu"
(lambda () (interactive) (rich-style 'underline)))
(define-key enriched-mode-map "\C-cr"
(lambda () (interactive) (rich-style "red")))
;; Repeat for any other colors you want from rgb.txt
(define-key enriched-mode-map (kbd "C-c ")
(lambda () (interactive) (rich-style nil)))
)
(add-hook 'enriched-mode-hook 'enriched-mode-keys)
```
# Answer
> 1 votes
After **days** of research on how to approach this problem, I came across these two solutions which each solve different aspects of the problem, namely changing text surrounded by a specific character into a user defined colour.
After combining those two solutions together, I came up with this code:
```
;; set colour in Org mode
(defun ask-colour (x)
"Ask colour."
(interactive "sEnter your desired colour: ")
(message "Colour has been set to: %s" x)
(setq org-emphasis-alist `(("~" (:foreground ,x )))))
(global-set-key (kbd "s-j") 'ask-colour)
```
It basically allows you to specify the desired colour via Keybinding `Super key + j` then any text you type in between two Tilde (`~`) characters will change to that specified colour.
The problem with the above code was that when the `.org` document was saved and reloaded, all the colour information was gone.
So, after even more research, I came across this answer which gives the code below:
```
(require 'org-habit nil t)
(defun org-add-my-extra-fonts ()
"Add alert and overdue fonts."
(add-to-list 'org-font-lock-extra-keywords '("\\(!\\)\\([^\n\r\t]+\\)\\(!\\)" (1 '(face org-habit-alert-face invisible t)) (2 'org-habit-alert-face t) (3 '(face org-habit-alert-face invisible t))) t)
(add-to-list 'org-font-lock-extra-keywords '("\\(%\\)\\([^\n\r\t]+\\)\\(%\\)" (1 '(face org-habit-overdue-face invisible t)) (2 'org-habit-overdue-face t) (3 '(face org-habit-overdue-face invisible t))) t)
(add-to-list 'org-font-lock-extra-keywords '("\\(@\\)\\([^\n\r\t]+\\)\\(@\\)" (1 '(face org-habit-clear-face invisible t)) (2 'org-habit-clear-face t) (3 '(face org-habit-clear-face invisible t))) t))
(add-hook 'org-font-lock-set-keywords-hook #'org-add-my-extra-fonts)
```
This seems to work as expected, saving the colour information after reopening the file. It even works in Org mode *(i.e. no need to bother with enriched mode)*. Next, I changed the defaults for the faces by adding this piece of code at the start of my init file:
```
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(org-habit-alert-face ((t (:foreground "green"))))
'(org-habit-clear-face ((t (:foreground "deep sky blue"))))
'(org-habit-overdue-face ((t (:foreground "gold"))))
```
Now every time I enclose text in:
Two `!` characters it appears green **==\>** `!this text appears green!`
Two `@` characters it appears blue **==\>** `@this text appears blue@`
Two `%` characters it appears gold **==\>** `%this text appears gold%`
This is not the ideal solution, considering I wanted to use many different colours and this solution restricts me to only a handful of colour options ***(how many colours are available depends on how many characters are available on your keyboard, and also how many of those you are willing to set)***, but I guess it's better than nothing.
**PS:** for anyone interested, researching this led me to this post where it seems this issue has been brought up many times previously, and one of the developers even made a working patch to implement easy to use syntax to add font colour to org mode but it doesn't seem as if it was merged with the main code for some reason *(I couldn't find references to the patch in the main program source code)*.
---
Tags: org-mode, key-bindings, faces, colors, enriched-mode
--- |
thread-64029 | https://emacs.stackexchange.com/questions/64029 | Can org options be applied to specific export modes only? | 2021-03-21T21:21:45.143 | # Question
Title: Can org options be applied to specific export modes only?
Here is an org document
```
#+title: my document
#+options: num:nil
* first section
** first subsection
* second section
```
My problem is that I want the option `#+option: num:nil` to only be applied when I export to html. When I export to other formats, I do not want this option applied. Is this possible?
# Answer
# Macros
You can evaluate arbitrary Lisp code using a macro:
```
#+MACRO: macroname (eval <lisp code...>)
```
When the macro is expanded, the code is executed.
## Using the Macro
So we can do something like this:
```
#+MACRO: options (eval (if (org-export-derived-backend-p org-export-current-backend 'html) "#+OPTIONS: num:nil"))
{{{options}}}
#+title: my document
* first section
** first subsection
* second section
```
`org-export-current-backend` is a dynamically scoped variable that is set by the exporter before it touches the document. Now when this document is exported, the macro is defined and it is then expanded (through the `{{{options}}}` macro call). The Lisp expression is evaluated and *if* the current backend is (or is derived from) the HTML backend, then the `#+OPTIONS: num:nil` string is the result of the evaluation - and the expansion of the macro. Since macros are expanded as the first step in the export process, the rest of the export proceeds as if the options string was already included in the file.
## Including lisp functions
Here is an elaboration of the idea above to work around the fact (AFAIK) that the macro definition needs to be in a single line. Define a Lisp function to do what you want (which may be arbitrarily complicated) and then eval the call to the function in the macro definition:
```
#+MACRO: options (eval (ndk/options org-export-current-backend))
{{{options}}}
* foo
This is foo
** foo.2
This is foo.2
* bar
This is bar
* baz
This is baz
* Code :noexport:
#+begin_src elisp
(defun ndk/options (be)
"Different options for different backends. Caveat: this function needs to be
defined, before the file is exported. And if e.g. an option changes, it needs to
be defined again (just run the code block with `C-c C-c')."
(cond
((org-export-derived-backend-p be 'latex) "#+OPTIONS: latex:t num:t toc:nil")
((org-export-derived-backend-p be 'html) "#+OPTIONS: html:t num:nil toc:t")))
#+end_src
```
That works OK interactively, but not in batch mode: You would have to store the definition of the function in some file and then use `emacs --batch -l file.el ....` to load it.
But that can be done by giving the code block a name and using the `org-sbe` function to do the evaluation of the code block. We can then incorporate *that* into the definition of the macro, so that when it is expanded, it first evaluates the code block and then it calls the function to produce the options:
```
#+MACRO: options (eval (progn (org-sbe "ndk/options") (ndk/options org-export-current-backend)))
{{{options}}}
... as before ...
* Code :noexport:
#+name: ndk/options
#+begin_src elisp
... as before ...
#+end_src
```
You can now go wild in the function - nothing else needs to be touched.
## Conclusion
With multiple `#+OPTIONS` lines, you can set defaults for every backend and use the macro to override only backend-dependent options (later `#+OPTIONS` lines override earlier ones):
```
#+MACRO: ....
#+OPTIONS: ... backend-independent options go here ...
{{{options}}}
...
```
The main idea was presented by Juan Manuel Macías on the Org mode mailing list - see this post and its enclosing thread.
> 3 votes
---
Tags: org-mode, org-export
--- |
thread-57776 | https://emacs.stackexchange.com/questions/57776 | Open buffer created by run-python in the current window | 2020-04-13T19:52:37.903 | # Question
Title: Open buffer created by run-python in the current window
I recently started using spacemacs, and have a newbie question about modifying the way `run-python` works.
When I execute `run-python`, a new buffer is opened in a different window. I'd like to change it so that it opens the newly created buffer in the current window.
Using `find-function` I found the source for `run-python`:
```
(defun run-python (&optional cmd dedicated show)
"Run an inferior Python process.
Argument CMD defaults to `python-shell-calculate-command' return
value. When called interactively with `prefix-arg', it allows
the user to edit such value and choose whether the interpreter
should be DEDICATED for the current buffer. When numeric prefix
arg is other than 0 or 4 do not SHOW.
For a given buffer and same values of DEDICATED, if a process is
already running for it, it will do nothing. This means that if
the current buffer is using a global process, the user is still
able to switch it to use a dedicated one.
Runs the hook `inferior-python-mode-hook' after
`comint-mode-hook' is run. (Type \\[describe-mode] in the
process buffer for a list of commands.)"
(interactive
(if current-prefix-arg
(list
(read-shell-command "Run Python: " (python-shell-calculate-command))
(y-or-n-p "Make dedicated process? ")
(= (prefix-numeric-value current-prefix-arg) 4))
(list (python-shell-calculate-command) nil t)))
(get-buffer-process
(python-shell-make-comint
(or cmd (python-shell-calculate-command))
(python-shell-get-process-name dedicated) show)))
```
and the source for `python-shell-make-comint`
```
(defun python-shell-make-comint (cmd proc-name &optional show internal)
"Create a Python shell comint buffer.
CMD is the Python command to be executed and PROC-NAME is the
process name the comint buffer will get. After the comint buffer
is created the `inferior-python-mode' is activated. When
optional argument SHOW is non-nil the buffer is shown. When
optional argument INTERNAL is non-nil this process is run on a
buffer with a name that starts with a space, following the Emacs
convention for temporary/internal buffers, and also makes sure
the user is not queried for confirmation when the process is
killed."
(save-excursion
(python-shell-with-environment
(let* ((proc-buffer-name
(format (if (not internal) "*%s*" " *%s*") proc-name)))
(when (not (comint-check-proc proc-buffer-name))
(let* ((cmdlist (split-string-and-unquote cmd))
(interpreter (car cmdlist))
(args (cdr cmdlist))
(buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
interpreter nil args))
(python-shell--parent-buffer (current-buffer))
(process (get-buffer-process buffer))
;; Users can override the interpreter and args
;; interactively when calling `run-python', let-binding
;; these allows having the new right values in all
;; setup code that is done in `inferior-python-mode',
;; which is important, especially for prompt detection.
(python-shell--interpreter interpreter)
(python-shell--interpreter-args
(mapconcat #'identity args " ")))
(with-current-buffer buffer
(inferior-python-mode))
(when show (display-buffer buffer))
(and internal (set-process-query-on-exit-flag process nil))))
proc-buffer-name))))
```
Based on the following snippets of documentation taken from the definition of `display-buffer`
```
"Optional argument ACTION, if non-nil, should specify a buffer
display action of the form (FUNCTIONS . ALIST). FUNCTIONS is
either an \"action function\" or a possibly empty list of action
functions. ALIST is a possibly empty \"action alist\"."
"Action functions and the action they try to perform are:
`display-buffer-same-window' -- Use the selected window."
```
I thought by changing the line `(when show (display-buffer buffer))` to `(when show (display-buffer buffer (cons '(display-buffer-same-window) '())))` I could get the behavior I wanted, but it didn't seem to have any effect.
Questions:
1. Is my understanding of how the code works incorrect? If so, how?
2. Is modifying and saving the buffer sufficient to change the behavior of the `run-python` command?
3. Is there a simpler way to do this?
# Answer
> 2 votes
This should do it:
```
(add-to-list 'display-buffer-alist
'("^\\*Python\\*$" . (display-buffer-same-window)))
```
---
Tags: spacemacs, python
--- |
thread-64306 | https://emacs.stackexchange.com/questions/64306 | Syntax Highlighting of Common Lisp User-Defined Macros in Emacs | 2021-04-05T16:35:15.000 | # Question
Title: Syntax Highlighting of Common Lisp User-Defined Macros in Emacs
I would like to start writing a few simple Domain Specific Languages in Common Lisp and would like the names of macros I define to be highlighted as if they were Common Lisp functions or macros in Emacs.
Below is a simple example which is not precisely the code I am hoping to write but it shows the kind of functionality I desire.
```
(defmacro class* (class-name superclasses slots)
(let ((slot-declarations
(loop for slot in slots collecting
(list slot :accessor slot :initform nil))))
`(defclass ,class-name ,superclasses ,slot-declarations)))
(class* graph () (nodes edges))
```
What I would like is for `class*` in the *second* form to show up in magenta (given the default colours in my Emacs installation) and `graph` should be highlighted in blue.
I have seen some examples of how to adjust syntax highlighting for LaTeX, but I could not extend those to work for me in Common Lisp.
# Answer
> 1 votes
I have been able to solve my issue above by looking through the Emacs source code, specifically `font-lock.el`. It is recommended that one use `regex-opt` to generate a suitable regular expression to be added to the font lock keywords for the mode.
In my case `(regex-opt '("class*"))` generates `"\\(?:class\\*\\)"`.
This is then added (in my case) to `lisp-mode` as below.
```
(font-lock-add-keywords 'lisp-mode '("\\(?:class\\*\\)"))
```
However, this has revealed to me a deeper issue - I would actually like to have the `class*` in the macro definition highlit in *blue* since it is the name being declared/defined. Also, it would be nice if the word `graph` was in blue as well, but later on if used to create graph objects it would be in maroon.
I will work on this add anything I find later to this post in case it is of interest. Otherwise if it is felt this issue should be closed, please do so.
---
Tags: syntax-highlighting, common-lisp
--- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.