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-20492
|
https://emacs.stackexchange.com/questions/20492
|
How can I get a sensible split-window policy?
|
2016-02-22T11:02:40.300
|
# Question
Title: How can I get a sensible split-window policy?
Emacs is constantly making new windows and it's been ruining my day lately. How can I tell emacs to use the following policy when creating windows?
* Prefer vertical splits
* Stop doing vertical splits when windows would be less than 80 columns.
* Stop doing horizontal splits when window would be less than 60 rows.
* When I reach this 6x6 grid, on my 27" monitor, start reusing windows!
Also, I'd prefer my windows to always be balanced, but every split leaves the widow sizes unbalanced. I'd rather have 3 equally sized windows than 1 large and two which are too small! Is there a setting for this, or a sensible place to put a balance-windows advice?
# Answer
A little late, but because I also searched for this and could not find a ready solution:
You could define your own `split-window-sensibly` function.
To do so, put the following in your `init.el`:
```
(setq split-height-threshold 120
split-width-threshold 160)
(defun my-split-window-sensibly (&optional window)
"replacement `split-window-sensibly' function which prefers vertical splits"
(interactive)
(let ((window (or window (selected-window))))
(or (and (window-splittable-p window t)
(with-selected-window window
(split-window-right)))
(and (window-splittable-p window)
(with-selected-window window
(split-window-below))))))
(setq split-window-preferred-function #'my-split-window-sensibly)
```
*Note:* the thresholds need to be twice as big as the smallest window allowed, because the new windows each use half of former window size.
The last line tells emacs to use the defined split function.
> 6 votes
# Answer
I've been using the following for a long time. You might need to edit it to accommodate your own preferred style.
```
;; ------------------------------------------------------------------
;; display-buffer
;; The default behaviour of `display-buffer' is to always create a new
;; window. As I normally use a large display sporting a number of
;; side-by-side windows, this is a bit obnoxious.
;;
;; The code below will make Emacs reuse existing windows, with the
;; exception that if have a single window open in a large display, it
;; will be split horisontally.
(setq pop-up-windows nil)
(defun my-display-buffer-function (buf not-this-window)
(if (and (not pop-up-frames)
(one-window-p)
(or not-this-window
(not (eq (window-buffer (selected-window)) buf)))
(> (frame-width) 162))
(split-window-horizontally))
;; Note: Some modules sets `pop-up-windows' to t before calling
;; `display-buffer' -- Why, oh, why!
(let ((display-buffer-function nil)
(pop-up-windows nil))
(display-buffer buf not-this-window)))
(setq display-buffer-function 'my-display-buffer-function)
```
> 3 votes
# Answer
This will make you prefer vertical splits
```
(setq split-width-threshold 1)
```
> 0 votes
# Answer
This works for me on both my 15" MacBook Pro and external widescreen display:
`(setq split-height-threshold nil) (setq split-width-threshold 200)`
* Setting `split-height-threshold` to basically never wanting to split horizontally
* `200` seems like a high-enough number that even on a large external display Emacs will only split at most once.
> 0 votes
---
Tags: window-splitting
---
|
thread-53115
|
https://emacs.stackexchange.com/questions/53115
|
Troubleshooting a hanging `list-processes`
|
2019-10-12T15:40:50.540
|
# Question
Title: Troubleshooting a hanging `list-processes`
Normally I'd use `M-x list-processes` to see what Emacs is running in the background. But in this case `list-processes` *itself* hangs. What is the right thing to do in this situation?
# Answer
If this happens it means that Emacs is having trouble communicating with some subprocess. It is a good idea to leave Emacs and look at its subprocesses from the hosting operating system.
For example, on Unix this may be done with `pstree $(pidof emacs)`. This won't show which process is causing the problem, but can at least serve as a kind of sanity check.
You can also send Emacs a `SIGUSR2` signal, which will stop it from hanging and kick it into a debugger.
> 1 votes
---
Tags: process, performance, subprocess
---
|
thread-53132
|
https://emacs.stackexchange.com/questions/53132
|
How to delete numerals of a certain size from text
|
2019-10-14T01:53:10.333
|
# Question
Title: How to delete numerals of a certain size from text
I'm pretty new to emacs, so I'm still learning all the functions.
I'm trying to remove certain metadata from each line of several large .txt files (Bible translations) and was wondering if if there was a way to search for and delete numerals above a certain value or to delete a specific column (the 4th) separated by TAB characters.
```
BOOK <TAB> CHAPTER# <TAB> VERSE# <TAB> VERSE-ID# <TAB> TEXT
```
The 4th field is a universal verse number starting at "10" and increases sequentially by 10s, so it becomes quite large - far larger than any other numeral in the file, which would otherwise be less than 300.
An example of what I'd like to do would be changing this:
```
PSALMS 150 5 164000 Praise him upon the loud cymbals: praise him upon the high sounding cymbals.
PSALMS 150 6 164010 Let every thing that hath breath praise the LORD. Praise ye the LORD.
```
to this:
```
PSALMS 150 5 Praise him upon the loud cymbals: praise him upon the high sounding cymbals.
PSALMS 150 6 Let every thing that hath breath praise the LORD. Praise ye the LORD.
```
The files also are divided into books by org-mode headings:
```
* THE NEW TESTAMENT
** The GOSPEL According to Matthew
MATTHEW 1 1 231460 The book of the generation of Jesus Christ, the son of David, the son of Abraham.
```
I suppose a delete-by-column function would have to be iterated, but that's not an issue for me as I can easily whip up a macro. Messing up the formatting (i.e. leaving an empty field) should be easy enough for me to clean up, so simply either deleting the column or an arbitrarily large numeral is acceptable.
# Answer
Since you have a very specific line format, we can use regexes to accomplish this task. This method will go through your file, and on each line that is in that specific format, replace it with the line without that section.
I've left it inserting tabs; if you would rather have spaces, the replacement (the argument to `replace-match`) can be easily modified.
```
(defun remove-verse-ids ()
(interactive)
(goto-char (point-min))
(while (re-search-forward "\\([[:alnum:]]*\\)\t\\([[:digit:]]*\\)\t\\([[:digit:]]*\\)\t[[:digit:]]*\t\\(.*\\)"
nil
t)
(replace-match "\\1\t\\2\t\\3\t\\4")))
```
The regex used in `re-search-forward` is a little wordy; but I'm not sure what would easily shorten it, other than replacing `[[:digit:]]` with `[0-9]`, which I believe would be slightly less readable.
For fun, an explanation of the regex follows. All lines beginning with `;;` are comments as explanations.
```
\\([[:alnum:]]*\\)
;;First, any number of alphanumeric characters, captured for later use. The "book".
\t
;;A tab character.
\\([[:digit:]]*\\)
;;Any number of, well, numbers, captured for later use. The chapter number.
\t
;;A tab character.
\\([[:digit:]]*\\)
;;Any number of numbers, captured for later use. The verse number.
\t
;;A tab.
[[:digit:]]*
;;Numbers. The verse ID number, which is not captured.
\t
;;Tab
\\(.*\\)
;;Any number of characters, for later use. The actual text.
```
> 0 votes
# Answer
> ... a way to search for and delete numerals above a certain value
I think column-based solutions make more sense in this case but, just for fun, here's an interactive way you could delete numerals above a certain value using search-and-replace:
`M-x` `replace-regexp` `RET` `\b\([0-9]\{6,\}\)\b` `RET` `\,(if (> \#1 164000) "" \1)` `RET`
Which will turn your example into:
```
PSALMS 150 5 164000 Praise him upon the loud cymbals: praise him upon the high sounding cymbals.
PSALMS 150 6 Let every thing that hath breath praise the LORD. Praise ye the LORD.
```
By changing numbers greater than 164000 to an empty string.
This is matching only numbers of at least six digits, and then testing all matched numbers to see whether they're \> 164000, and replacing them with either the original matched text OR an empty string, depending on the test.
---
As you've said you're new to Emacs, I'll add that this *is* a somewhat advanced technique, combining regular expressions, emacs lisp, and some special-purpose interactive replacement syntax; but you might find it interesting to figure out how that all fits together. You can also use `query-replace-regexp` instead of `replace-regexp` in order to step through the replacements one at a time, which will show the process a bit better.
> 1 votes
# Answer
A way to do it interactively:
```
M-x query-replace-regexp ^\([A-Z]+\)\([ ]+\)\([0-9]+\)\([ ]+\)\([0-9]+\)[ ]+[0-9]+\([ ]+\)\(.+\) RET \1\2\3\4\5\2\7 RET
```
For those not familiar with regular expressions: \[A-Z\] matches all upcase characters, \[0-9\] matches integers, the "+"-flag means: one-or-many occurrences, the \\(..\\) grouping construct permits to fetch the stuff inside later in replacement text. Note the \2 in replacements, fetching two times the first space amount.
> 0 votes
---
Tags: search, numbers
---
|
thread-53126
|
https://emacs.stackexchange.com/questions/53126
|
`eval` in `rx-to-string` works in `*scratch*` but not in code
|
2019-10-13T11:44:21.530
|
# Question
Title: `eval` in `rx-to-string` works in `*scratch*` but not in code
I am trying to code an `rx-to-string` form that contains an intermediate regexp.
This code works in Lisp Interaction Mode:
```
(let* ((a-plus '(one-or-more "a")))
(rx-to-string '(sequence (eval a-plus))))
```
but fails in Emacs Lisp Mode with a `(void-variable a-plus)` error. Why? How do I fix that?
EDIT: I have found the cause: the `lexical-binding: t` directive in the Emacs Lisp buffer.
# Answer
> 0 votes
The problem is that `rx-to-string` does not work with `lexical-binding: t`, because of `eval` (see also: https://emacs.stackexchange.com/a/30174/2763).
However, the workaround proposed by @JohnKitchin works:
```
(let* ((a-plus '(one-or-more "a")))
(rx-to-string `(sequence ,a-plus)))
```
---
Tags: rx
---
|
thread-53138
|
https://emacs.stackexchange.com/questions/53138
|
How to denote an aside in org?
|
2019-10-14T14:54:01.903
|
# Question
Title: How to denote an aside in org?
I am trying to go deeper with org mode to the literate coding stuff itself rather than merely for markup.
I am writing a document where I'm solving some coding challenge, and part way through reasoning about it, decide to take an aside to ensure that I know how to pass tables into src blocks and to use sessions. The next section of my document is a sort of "aside" where I am testing just that (though using some of the named tables in the containing header). I then want to return to solving the problem.
So I have
```
* My problem
writing
src block
writing
a-named-table
more writing
here's my aside, writing
src block
writing
src
writing
src
writing, back to the main thing, I'm not referencing anything in the aside here
```
What is a good way of denoting that aside so that I can expand/collapse it and control whether I want it exported or not later?
I could use a headline but then returning to the main code would require its own headline which would be weird in the outline as it would split up what is one logical flow of thought into two simply because an aside was nestled between.
I use asides in writing prose a lot so I think it would probably be beneficial for my literate coding efforts to know the "right" way of doing it.
# Answer
You can use the executable org source blocks from the answer to another question.
Write your aside into that org source block. That gives your the possibility to structure your aside and to include almost everything that is possible in org mode into the aside.
With the `:exports` header argument you can freely export the source code of the org source block (`code`), the resulting org mode code (`results`), or nothing at all (`none`).
Citation of the function enabling the export of org source blocks:
```
(defun org-babel-execute:org (body params)
"Return BODY with variables from PARAMS replaced by their values."
(let* ((vars (cl-loop for par in params
if (eq (car par) :var)
collect (cons (symbol-name (cadr par)) (cddr par))))
(re (regexp-opt (mapcar #'car vars) 'words))
(pos 0))
(while (string-match re body pos)
(setq body (replace-match
(format "%s" (cdr (assoc-string (match-string 0 body) vars)))
nil nil
body)))
body))
```
There follows the org code for your document. The `:results:` drawer is generated by the execution of the org source block.
You can fold the org source block and also the `:results:` drawer.
```
** My problem
writing
src block
writing
a-named-table
more writing
#+begin_src org :results drawer :exports results
here's my aside, writing
,#+begin_src emacs-lisp
(message "Hello world!")
,#+end_src
writing
,#+begin_src emacs-lisp
(message "Src block 2!")
,#+end_src
writing
,#+begin_src emacs-lisp
(message "Src block 3!")
,#+end_src
#+end_src
#+RESULTS:
:results:
here's my aside, writing
#+begin_src emacs-lisp
(message "Hello world!")
#+end_src
writing
#+begin_src emacs-lisp
(message "Src block 2!")
#+end_src
writing
#+begin_src emacs-lisp
(message "Src block 3!")
#+end_src
:end:
writing, back to the main thing, I'm not referencing anything in the aside here
```
Exporting the resulting org source with `:exports results` header argument:
Exporting the source code from the org source block with `:exports code` header argument:
Exporting nothing related to the org source block with `:exports none` header argument:
> 3 votes
# Answer
This sounds like a job for "inline tasks" (FAQ entry: https://orgmode.org/worg/org-faq.html#list-item-as-todo).
There's another answer here that shows them, including choosing to export or not to export via "OPTIONS": https://emacs.stackexchange.com/a/34504/737 -- I suggest you upvote that one rather than this one if that helps, since I'm not reproducing the answer here.
> 0 votes
---
Tags: org-mode
---
|
thread-53149
|
https://emacs.stackexchange.com/questions/53149
|
Avoid Adding Backslash to Curly Brackets when Exporting Latex
|
2019-10-14T21:05:30.960
|
# Question
Title: Avoid Adding Backslash to Curly Brackets when Exporting Latex
I want to export an org tree to latex, but whenever I have a command that nests curly brackets, org export will automatically prepend all brackets with a backslash.
For **example**, the tree:
Exports to (`C-c C-e C-s l l`):
Instead of:
**Question:** How do I export the literal latex command I typed without having org-export prepend backslashes as in the example above?
# Answer
> 0 votes
This discussion thread is related to my question. A solution that seems to work for single line Latex commands is to use the in-buffer setting `#+LATEX`.
In the example mentioned in the question, we would have:
Which correctly exports to:
---
Tags: org-export, latex
---
|
thread-53139
|
https://emacs.stackexchange.com/questions/53139
|
Can "kaz-yos/eval-in-repl" use the prexisting "inf-ruby" console started by robe mode
|
2019-10-14T15:10:28.570
|
# Question
Title: Can "kaz-yos/eval-in-repl" use the prexisting "inf-ruby" console started by robe mode
I've been using org babel to execute ruby code, works well but
* wrapping blocks with begin\_src/end\_src is cumbersome
* no live output - i have to wait till the whole process finishes to see output
Suppose I have this bit of text in a fundamental buffer
```
puts `pwd`
puts RUBY_VERSION
```
When I press `C-c a` I want this executed using ruby interpreter. I started writing a defun for it like this:
```
(defun my-execute-region-with-ruby()
(interactive))
```
I've found a package/function that does it (https://github.com/kaz-yos/eval-in-repl/blob/master/eval-in-repl-ruby.el)
but looking for a different solution or to amend the solution in that package. My issues:
1) When the ruby code block is executed, the "system ruby binary" is used, which is 99% of the time not the binary used by for example the rails project I'm working on 2) there should be a way to indicate the "cd working directory" when executing the ruby code block.
I've noticed "github.com/kaz-yos/eval-in-repl" uses a live inf-ruby buffer for the execution. I already (always) have an inf-ruby consiole running because I use "github.com/dgutov/robe", so was wondering how I can tell "eval-in-repl-ruby.el" to re-use the preexisting "inf-ruby" repl, because the robe repl already has it's `cd` set correctly, and as a result the ruby version is correct too because 'RBENV' detects the appropriate ruby version to use by reading the "project/.ruby-version" file.
# Answer
I think I figured out a solution.
https://github.com/nonsequitur/inf-ruby/issues/126
> -1 votes
---
Tags: org-babel, repl, ruby
---
|
thread-53147
|
https://emacs.stackexchange.com/questions/53147
|
Copy to PRIMARY selection in command
|
2019-10-14T20:05:32.070
|
# Question
Title: Copy to PRIMARY selection in command
I'm a novice in Lisp, so I feel like I'm missing something very basic here. My intention was to create a function/shortcut to remove all whitespace and newline chars from the selected text and copy the resulting string to the X primary clipboard/selection. For example, when selecting the text:
```
line 1
line 2
```
The function should copy `line1line2` to the clipboard. To be precise, it should be copied to the *primary* selection. I've written the following code for this presumably easy task:
```
(defun copy-no-white-space ()
(interactive)
(gui-set-selection
'PRIMARY
(replace-regexp-in-string "[\s\n]" "" (buffer-substring (region-beginning) (region-end))))
```
Unfortunately, this does not work this way. When I try to paste the modified pattern, it only yields the original region with no modifications and I just can not wrap my head around why: It works when `PRIMARY` is replaced with `CLIPBOARD` (only that I really want to use `PRIMARY`). ~~What confuses me even more is the fact that it works with `PRIMARY` when I remove the regular expression in favor of a fixed string and that it also works when I put it outside of the function.~~ (edit: only when nothing is marked) Why? ;)
# Answer
> 2 votes
After reading Primary Selection I got a clue for the solution. A simple `deactivate-mark` did the trick for me:
```
(defun copy-no-white-space ()
(interactive)
(deactivate-mark)
(gui-set-selection
'PRIMARY
(replace-regexp-in-string "[\s\n]" "" (buffer-substring (region-beginning) (region-end))))
```
My interpretation is the following: After leaving the `interactive` function, X or Emacs(?) re-evaluates the current selection, to bring the highlighted region to the primary clipboard again. Thinking about it, this probably makes a lot sense for other functions that do not actually want to fiddle with the primary selection, I see that my intention is kind of goofy in this sense.
---
Tags: copy-paste, clipboard
---
|
thread-53151
|
https://emacs.stackexchange.com/questions/53151
|
Org Capture - prepend after org header/config block?
|
2019-10-14T22:23:03.220
|
# Question
Title: Org Capture - prepend after org header/config block?
One of my org capture templates (in my init.el) looks like the following:
```
("n" "Note" plain
(file "/path/to/file.org")
"* %^{Title} %U \n%? \n"
:prepend t)
```
I'd like to see the following after I capture a note using this template:
```
#+TITLE: Notes
#+DESCRIPTION: a file of notes
* captured note [2019-10-14 Mon 18:06]
* test note 2 [2019-10-14 Mon 13:00]
* test note 1 [2019-10-14 Mon 10:37]...
```
But what I actually get is:
```
* captured note [2019-10-14 Mon 18:06]
#+TITLE: Notes
#+DESCRIPTION: a file of notes
* test note 2 [2019-10-14 Mon 13:00]
* test note 1 [2019-10-14 Mon 10:37]...
```
The "prepend" property almost does what I want - it prepends the headline to the beginning of the file, rather than the end. However, I'd like the header to stay at the top of the file.
Is there a way to prepend new headlines after the initial "#+" lines?
# Answer
Change `plain` to `entry`.
See org manual template elements:
```
type
The type of entry, a symbol. Valid values are:
‘entry’
An Org mode node, with a headline. Will be filed as the child
of the target entry or as a top-level entry. The target file
should be an Org file.
...
‘plain’
Text to be inserted as it is.
```
> 3 votes
---
Tags: org-mode, org-capture
---
|
thread-53163
|
https://emacs.stackexchange.com/questions/53163
|
Aquamacs for macOS Mojave and Catalina - error in process filter: ‘recenter’ing a window that does not display current-buffer. How can I fix this bug?
|
2019-10-15T12:37:43.613
|
# Question
Title: Aquamacs for macOS Mojave and Catalina - error in process filter: ‘recenter’ing a window that does not display current-buffer. How can I fix this bug?
I'm a very new Mac user and not really an Emacs user. I just use emacs to run PVS Specification and Verification System, by typing the pvs command in the terminal to start the software.
Aquamacs was working properly but suddenly it started to get stuck when running some .pvs files (not all), including some that were working normally before. I'm receiving the following message:
"error in process filter: ‘recenter’ing a window that does not display current-buffer".
The Aquamacs windows freeze, and I just can force it to ends by using the Mac tool or closing the terminal. My Mac was running macOS Mojave when the error started, but after I updated to Catalina the bug continued.
As I'm a new Mac user a beginner in Emacs, I really appreciate any help to fix this.
# Answer
> 2 votes
The best way to get this addressed is to:
* Confirm that your bug occurs with `open -a Aquamacs --args -Q`.
* Confirm that your bug occurs with the latest release (August) and/or the latest nightly.
* Report bugs with the "Send Bug Report" function (Help menu) from within Aquamacs.
* If you are unable to use the bug reporting function, please send your bug
report to the Aquamacs bug reports address by directly e-mailing aquamacs-bugs@aquamacs.org (no subscription required).
* Include as much detail as possible. Don't be afraid of providing too much.
Additionally, I'd file the same bug report to the Aquamacs github issue tracker. Aquamacs is going through a transition of maintainers, so please be patient.
---
Tags: osx, aquamacs
---
|
thread-53156
|
https://emacs.stackexchange.com/questions/53156
|
Why does emacs add a tab to the current line when I use "expand abbreviation" feature?
|
2019-10-15T00:58:29.717
|
# Question
Title: Why does emacs add a tab to the current line when I use "expand abbreviation" feature?
Apologies if my question is silly, it's my first day using abbrev expand.
I have an abbrev set up like this
```
"bm" 3 "bookmarks-acd1fe"
```
When I press bm tab, I end up with
```
bookmarks-acd1fe<tab character here>
```
I didn't want a tab character, why is it inserting tab? ¯\_(ツ)\_/¯
# Answer
When you enter `b``m``TAB`, `abbrev` expands and then inserts the tab you entered. If you had hit `SPACE` instead, it would have entered a space.
Emacs links process of expanding abbreviations to a couple of character-inserts, called self-insert-command. I.e. when abbrev-mode is on and such a character gets inserted, Emacs looks before point for an abbreviation and expands it if found. Characters which trigger `expand-abbrev` are SPACE and TAB. It's also possible to call it interactively: M-x expand-abbrev RET.
> 2 votes
---
Tags: abbrev
---
|
thread-53167
|
https://emacs.stackexchange.com/questions/53167
|
Check whether buffer is in org-mode
|
2019-10-15T15:46:06.350
|
# Question
Title: Check whether buffer is in org-mode
I want to programmatically check whether the current buffer is in `org` mode. I know that major modes should usually define the variable `<modename>-mode`, i.e., `org-mode` should be a defined variable.
However, if I execute `describe-variable` in an org buffer, I don't see any `org-mode`. Now, I'm not sure whether `describe-variable` works for buffer-local variables, so I typed `(message org-mode)` into my org buffer and ran `eval-last-sexp`. This gives me the error `(void-variable org-mode)`, so I guess that org mode does not define any `org-mode` variable.
What is the correct way to check whether a buffer is in org mode?
# Answer
> I know that major modes should usually define the variable -mode, i.e., org-mode should be a defined variable.
Not quite: a major mode should set the variable `mode-name` to the "pretty name" for the mode (i.e., the one that will appear in the modeline), and the variable `major-mode` to the major mode's command symbol (i.e., `org-mode` in this case). You can test if the current buffer is in `org-mode` with:
```
(string-equal major-mode "org-mode")
;; or equivalently:
(string-equal mode-name "Org")
```
These conventions are explained in the Emacs Lisp manual, (elisp) Major Mode Conventions.
> 5 votes
---
Tags: org-mode, major-mode, variables
---
|
thread-38565
|
https://emacs.stackexchange.com/questions/38565
|
Inferior Python shows not output, or input
|
2018-02-02T21:00:16.717
|
# Question
Title: Inferior Python shows not output, or input
I have the symptoms described here Input and Output does not show up in python mode, except this happens with python3 as interpreter as well as ipython, and I've tried the suggestions there for fixing ipython and have no improvement. show output from python-shell-send-region
With Ubuntu Linux, Emacs-25.2.2, the Python Inferior Shell does not show either the input nor the output I expect. I've tested with both python3 and ipython3, and I have the same symptom. Because I use R with Emacs-ESS, I had some expectation that Python with an inferior session would be similar, but, well, this seems to do nothing.
My init.el file has custom-set-variables so I use python3
```
(python-shell-interpreter "python3")
```
When I open a python code file, the Emacs status line says (Python) and to launch the interpreter, I either can use pull down menu Python -\> Start Interpreter or M-x run-python. Either way, new buffer starts, looks like this:
In the python code buffer, I highlight some lines of code and use the pull down menu Python -\> Eval Region. Emacs minibuffer says "Sent: import re ..." but, when using python3, the Inferior shell does not change at all. It displays neither input nor output.
I'll be specific. I'm using BeautifulSoup to read in an HTML file I saved. My Python region:
```
import re
from bs4 import BeautifulSoup
filename = "../workingdata/wp039-910.html"
soup = BeautifulSoup(open(filename, encoding='windows-1251'), "html.parser")
links = soup.find_all("a")
type(links)
type(links[4])
```
The Shell looks like this:
```
Python 3.6.3 (default, Oct 3 2017, 21:45:48)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> python.el: native completion setup loaded
>>>
```
THat does not change when I highlight new code regions and run them, even if commands do trigger output
However, I can type a line into the shell and it shows the session did run those line.
> > > type(links\[4\])
I notice, however, that the history of the Python shell does not include the lines that were submitted by python mode, only the one I manually typed in.
What I want is for this to behave like Emacs-ESS, where the code I run fills in the output buffer, and the output also appears there.
When I change the shell to ipython3 with this insertion in the init file:
```
(setq python-shell-interpreter "ipython3"
python-shell-interpreter-args "--simple-prompt --pprint")
```
The problem is slightly different. I can see the prompt incrementing in the shell when I send a region, but never see any input or output. Here I highlighted a block of lines and use pull down Python -\> Eval Region, and I see the counter increments from 1 to 2:
```
Python 3.6.3 (default, Oct 3 2017, 21:45:48)
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
In [2]:
```
And I can type commands there and it seems correct.
```
In [2]: links = soup.find_all("a")
In [3]: links[3]
Out[3]:
<a class="a1" href="wp001e">English</a>
```
As it stands, this Inferior shell seems rather useless, if the only workable way to interact with it is to copy/paste from a py file at the prompt. I can't see any benefit in this and wonder if it is like this for everybody.
# Answer
> 0 votes
I had a similar issue, to be more specific about the comments above:
1) For https://github.com/jorgenschaefer/elpy/issues/924 (suggested by thelatemail), I simply added the suggested block to `(add-hook 'python-mode-hook ...)`
2) The second option (lpy) prints evaluated sexps/lines in the minibuffer, and has other really nice features
---
Tags: ipython, inferior-buffer
---
|
thread-53170
|
https://emacs.stackexchange.com/questions/53170
|
Can which-key help with extended keyboard shortcuts?
|
2019-10-15T22:17:49.487
|
# Question
Title: Can which-key help with extended keyboard shortcuts?
I have two shortcuts defined like this
```
;; eval in shell
(global-set-key (kbd "C-c x s") 'eir-eval-in-shell)
;; eval in ruby
(global-set-key (kbd "C-c x r") 'eir-eval-in-ruby)
```
`which-key` helps me when I forgot my keyboard shortcuts.
The problem is, When I press C-c and wait 1 second I don't get any useful info about the above 2 combos.
What I get is
```
& → +prefix e → er/expand-region h → experiment-001 m → experiment-002 → +projectile-command-map
b → bury-buffer f → ffap i → experiment-003 o → experiment-005 x → +prefix
C-c- [C-h paging/help]
```
But
```
x → +prefix
```
doesn't help. Any ideas what to do here?
# Answer
> 2 votes
* Use `define-prefix-command` to define a *named* prefix
* Bind `C-c x` to that prefix command
* Bind `s` and `r` in the prefix command keymap
When you type `C-c`, `which-key` will then show you your chosen prefix name instead of just "prefix", which gives you better context for which commands you can expect to be bound underneath it.
Obviously you can type `x` (with or without doing the above) to see the bindings themselves.
---
Tags: key-bindings, help
---
|
thread-53172
|
https://emacs.stackexchange.com/questions/53172
|
How to make `pulse-momentary-highlight-region` stop highlighting after 1 second?
|
2019-10-16T01:03:37.750
|
# Question
Title: How to make `pulse-momentary-highlight-region` stop highlighting after 1 second?
When I do `pulse-momentary-highlight-region`, the highlight stays till I press any key.
(I'm on macOS `emacs -nw`.)
How can I make the pulse to go away after a short while?
# Answer
> 2 votes
Type `M-x find-library RET pulse RET` and have a peek at the variables defined with `defcustom` and `defvar` -- you can use `isearch` ....
How about customizing the following *three* variables?:
`pulse-iterations`: "Number of iterations in a pulse operation." \[The default value is **10**.\]
`pulse-delay`: "Delay between face lightening iterations." \[The default value is **.03**.\]
`pulse-flag`: "Whether to use pulsing for momentary highlighting. ..." \[The default value is determined by the function `(pulse-available-p)`.\] The doc-string is semi-lengthy and has been truncated here for simplicity purposes.
---
Tags: osx
---
|
thread-53175
|
https://emacs.stackexchange.com/questions/53175
|
When does shell-command-on-region actually pass the region to the command?
|
2019-10-16T04:17:51.183
|
# Question
Title: When does shell-command-on-region actually pass the region to the command?
I am having some trouble understanding how shell-command-on-region works. Sometimes the region is passed to command, sometimes not, as far as I can tell.
Suppose I have an emacs buffer with "word" in the region, then counting the region's length with wc:
```
shell-command-on-region wc
```
returns 0 1 4 , as it should. But other commands don't seem to receive the region as input. For instance, both
```
shell-command-on-region echo
```
and
```
shell-command-on-region locate
```
produce, respectively, an empty result and an error message ("locate: no pattern to search for specified").
Why is the region passed to the command in the first example and not in the second and third one?
# Answer
> 6 votes
> Why is the region passed to the command in the first example and not in the second and third one?
The region is passed in all three cases; but if the command you pass it to does nothing with its *standard input*, then you will not get a useful result.
i.e. You are effectively doing this:
```
printf word | wc
printf word | echo
printf word | locate
```
Note that the default key binding `M-|` is a mnemonic for the fact that you are piping the region as input to the command. That might make it easier to remember.
---
Edit:
> I'm still wondering if there is an emacs command that calls a a command with the region as argument, though.
```
(defun my-shell-command-with-region-arg (command beginning end)
"Prompt for a shell COMMAND, and use the region as an argument.
Buffer text from BEGINNING to END is passed as a single argument to COMMAND."
(interactive (list (read-shell-command "Shell command: ")
(region-beginning)
(region-end)))
(let ((region (buffer-substring-no-properties beginning end)))
(shell-command (concat command " " (shell-quote-argument region)))))
```
---
Tags: shell-command
---
|
thread-53014
|
https://emacs.stackexchange.com/questions/53014
|
Fixed width font for sending mails - notmuch + gmailieer + emacs - How?
|
2019-10-07T18:00:45.177
|
# Question
Title: Fixed width font for sending mails - notmuch + gmailieer + emacs - How?
I have recently set-up my personal mail(gmail) for use through emacs, notmuch and gmailieer. For sending mails, I am relying on the inbuilt smtp mail package and the Message mode.
Earlier, when using the web interface I could set a font while composing the mail. Now, through emacs, when I send an email, it is received in some default variable width font. How do I make sure the mail is sent as fixed width?
Do I have to send a Html mail for that?
# Answer
If you have not specified anything, it will be the receiver's settings that matter, and that's as it should be. If you want to read your emails in a fixed width font, you should be able to set that; let others read them as they wish.
> 1 votes
---
Tags: fonts, notmuch
---
|
thread-53180
|
https://emacs.stackexchange.com/questions/53180
|
Improving Etags support for fortran?
|
2019-10-16T13:42:23.243
|
# Question
Title: Improving Etags support for fortran?
When using `xref` with Fortran I noticed that indexing by `etags` is highly incomplete; Almost exclusively subroutines (and maybe functions) are index, but modules, types, constants and global variables are all ignored.
This situation is even confirmed by the executable:
```
$ etags --help --lang=fortran
In Fortran code, functions, subroutines and block data are tags.
```
I am trying to fix the situation by adding regular expressions manually, e.g.
```
find -name "*.f90" | \
xargs -d $'\n' etags --append \
--regex='{fortran}/[[:blank:]]*module[[:blank:]]+\([[:alnum:]_]+\)/\1/i' \
--regex='{fortran}/\(?:[^(]*\|.*::.*\)\(?1:\_<.*?\_>\)[[:blank:]]*=/\1/i' \
--regex='{fortran}/[[:blank:]]*type[[:blank:]]*\(?:::\)?[[:blank:]]*\(?1:[[:alnum:]_]+\)/\1/i'
```
While it works, this makes me wonder if any better method is available -- maybe a specialized tools giving better etags for fortran, or at least a centralized place to store my custom regex list.
# Answer
The simple solution: Use `ctags -e` instead of `etags` (assuming "Exuberant Ctags"<sup>\[1\]</sup>)
While `man ctags` explicitly says that `etags` is preferred for use with emacs, ctags seems to have much better fortran support. I now use:
```
ctags -e --recurse
# : :
# : `- Recursive processing of subdirectories.
# : Apparently also filters by extension,
# : avoiding the need for manual filtering of `find`.
# :
# `- Output in emacs mode.
# Also changes filename from "tags" to "TAGS"
```
---
<sup>\[1\]</sup> There are multiple flavors of "Ctags". On my system, "Exuberant Ctags" was installed; Language support, Emacs-compatbility and supported flags may deviate. In the comments, "Universal CTags", a fork<sup>\[2\]</sup> of "Exuberant CTags", was recommended.
<sup>\[2\]</sup> https://en.wikipedia.org/wiki/Ctags#Universal\_Ctags
> 2 votes
---
Tags: ctags, xref, etags, fortran
---
|
thread-53036
|
https://emacs.stackexchange.com/questions/53036
|
switching from tmux + terminal emacs to Emacs only
|
2019-10-08T16:23:10.117
|
# Question
Title: switching from tmux + terminal emacs to Emacs only
I am thinking of switching from tmux + terminal emacs (emacs -nw) to just pure emacs. The only thing that is holding me back is tmux offer switching between sessions without switching the terminal window itself (C-b s). For instance, if I have tmux session 0 and tmux session 1. If my current tmux session is attach to session 0, I can easily switch to session 1 by using the keybinding (C-b s 1) without leaving my current Xterm window. I know that there are frames, windows, buffer and server in emacs, but I still can't find anything equivalent to this (swap between frame/server without leaving my main GUI).
**UPDATE:**
I found something pretty close to what I need by starting two emacs server:
In xterm1:
```
emacs --daemon="one"
```
In xterm2:
```
emacs --daemon="two"
```
By doing this, I can group all the file buffers and ansi-term by projects in each emacs server. However, are there any easy way to switch between daemon (the help page use the term "socket") within the Emacs without leaving the GUI?
# Answer
> 1 votes
In Spacemacs, there is the Layout concept where you can isolate buffers into different layout. It groups buffers together and adjacent layout would not have the access to the buffers at the other layout.
My solution is actually very simple. I launch an emacs and create a new frames with M-x new-frame. Now I have multiple emacs windows (say windows 1 and windows 2).*Tho, windows here means emacs frame*
I used emacs keybinding. So, you may replace M-m with SPC if you used Vim keybinding.
In Windows 1, I create a layout by using the following command:
```
M-m l 2
```
Just give your layout a name when it prompts you for a name. I call it work1. Then Open a few files.
In Windows 2, I repeated the same steps with :
```
M-m l 3
```
Let's call it work2 and open up a few files.
In Window 2 (work2), u can switch your buffers by using :
```
C-x b
```
You will found out that the buffers opened in work1 is not available here (It is so much cleaner!!).
You may easily switch between work1 and work2 by using:
```
M-m l <your layout index>
```
# Answer
> 1 votes
I can do that entirely in the gui emacs by running tmux in either ansi-term or zsh (set as the multi-term-program). The two or more tmux sessions can either be created inside or out of emacs.
---
Tags: buffers, frames, emacsclient, tmux
---
|
thread-53186
|
https://emacs.stackexchange.com/questions/53186
|
Don't consider space and tab as abbrev-expand commands, but keep the C-x whatever shortcuts intact
|
2019-10-16T14:27:22.333
|
# Question
Title: Don't consider space and tab as abbrev-expand commands, but keep the C-x whatever shortcuts intact
I read the docs (at bottom) but can't figure this out.
I just started using "abbrev.el", and find that pressing space, tab, C-x ', C-x a ', C-x a e can cause the expansion to happen.
what if I find it dangerous for the expand to happen on tab and space, how can I tell abbrev.el to not expand when pressing tab/space,
I still want to keep the ability to expand using "C-x ', C-x a ', C-x a e"
```
C-x ' runs the command expand-abbrev (found in global-map), which is
an interactive compiled Lisp function in ‘abbrev.el’.
It is bound to C-x ', C-x a ', C-x a e.
(expand-abbrev)
Expand the abbrev before point, if there is an abbrev there.
Effective when explicitly called even when ‘abbrev-mode’ is nil.
Before doing anything else, runs ‘pre-abbrev-expand-hook’.
Calls the value of ‘abbrev-expand-function’ with no argument to do
the work, and returns whatever it does. (That return value should
be the abbrev symbol if expansion occurred, else nil.)
```
# Answer
> 2 votes
When `abbrev-mode` is on, it expands abbreviations anytime you enter a character with non-word syntax, such as a space, a tab, or a period.
If you don't like that behavior, turn *off* `abbrev-mode`. Calling `expand-abbrev` explicitly will still expand your abbreviations, and you can bind that command to whatever keybinding you like.
---
Tags: abbrev
---
|
thread-53189
|
https://emacs.stackexchange.com/questions/53189
|
Run R code on selected object
|
2019-10-16T14:43:23.557
|
# Question
Title: Run R code on selected object
I am missing (or not aware) of a feature in ESS to run some R code on selected text. When editing a script, like
```
df1 <- data.frame(a=1:100,b=rnorm(100))
```
I often want to see `head(df1)` in my terminal. I'd like to be able to move the cursor to `df1` and run an elisp function that sends `head(df1)` to the R terminal. Can you direct me to how to do that, please? If I can define a few R-functions in Elisp functions and assign them to shortcuts, it would often ease my workflow.
# Answer
> 3 votes
Here's a quick and dirty approach. Depending on what you want there's lots of room for improvement.
```
(defun head-at-point ()
(interactive)
(let ((target (thing-at-point 'symbol)))
(ess-send-string (ess-get-process ess-local-process-name)
(concat "head(" target ")\n"))))
```
---
Tags: ess, r
---
|
thread-53177
|
https://emacs.stackexchange.com/questions/53177
|
Tramp x11 on Mac os (local) , centos (remote)
|
2019-10-16T07:21:33.610
|
# Question
Title: Tramp x11 on Mac os (local) , centos (remote)
I understand that I should be able to use X11 to show graphs from a remote R when I use a local emacs to connect to the remote machine with tramp.
I have tried a few different things but can not get it to work. I know that the server will work with X11 as if I ssh in using a normal terminal it works.
Currently my `.emacs` file has:
```
;; emacs x11 tramp
(add-to-list 'tramp-remote-process-environment
(format "DISPLAY=%s" (getenv "DISPLAY")))
(with-eval-after-load 'tramp
(add-to-list 'tramp-methods
'("sshx11"
(tramp-login-program "ssh")
(tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
("-e" "none") ("-Y") ("%h"))) ; tried -Y and -X :(
(tramp-async-args (("-q")))
(tramp-remote-shell "/bin/sh")
(tramp-remote-shell-login ("-l"))
(tramp-remote-shell-args ("-c"))
(tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
("-o" "UserKnownHostsFile=/dev/null")
("-o" "StrictHostKeyChecking=no")
("-o" "ForwardX11=yes")))
(tramp-default-port 22)))
(tramp-set-completion-function "sshx11" tramp-completion-function-alist-ssh))
```
On my local machine I also have two files, `config` and `sshd_config` in my `.ssh` folder. The latter simply contains `X11Forwarding yes` whereas the former has `Host my_alias
Hostname myhost
User myusername
ForwardX11 yes
ForwardX11Trusted yes` (with appropriate subs)
I connect to my server with `C-x C-f sshx11:user@host:/` I then do `M-x shell` and select the "remote shell path" (to bin bash) and the starting directory.
Now when in the shell if I try `echo $DISPLAY` I get `/private/tmp/com.apple.launchd.zmPeFoMlxA/org.macosforge.xquartz:0`
But if I try to load an xprogram such as `xterm` to test I get: `xterm Xt error: Can't open display: /private/tmp/com.apple.launchd.zmPeFoMlxA/org.macosforge.xquartz:0`
# Answer
I managed to kind of fix this by running "echo $DISPLAY" in a normal terminal and copying the value of that into the emacs terminal with "export DISPLAY=localhost:12.0" the value does change some times.
> 1 votes
---
Tags: osx, tramp, x11
---
|
thread-53104
|
https://emacs.stackexchange.com/questions/53104
|
Stop company-lsp from completing function arguments
|
2019-10-11T19:22:37.933
|
# Question
Title: Stop company-lsp from completing function arguments
I try to configure `lsp-mode` and `company-lsp` with `python-language-server` for python autocompletion, but when I choose completion candidate it completes with function arguments. How can I prevent this behaviour?
For example for function
```
def foo(arg1, arg2):
...
```
It will autocomplete like
```
foo(arg1, arg2)
```
I tried to set `(setq lsp-enable-snippet nil)` but it didn't help
# Answer
There are actually two variables that drive this behavior.
You tried the first one, `lsp-enable-snippet` and it didn't work. This means that the culprit is probably `company-lsp`, which engages in a similar behavior and uses a variable that is nearly identical, `company-lsp-enable-snippet`.
Try disabling that with `(setq company-lsp-enable-snippet nil)` and see if that does the trick .
As an aside, when I struggle with a problem like this (where I have a suspicion there is a tangential/related mode driving the behavior), I try to looking for similarly named variables or variables that contain a reference to the behavior/feature/setting at hand. It's not a perfect heuristic, but it is how I found out about company's complementing behavior to lsp mode as answer above. If you have a feeling a problem is of this nature, next time try using `C-h v` and searching for the culprit variable.
> 3 votes
---
Tags: python, company-mode, lsp-mode
---
|
thread-53202
|
https://emacs.stackexchange.com/questions/53202
|
Automatically fixing bad indentation (Scheme-Lisp)
|
2019-10-17T14:00:05.717
|
# Question
Title: Automatically fixing bad indentation (Scheme-Lisp)
Let's say I make this code with bad formatting: is there an emacs command that can automatically fix indentation? I know this question has been asked a few times before, but all the answers I've seen seem very technical (I'm a CS noob).
```
(define (count-until x y list1)
(define (iter list1 score)
(if (eq? (car list1) x)
(iter (cdr list1) (+ score 1))
(iter (cdr list1) score)))
(iter list1 0))
```
# Answer
> 1 votes
Select the whole code (e.g. by pressing `C-Space` at the start and using cursor keys to get to the end) and run `indent-region` (bound to `C-M-\` in my Emacs).
---
Tags: indentation, scheme
---
|
thread-53204
|
https://emacs.stackexchange.com/questions/53204
|
Org Mode - Stop Recurring Events From Appearing as Late on Agenda
|
2019-10-17T15:26:33.743
|
# Question
Title: Org Mode - Stop Recurring Events From Appearing as Late on Agenda
I am using the org mode agenda and my issue is that recurrent scheduled items appear as late everyday.
For example an event that happens every Tuesday will also appear every Wednesday as 1 day late, on Friday as 2 days late etc...
There is no reason why I would want that, so how can I stop those "late" events from appearing, except on the dates they are scheduled to happen?
# Answer
Use a plain timestamp rather than a scheduled or deadline timestamp.
> 2 votes
---
Tags: org-mode
---
|
thread-53209
|
https://emacs.stackexchange.com/questions/53209
|
How to prompt user for a proper writable file in Emacs Lisp?
|
2019-10-17T22:22:46.717
|
# Question
Title: How to prompt user for a proper writable file in Emacs Lisp?
I need to prompt the user for a file which is 1) not a directory 2) if already exists, is writable.
I know I can use `read-file-name`, but I'm not sure how to filter out the improper files. Specifically, I need to filter out those are either 1) a directory or 2) read-only (not writable).
# Answer
The 6th argument to `read-file-name` is a `PREDICATE` that filters completion candidates (file names). `C-h f read-file-name` says, about it:
> Sixth arg `PREDICATE`, if non-`nil`, should be a function of one argument; then a file name is considered an acceptable completion alternative only if `PREDICATE` returns non-`nil` with the file name as its argument.
The file name passed to the predicate is a relative name, so your predicate function may need to use `expand-file-name` to obtain an absolute file name. Then you will want to apply function `file-directory-p` to each candidate, to see if it's a directory, and apply function `file-attribute-modes` to each candidate, to see if it is writable.
See also (elisp) File Attributes for info about function `file-attributes` (search for `file-attribute-modes` in that manual node).
> 1 votes
---
Tags: files
---
|
thread-53201
|
https://emacs.stackexchange.com/questions/53201
|
Why does ido, when used with recentf, show candidates in the order it does?
|
2019-10-17T13:39:29.833
|
# Question
Title: Why does ido, when used with recentf, show candidates in the order it does?
Wanting to stay simple as possible I refrain from using Helm or Ivy etc. and use IDO. Ido-switch-buffer is supposed to allow me to access recently opened buffers quite efficiently with the help of recentf. which I enabled as well. My config thus reads
```
(recentf-mode t)
(setq recentf-max-menu-items 25)
(setq recentf-max-saved-items 25)
(ido-mode t)
(setq ido-everywhere t)
(global-set-key (kbd "C-x C-b") 'ido-switch-buffer)
```
but when I invoke ido-switch-buffer, listed first are log files, scratch buffe,etc. only later followed by files I care about.
Am I forgetting something in the config? A recentf file is created and written to, so I suppose its working.
# Answer
> 1 votes
Try:
M-x recentf-ido-find-file (my favorite)
```
(defun recentf-ido-find-file ()
"Find a recent file using ido."
(interactive)
(let ((file (ido-completing-read "Choose recent file: " recentf-list nil t)))
(when file
(find-file file))))
```
and M-x ido-recenf-open
```
(defun ido-recentf-open ()
"Use `ido-completing-read' to \\[find-file] a recent file"
(interactive)
(if (find-file (ido-completing-read "Find recent file: " recentf-list))
(message "Opening file...")
(message "Aborting")))
```
I am using them from years: Helpful: Recently opened files in ido-mode
---
Tags: ido, recentf
---
|
thread-53179
|
https://emacs.stackexchange.com/questions/53179
|
Merging diffs/hunks
|
2019-10-16T10:15:12.733
|
# Question
Title: Merging diffs/hunks
When using ediff, I often get conflicts like this:
```
<<<<<<< variant A
added_function_1 () {
=======
added_function_2 () {
>>>>>>> variant B
<<<<<<< variant A
body1
=======
body2
>>>>>>> variant B
}
```
when I expect this:
```
<<<<<<< variant A
added_function_1 () {
body1...
=======
added_function_2 () {
body2...
>>>>>>> variant B
}
```
Ediff created two chunks where I expected only one. Is there a way to merge them?
This also happens with `smerge-ediff`, it actually splits up the chunks the diff tool generated.
---
What I actually want is of course
```
<<<<<<< variant A
added_function_1 () {
body1...
}
=======
added_function_2 () {
body2...
}
>>>>>>> variant B
```
but I guess that would require semantic diffing.
# Answer
I think you're looking for `M-x smerge-combine-with-next RET`.
> 1 votes
---
Tags: ediff, smerge
---
|
thread-53200
|
https://emacs.stackexchange.com/questions/53200
|
emacs -nw mode, when you paste in some text from another application emacs sometimes misses parts or stops halfway. how can I mitigate it?
|
2019-10-17T13:16:00.110
|
# Question
Title: emacs -nw mode, when you paste in some text from another application emacs sometimes misses parts or stops halfway. how can I mitigate it?
In macOS in `emacs -nw` mode, when you paste in some text from another application emacs sometimes misses parts or stops halfway. Often I see a tilde as the last character entered, when there wasnt even a tilde in the incoming text.
I read somewhere that switching to fundamental mode helps, but there's still some 10% of cases where even that doesn't help. Is there anything else one can try to mitigate this issue?
# Answer
> 2 votes
When you paste some text into a terminal, the application sees it just as if you had typed the clipboard content. Depending on the software involved (operating system, clipboard mechanism, terminal emulator, Emacs and the system libraries that it uses), this can result in text being lost, or in text being changed because some inputs trigger special behavior. A common kind of special behavior is automatic indentation after line breaks, which increases whatever indentation is in what you paste.
A sure-fire way to avoid trouble is to not paste through the terminal. You can obviously do that by running a GUI Emacs, but it may be possible even in a terminal Emacs. I think that on macOS, as long as Emacs is running locally (as opposed to remotely, e.g. via SSH), you can run the `pbpaste` command to output the clipboard content.
`M-1 M-! pbpaste RET`
The analog on systems using X11 is `M-1 M-! xsel -b RET` or `M-1 M-! xclip -sel c RET` (for what X11 calls the clipbard; plain `xsel` or `xclip -o` gives you the text selected with the mouse but not explicitly copied). This works in a terminal Emacs as long as the environment variables to connect to the X11 display are set (`DISPLAY` and if needed `XAUTHORITY`), which is typically the case if you always work in a GUI session, but may not be the case if Emacs is running under Screen or Tmux.
---
Tags: copy-paste
---
|
thread-53196
|
https://emacs.stackexchange.com/questions/53196
|
How to quickly revert the buffer?
|
2019-10-17T01:58:07.580
|
# Question
Title: How to quickly revert the buffer?
`revert-buffer` is often slower than closing an opening the same file.
I've noticed - for example, I can undo to the state of the file before reverting.
While this might be useful in some cases, I would like to clear undo history and load the file as if I'd just opened emacs.
Some possible solutions:
**Fast Revert**
* Disable undo.
* Clear undo history, jump list ... etc.
* Clear the buffer.
* Load the data from the file into the buffer.
* Re-enable undo.
**Fake Revert**
* Store the scroll & cursor position.
* Close the buffer.
* Open the buffer.
* Restore the scroll & cursor position.
While I could write this, it seems like there may be a more elegant solution then writing my own `fast-revert-buffer` function.
Does Emacs provide a way to do this already?
# Answer
The `revert-buffer` function takes a few parameters which I think make the reload faster. I've got this bound to a keyboard shortcut for reloading the current buffer, it feels as fast as when you first open the file:
```
(defun reload-file-preserve-point ()
(interactive)
(when (or (not (buffer-modified-p))
(y-or-n-p "Reverting will discard changes. Proceed?"))
(save-excursion
(revert-buffer t t t))
(setq buffer-undo-list nil)
(message "Buffer reverted")))
```
> 2 votes
---
Tags: revert-buffer
---
|
thread-50467
|
https://emacs.stackexchange.com/questions/50467
|
Shortcut to actual previous line in markdown mode, or end of section
|
2019-05-12T16:57:47.427
|
# Question
Title: Shortcut to actual previous line in markdown mode, or end of section
I use `markdown-mode` and often fold the tree. I sometimes need to go to the last line of a tree, e.g. if I adjust the tree heading and then want to work at the last leaf. I suppose a shortcut can take me to the last line of a subtree. Alternatively, I could fold the subtree, go to the next heading, and go up one line (`C-p` or `previous-line`), but it goes to the previous visible line, not the actual previous line.
How can I go to the last line under a heading at point, or go to the actual previous line of the next heading?
# Answer
> 1 votes
From the documentation of `previous-line` (`C-h f previous-line RET`):
```
This function is for interactive use only;
in Lisp code use `forward-line' with negative argument instead.
...
If the variable ‘line-move-visual’ is non-nil, this command moves
by display lines. Otherwise, it moves by buffer lines, ...
```
So the problem was trying to move over buffer lines when the tree was folded with visual lines. The documentation suggests `(forward-line -1)`.
Here is a function that does it, knowing that Markdown mode inherits from Outline mode. If the tree is folded, you had better move to the heading, and unfold the tree. To know whether the tree is folded, place point at the first character after the end of the heading. then you can unfold the tree ("cycling visibility") and place point at the end:
```
(defun my-outline-move-end-of-subtree ()
"Move point to the last line under this tree."
(interactive)
(outline-back-to-heading)
;; Check if tree is folded by placing point at the end of the heading
(forward-line)
(backward-char)
(when (invisible-p (point))
(markdown-cycle))
(ignore-errors
(outline-end-of-subtree)))
```
---
Tags: key-bindings, markdown-mode
---
|
thread-53221
|
https://emacs.stackexchange.com/questions/53221
|
Simplest Pattern for matching Identifiers in complex Regular Expressions?
|
2019-10-18T09:45:31.813
|
# Question
Title: Simplest Pattern for matching Identifiers in complex Regular Expressions?
I frequently need a regular expression, that approximately matches identifiers in a given environment. Ignoring the "must not start with a number" requirement, this would mean e.g.
```
[[:alnum:]_]+ e.g. Python, C, ...
```
When used in complicated expressions, this is rather verbose. So I was wondering if there is any shorter way to express "character that may be part of an identifier or keyword".
Things that didn't work:
```
\w or \sw . . . . Matches only word characters.
\s_ . . . . . . . Matches symbol constituents,
EXCEPT for word characters.
\(?:\w\|\s_\) . . Does the job, but very verbosely.
Delegates knowledge of the languages rules
to the syntax table.
\_<.*?\_> . . . . Works for simple cases, but breaks down
when trying to be specific; e.g. \_<.*?z\_>
will match the whole line
foo bar baz
rather than just "baz".
```
# Answer
I do not know a shortcut for identifier regexps. Maybe, that is due to the complicated rules that exist for identifiers of some languages.
Nevertheless you can define your own format strings and convert them by `format-spec` to regexps with identifiers.
The following lisp code defines a function `my-re` for transforming extended regular expressions with `%i` as regexp for identifiers to normal regular expressions.
Furthermore, it exemplarily defines `my-re-search-forward` for searching with extended regexps.
`format-spec` implies some constraints:
* if you do not want the identifier regexp at some place where `%i` occurs in the search string you have to replace it with `%%i`
* the regexp may not end with a single `%` if that is a really problem you can replace it with something like `%\{1\}`
```
(defconst my-identifier-re "\\(?:\\w\\|\\s_\\)\\(?:\\w\\|\\s_\\|[0-9]\\)+"
"Regular expression for identifiers.")
(defconst my-re-format-with-identifier
`((?i . ,my-identifier-re)
(?% . "%") ;; escape
;; self-insert all others:
,@(cl-loop for c from 0 upto 255
collect (cons c (string ?% c))))
"Format for format string with ")
(defun my-re (re)
"Transform extended REGEXP into regexp."
(format-spec re my-re-format-with-identifier))
(defun read-interactive (fun)
"Read argument list like `interactive' does."
(call-interactively `(lambda (&rest args)
,(interactive-form fun)
args)))
(defun my-re-search-forward (re &rest args)
"Imitate `re-search-forward' with RE and ARGS but add %i as identifier re."
(interactive (read-interactive 're-search-forward))
(apply #'re-search-forward
(my-re re)
args))
(defun my-occur (re &rest args)
"Run `occur' with `re-search-forward' replaced by `my-re-search-froward'."
(interactive (read-interactive 'occur))
(apply #'occur (my-re re) args))
```
Example: `my-occur` input for a search for C-function declarations/headers. It is not complete but covers quite many situations and there are only a few false positives.
```
^ \{0,3\}\(%i[&*]?[[:space:]
]+\)+%i[[:space:]
]*( *\(%i[&*]? *\)*\(, *\(%i[&*]? *\)+\)*)[[:space:]
]*\({\|;\)
```
> 3 votes
---
Tags: regular-expressions, syntax-table
---
|
thread-53228
|
https://emacs.stackexchange.com/questions/53228
|
How to ignore case when switching buffers?
|
2019-10-18T15:43:22.817
|
# Question
Title: How to ignore case when switching buffers?
I want to open a buffer called `Echo.md` and `switch-buffer` (`C-x b`) does not auto-complete it when I type `echo` because of the case. But `find-file` does auto-complete from lower-case to upper-case. The documentation for either function does not mention case.
How can Emacs ignore case when switching buffers?
# Answer
> 4 votes
Customize option `read-buffer-completion-ignore-case` to non-`nil`.
`C-h v read-buffer-completion-ignore-case` tells you:
> **`read-buffer-completion-ignore-case`** is a variable defined in `C source code`.
>
> Its value is `nil`
>
> Documentation:
>
> Non-`nil` means completion ignores case when reading a buffer name.
>
> You can customize this variable.
>
> This variable was introduced, or its default value was changed, in version 23.1 of Emacs.
---
Please consider filing a bug report (enhancement request), asking for the doc of `switch-to-buffer` and similar commands to mention the option: **`M-x report-emacs-bug`**.
I agree that it's not obvious. I looked at the source code for that command and followed the trail backward through a few functions to finally stumble on the option. (Yes, I could have guessed there was such an option and tried `apropos` to find it.)
---
Tags: buffers, case-folding
---
|
thread-53227
|
https://emacs.stackexchange.com/questions/53227
|
Spacemacs pdf-tools inverse search with keyboard possible?
|
2019-10-18T15:12:02.283
|
# Question
Title: Spacemacs pdf-tools inverse search with keyboard possible?
I am running spacemacs and pdf-tools on Ubuntu 18.04. It does work quite well, however now I asked myself whenever there is an option to do inverse search (or to make a new command doing inverse search) with a keyboard key.
The built in command `Ctrl-Mouse-1` works well, but could I for example inverse search from the pdf back to the beginning of the page in the tex file with a keystroke? Or in a more sophisticated, but versatile way could I run pdf-occur, let the results show up and then go to the line in my editing file with a keyboard command?
# Answer
> 2 votes
If `Ctrl-Mouse-1` works well for you, you can always write a function that emulates it's behavior and bind a key to it. If, as you indicate, you want to sync backward to the position in the tex-file corresponding to the beginning of the pdf page, you can emulate a `Ctrl-Mouse-1` click on position (1,1) with the function:
```
(defun pdf-sync-backward-to-top-of-page ()
"Use coordinate (1,1) to sync backward"
(interactive)
(pdf-sync-backward-search 1 1))
```
and bind it to a key (here "s-t"):
```
(add-hook 'pdf-sync-minor-mode-hook
(lambda () (define-key pdf-sync-minor-mode-map
(kbd "s-t")
'pdf-sync-backward-to-top-of-page)))
```
---
Tags: spacemacs, latex
---
|
thread-53217
|
https://emacs.stackexchange.com/questions/53217
|
Org mode 9.2.6 - Org agenda - match tags/prop/todo query hangs
|
2019-10-18T04:19:47.037
|
# Question
Title: Org mode 9.2.6 - Org agenda - match tags/prop/todo query hangs
After typing a keyword the command just hangs, regardless of the query.
The trace is as follows:
```
Debugger entered--Lisp error: (quit)
org-add-prop-inherited("qpct")
#[257 "\300!\262\301!\207" [copy-sequence org-add-prop-inherited] 3 "\n\n(fn X)"]("qpct")
mapcar(#[257 "\300!\262\301!\207" [copy-sequence org-add-prop-inherited] 3 "\n\n(fn X)"] ("qpct"))
org-scan-tags(agenda (lambda (todo tags-list level) (progn (setq org-cached-props nil) (or (and (member "bug" tags-list))))) nil)
org-tags-view(nil)
funcall-interactively(org-tags-view nil)
call-interactively(org-tags-view)
org-agenda()
org-agenda-append-agenda()
funcall-interactively(org-agenda-append-agenda)
call-interactively(org-agenda-append-agenda nil nil)
command-execute(org-agenda-append-agenda)
```
Is anyone facing the same issue?
# Answer
I fixed my issue by force recompiling of all the packages. I think things got messed up after a recent update of packages. Along with issues with org agenda, I was also seeing issues with org html export.
I ran the following function: `(byte-recompile-directory package-user-dir nil 'force)`
> 1 votes
---
Tags: org-mode
---
|
thread-53238
|
https://emacs.stackexchange.com/questions/53238
|
make org "c-c c-c" actually do something useful on a simple line of text
|
2019-10-19T03:02:14.947
|
# Question
Title: make org "c-c c-c" actually do something useful on a simple line of text
how can one teach emacs to do something useful here?
for example if the current line contains the word "FOO" anywhere, change it to whatever the string returned by special-lisp-function-001
# Answer
You can attach something to `org-ctrl-c-ctrl-c-final-hook`:
> Hook for functions attaching themselves to ‘C-c C-c’.
>
> This can be used to add additional functionality to the C-c C-c key which executes context-dependent commands. This hook is run after any other test, while ‘org-ctrl-c-ctrl-c-hook’ is run before the first test.
To add something to a hook, we use `add-hook`:
```
(add-hook 'org-ctrl-c-ctrl-c-final-hook
(lambda () (message "yeah, you got \"%s\"" (word-at-point))
t))
```
Now, when you press `C-c C-c`, and org has no other action for the place that point is at, it'll send a message in the minibuffer. Obviously you can change this as necessary.
Note that we explicitly return a non-nil value so that `org-ctrl-c-ctrl-c` knows to stop running other functions in `org-ctrl-c-ctrl-c-final-hook` once we hit this one.
> 8 votes
---
Tags: org-mode
---
|
thread-53106
|
https://emacs.stackexchange.com/questions/53106
|
How to search within current folder and sub folder (Spacemacs)
|
2019-10-11T21:29:42.057
|
# Question
Title: How to search within current folder and sub folder (Spacemacs)
When I do space + s + P, I can search within the project which is cool. But I would like to search in current foler and subfolder. how to achieve that?
# Answer
> 1 votes
## When I'm looking for file names:
`M-x find-name-dired`
I have it bound to `SPC f d`
`(global-set-key (kbd "M-m f d") 'find-name-dired)`
## When I'm looking for text search (grep)
* `M-x rgrep`
* `SPC f g`
---
Tags: spacemacs
---
|
thread-53236
|
https://emacs.stackexchange.com/questions/53236
|
Academic research about Emacs
|
2019-10-18T18:45:01.863
|
# Question
Title: Academic research about Emacs
I am looking for academic research about Emacs. Any disciplines are interesting; psychology, economics, design, computer science including subdisciplines such as HCI and software engineering, philosophy, anthropology, science and technology studies, political economy, theology, culinary sciences..., history, comparative literature, cultural studies, math; everything and anything is interesting.
The ones I found with a quick search were these two:
Twidale, Michael B.; Jones, M. Cameron. 2005. "Let them use emacs": the interaction of simplicity and appropriation, in *International reports on socio-informatics* 2(2) 66-71. Retrieved from https://www.ideals.illinois.edu/handle/2142/9607
Palmer, J.; Duffy, T.; Gomoll, K.; Gomoll, T; Richards-Palmquist, J. and Trumble, J. A. 1988. "The design and evaluation of online help for Unix EMACS: capturing the user in menu design," in *IEEE Transactions on Professional Communication*, vol. 31, no. 1, pp. 44-51, March 1988. doi: 10.1109/47.6920. Retrieved from https://ieeexplore.ieee.org/abstract/document/6920/references
# Answer
> 6 votes
Answering myself :) There is a new page (which I just set up today) on EmacsWiki called Research About Emacs, and also a Zotero group called Emacs for all your reference convenience.
The former is, hopefully and potentially a growing, maintainable, close-to-Emacs-community and also search engine friendly page for documenting, disseminating, organizing and debating research about and around Emacs. The latter is hopefully a growing, maintainable and also close-to-academic-community place for collecting Emacs references now and in the future.
This answers the question. Have a nice day, self, and enjoy the readings collected so far. So far they are
Aspinall, D. (2000). Proof General: A Generic Tool for Proof Development. In S. Graf & M. Schwartzbach (Eds.), *Tools and Algorithms for the Construction and Analysis of Systems* (pp. 38–43). Springer Berlin Heidelberg.
Crestani, M. (2005). A New Garbage Collectorfor XEmacs (Masters thesis, University of Tübingen). Retrieved from https://crestani.de/xemacs/pdf/thesis-newgc.pdf
Lapalme, G. (1998). Dynamic tabbing for automatic indentation with the layout rule. *Journal of Functional Programming*, 8(5), 493–502. https://doi.org/10.1017/S0956796898003098
Monnier, S., & Sperber, M. (2018, September). Evolution of Emacs Lisp. 36.
Neubauer, M., & Sperber, M. (2001). Down with Emacs Lisp: Dynamic Scope Analysis. *Proceedings of the Sixth ACM SIGPLAN International Conference on Functional Programming*, 38–49. https://doi.org/10.1145/507635.507642
Palmer, J., Duffy, T., Gomoll, K., Gomoll, T., Richards-Palmquist, J., & Trumble, J. A. (1988). The design and evaluation of online help for Unix EMACS: Capturing the user in menu design. *IEEE Transactions on Professional Communication*, 31(1), 44–51. https://doi.org/10.1109/47.6920
Stallman, R. M. (1981). EMACS the Extensible, Customizable Self-documenting Display Editor. *Proceedings of the ACM SIGPLAN SIGOA Symposium on Text Manipulation*, 147–156. https://doi.org/10.1145/800209.806466. Available online at https://www.gnu.org/software/emacs/emacs-paper.html
Twidale, M. B., & Jones, M. C. (2005). “Let them use emacs”: The interaction of simplicity and appropriation. *International Reports on Socio-Informatics*, 2, 66–71. Retrieved from http://hdl.handle.net/2142/9607
Voit, K. (2013). What really happened on September 15th 2008? Getting The Most from Your Personal Information with Memacs. ArXiv:1304.1332 \[Cs\]. Retrieved from http://arxiv.org/abs/1304.1332
Zhong, S., & Xu, H. (2019). Intelligently Recommending Key Bindings on Physical Keyboards with Demonstrations in Emacs. *Proceedings of the 24th International Conference on Intelligent User Interfaces*, 12–17. https://doi.org/10.1145/3301275.3302272
---
Tags: emacs-development, emacs-history
---
|
thread-53215
|
https://emacs.stackexchange.com/questions/53215
|
Mark input in swiper-thing-at-point
|
2019-10-18T02:36:16.817
|
# Question
Title: Mark input in swiper-thing-at-point
Having some command automatically populate the input string is a great thing (particularly, I refer to the feature that `swiper-thing-at-point` provides).
However, I would like to enhance this functionality even more by being able to have the input string automatically marked after running this command. The rationale behind it is that I find myself using swiper mostly for two things:
1. Find other occurrences of the thing that I currently have at point;
2. Find an arbitrary text in the current buffer, regardless of thing at point.
For each of these cases, having the input string automatically marked is optimal because I can, respectively, with a single command,
1. Start searching other occurrences of the thing at point right away;
2. Start typing the string I have in mind right away, knowing that, whatever input string there is, it will be completely replaced (assuming `delete-selection-mode` is enabled), without having to check if an initial input was populated in the minibuffer and deleting it in case it was.
I have tried creating a function to do so, but the problem is that the part of the function that tries to mark the input string (which should be whole line inside the minibuffer) is only executed when I finish the swiper search, i.e., I end up selecting a region in the buffer where I executed the function (not in the minibuffer), and the swiper input string is never selected (and so I have to delete it manually). What would be the best way to solve this problem?
# Answer
I use helm-swoop just like what you described, so the same technique can work for you in swiper too. Helm-swoop picks up the input at point and I want it to be selected automatically, so I can instantly overtype it with delete selection mode. I push the selection keys to unread command events, so they are executed automatically when swoop is waiting for input. I used a zero idle timer to push the keys, because it did not work without it for some reason, so I use it to wait until emacs becomes idle and push the keys then:
```
(global-set-key (kbd "C-a") (lambda ()
(interactive)
(run-with-idle-timer
0 nil (lambda ()
(push 'S-end unread-command-events)
(push 'home unread-command-events)))
(helm-swoop)))
```
> 2 votes
# Answer
I don't have an answer related to Swiper, sorry.
But FWIW, Icicles provides what (I think) you're describing.
---
1. You can insert buffer **text at point** into the minibuffer (appending it to what's already there).
You can take advantage of this feature for searching by using **`M-e`** when incremental-searching. That puts you in the minibuffer to edit the search string. (Then resume Isearch, e.g. `C-s`.)
*You insert text at point with **`M-.`**.*
So for example, you use `C-s M-e M-. C-s` to search for something at point. The first `C-s` starts searching; `M-e` activates the minibuffer; `M-.` inserts a thing at point; and the second `C-s` searches for it.
If you *repeat* `M-.` then you can either (1) grab more text from the buffer, appending it to what you've already grabbed, or (2) grab something different at the cursor (replacing the thing that you just grabbed).
The first alternative is kind of like using `C-w` in Isearch - it grabs successive things of the same kind. The second alternative cycles among different kinds of thing-at-point, to get to the one you want.
You can choose which of those two behaviors for repeated `M-.` to use by default, with option **`icicle-default-thing-insertion`**.
And you can change the behavior on the fly using `C-u`: it flips from your chosen default behavior to the alternative behavior.
You can customize what kinds of things can be grabbed using option **`icicle-thing-at-point-functions`**.
This all explained here: Inserting Text from Cursor.
---
2. Second, there's option **`icicle-default-value`**, which controls whether the **default value** provided by the current command is automatically inserted in the minibuffer, so you don't need to retrieve it with `M-n`. My own preference for the option value is `insert-end`, but it sounds like you might prefer, say, `preselect-end`.
These are the possible values:
* `nil` \- Do not insert default value or add it to prompt.
* `t` \- Add default value to `completing-read` prompt. Do not insert it.
* `insert-start` \- Insert default value and leave cursor at start.
* `insert-end` \- Insert default value and leave cursor at end.
* `preselect-start` \- Insert and preselect default value; leave cursor at beginning.
* `preselect-end` \- Insert and preselect default value; leave cursor at end.
.
Preselection can be useful in Delete Selection mode. It makes it easy to replace the value by typing characters, or delete it by hitting `C-d` or `DEL` (backspace). However, all of the initial input is lost if you type or hit `C-d` or `DEL`. That is inconvenient if you want to keep most of it and edit it only slightly.
Even without Delete Selection mode you can always completely empty the minibuffer using **`M-k`**. (I use Delete Selection mode all the time, including in the minibuffer, but to clear the minibuffer I use `M-k` \- no need to select anything.)
> 1 votes
# Answer
For completeness, here is what I ended up implementing, based on @Tom's answer:
```
(defun acg/with-marked-input (&rest args)
"Mark input of minibuffer. To be used as advice before any
function that starts with an initial input in the minibuffer."
(run-with-idle-timer
0 nil (lambda ()
(push 'C-S-right unread-command-events)
(push 'C-left unread-command-events))))
(advice-add 'swiper-thing-at-point :before #'acg/with-marked-input)
```
Then I binded `ESC` to perform `abort-recursive-edit` instead of `minibuffer-keyboard-quit` (as I had before), since then I can quit the minibuffer right away with having to click it twice (where once would solely deselect text):
```
(define-key ivy-minibuffer-map [escape] 'abort-recursive-edit)
```
> 1 votes
---
Tags: search, minibuffer, swiper, thing-at-point
---
|
thread-53207
|
https://emacs.stackexchange.com/questions/53207
|
Is it possible to use whitespace-mode without specyfing a background (or foreground) color?
|
2019-10-17T18:35:37.210
|
# Question
Title: Is it possible to use whitespace-mode without specyfing a background (or foreground) color?
I like having non-breaking spaces and a few other characters represented in my buffer as visible characters. The problem I have is that whitespace-mode seems determined to set the background color. In modes where the background color is different (for example, in src blocks in Org), the ordinary space characters are really obtrusive.
I can workaround this by not having those blocks appear in a different background color, but that seems like it shouldn't be necessary.
I've tried a few things that I've found by searching, but none appear to work.
# Answer
I eventually concluded that this was interaction between whitespace-mode attempting to use faces and Org mode attempting to use faces and the result just being incompatible. I told whitespace-mode to stop using faces and the result...better.
> 0 votes
---
Tags: faces, whitespace-mode
---
|
thread-53250
|
https://emacs.stackexchange.com/questions/53250
|
How to tell Occur to show the line in the top of the buffer
|
2019-10-20T15:50:43.177
|
# Question
Title: How to tell Occur to show the line in the top of the buffer
I usually use `occur` to make an index of the beginning of different things. When I jump to the occurrence, `Occur` shows the line in the middle of the buffer. How can I instruct `occur` to show the occurrence in the top of the buffer?
Thanks.
# Answer
You can scroll the window in `occur-mode-find-occurrence-hook` such that point is at the top of the window:
```
(defun my-occur-recenter ()
"Scroll point to the top of the window."
(recenter 0))
(add-hook 'occur-mode-find-occurrence-hook #'my-occur-recenter)
```
Notes:
1. The functions registered in `occur-mode-find-occurrence-hook` are called with point at the position of the selected occurence.
2. `recenter` called with a non-negative argument adjusts the vscroll of the window such that point is located that many lines from the top line.
> 3 votes
---
Tags: hooks, motion, occur
---
|
thread-53243
|
https://emacs.stackexchange.com/questions/53243
|
Fold all regexp matches
|
2019-10-19T15:30:46.280
|
# Question
Title: Fold all regexp matches
I'm working on email templates using `web-mode`, which – alas – requires inline styling galore… many of my opening tags won't fit on a single line even on a 4K-Display due to the massive amount of Attributes.
In order to reduce the clutter when editing the content I would like to fold only the attributes of all HTML-tags. This could be achieved if there was a way to fold all strings matching the following regex: `"[[:alnum:]]+=[^>]+"` or the first group of this one (probably safer): `"<[[:alnum:]]+ +\\([^>]+\\)>"`.
By folding I basically mean hiding the text, possibly having it replaced by a clickable placeholder revealing it when clicked. AucTex does it like that.The replacement part is not necessary htough. Basically all I need is to temporarily get the clutter out of sight, e.g.:
`<div class="someclass"> foo </div>``<div …> foo </div>`
I've tried `hs-mode`, but it seems to only operate on blocks, which won't work in my case since the Attributes are on the same line as the possible START and END regexes supposed to surround a block.
It should be possible to fold a regex, given the way e.g. AucTeX folds the content of certain macros etc. Any suggestions?
Many thanks in advance
Oliver
# Answer
The following elisp code defines a new minor mode `web-hide-attr-mode`. It is hooked to `web-mode`. So it is already active if you open a document in `web-mode`.
You can toggle it by `M-x` `web-hide-attr-mode`.
It works by adding an entry to `font-lock-keywords` that puts the `invisible` property `web-hide-attr` on the html attributes and by adding `web-hide-attr` to the `buffer-invisibility-spec`. It actually puts `(web-hide-attr . t)` there to generate the ellipses.
```
(defconst web-hide-attr-font-lock-keywords
'(("<[[:alnum:]]+ +\\([^>]+\\)>"
1
'(face default invisible web-hide-attr)
'append t
))
"Keywords for hiding attributes in `web-mode'.")
(define-minor-mode web-hide-attr-mode
"Hide tag attributes in `web-mode'."
:lighter " H"
(font-lock-add-keywords nil web-hide-attr-font-lock-keywords)
(if web-hide-attr-mode
(add-to-invisibility-spec '(web-hide-attr . t))
(remove-from-invisibility-spec '(web-hide-attr . t)))
(font-lock-flush)
(font-lock-ensure))
(add-hook 'web-mode-hook #'web-hide-attr-mode)
```
> 2 votes
---
Tags: regular-expressions, code-folding
---
|
thread-53225
|
https://emacs.stackexchange.com/questions/53225
|
Org Mode - Targeted Expansion of Headings
|
2019-10-18T13:12:25.087
|
# Question
Title: Org Mode - Targeted Expansion of Headings
In org mode with the headings collapsed you can go to each one and press TAB to expand it.
Is there an easy way to not have to navigate to headings by using the arrow keys?
# Answer
The obvious response is that you can bound `org-next-visible-heading` and `org-previous-visible-heading` with whatever key you like, but arrow keys are busy ones in the org keymap.
Supossing that you want to completely override up and down keys when org-mode is your major mode, this, in your init file, will do it.
```
(define-key org-mode-keymap (kbd "<down>") 'org-next-visible-heading)
(define-key org-mode-keymap (kbd "<up>") 'org-previous-visible-heading)
```
> 1 votes
# Answer
Use `C-c C-j` (org-goto) for that functionality.
> 0 votes
---
Tags: org-mode
---
|
thread-53208
|
https://emacs.stackexchange.com/questions/53208
|
Show headings only in sparse tree
|
2019-10-17T21:02:23.023
|
# Question
Title: Show headings only in sparse tree
I am generating a sparse tree typically using a regex (, / r ). What I am trying to do is get an overview of where in my document a match occurs, not the exact positions of the matches. So, if I have a heading with several kilobytes of plain text underneath that contains a match, I don't want my sparse tree to show the plain text, only the relevant heading.
So, given a doc:
```
* H1
** H2.1
Foo
etc
** H2.2
Bar
** H2.3
Foo
etc
etc
```
And a sparse tree generated for regex foo, I would want to see something like
```
* H1
** H2.1
...
** H2.3
```
# Answer
Looks like **`outline-hide-body`** does exactly what you want:
```
Hide all body lines in buffer, leaving all headings visible.
Note that this does not hide the lines preceding the first heading line.
```
So after creating the sparse tree use `M-x outline-hide-body RET`.
Or create a custom command that calls `org-occur` and hides the body lines afterwards:
```
(defun my-org-occur-and-hide-content ()
"Interactively call `org-occur' and hide body lines after."
(interactive)
(call-interactively #'org-occur)
(outline-hide-body))
```
Call it with `M-x my-org-occur-and-hide-content RET`.
Result with the example from the question:
> 1 votes
---
Tags: org-mode
---
|
thread-53260
|
https://emacs.stackexchange.com/questions/53260
|
Move specified lines down with C-(N) C-n
|
2019-10-21T12:59:01.807
|
# Question
Title: Move specified lines down with C-(N) C-n
I could move next 4 lines with `C-u C-n`,
Additionally, try to move next 6 lines with `C-6 C-n`, but it did only one line down in effect.
What's wrong with my usage?
# Answer
Thanks -- I didn't know that `C-[digit]` ran **digit-argument**. I always believed the numeric parameter comes after the `C-u`, thus the command would be `C-u 6 C-n`. For myself, I prefer `Meta-6 C-n`. The suggestions by @Drew are good ones: see what `C-h k C-6` pulls up, then search through your .emacs.el file.
> 1 votes
---
Tags: motion
---
|
thread-53266
|
https://emacs.stackexchange.com/questions/53266
|
Why does emacs on a remote computing cluster behave differently depending on how the cluster is accessed?
|
2019-10-21T17:21:47.853
|
# Question
Title: Why does emacs on a remote computing cluster behave differently depending on how the cluster is accessed?
I use SSH to work on a Linux computer cluster, emacs is my preferred text editor there.
My local computer is a Windows 10 machine. If I use PuTTY to access the cluster remotely, when I run emacs, it behaves as I'm used to it behaving on a cluster: it starts immediately, and CTRL+- lets you undo things.
I also have a Windows Subsystem for Linux (WSL) version of Ubuntu installed on the same machine, 18.04 LTS. When I SSH into the same cluster and open emacs, it behaves differently: it takes about 4 seconds to start up, and CTRL+SHIFT+- lets you undo things.
It was my impression that when I'm running emacs on a remote system, it is the remote system's emacs executable that runs, and it configures itself with various files also from the remote computer, not from my local machine. But clearly some of my local settings are bleeding over into the remote emacs, since it runs differently depending on whether I access the cluster via PuTTY or SSH-via-Linux-subsystem.
Any advice on what it is on my local machine that affects the remote running of emacs?
Whatever it is, I don't think that it is specific to the cluster, since this behavior is repeatable on two different clusters (emacs 23.1.1, Linux 2.6.32-696.20.1.el6.x86\_64; the other emacs 24.3.1, Linux 3.10.0-514.16.1.el7.x86\_64) and on the Google Cloud Platform (emacs 24.3.1, Linux 3.10.0-957.27.2.el7.x86\_64). The behavior is the same whether or not emacs is installed on the local WSL kernel. Presumably it's still something to do with WSL, though, but I don't know enough about how emacs works to be able to troubleshoot at that end. So any help about what to look for would be greatly appreciated.
# Answer
W.r.t the 4s delay, you should probably look at the $TERM env-var (e.g. with `echo "$TERM"` run from the same shell from which you start `emacs`) and then try and look at the corresponding `terminal-init-<termname>` function. My crystal ball suggests the delay is linked to `xterm-extra-capabilities`.
Regarding the difference in key-binding, the difference is presumably due to the terminal emulators used, again: use `C-h l` to see what sequence of characters it receives from the terminal emulator. You'll likely see that Emacs doesn't receive the same char sequence when you hit the `C--` key in PuTTY as when you hit it into the terminal emulator used for WSL.
> 1 votes
---
Tags: remote, wsl
---
|
thread-53265
|
https://emacs.stackexchange.com/questions/53265
|
Scilab-mode syntax highlighting
|
2019-10-21T17:17:49.937
|
# Question
Title: Scilab-mode syntax highlighting
I'm trying to install (and run) `scilab-mode`, but the syntax highlighting does not work when I open `.sci` or `.sce` file.
I use the exact configuration described in the scilab.el package.
https://www.emacswiki.org/emacs/scilab.el
Any help?
# Answer
The help page clearly says that this is an old script which does not work with the current version of Emacs without adapting it. It's really a shame and I would also be interested, but this elisp script is simply orphaned.
> 0 votes
---
Tags: syntax-highlighting
---
|
thread-53274
|
https://emacs.stackexchange.com/questions/53274
|
Add a group of options in a Magit transient
|
2019-10-22T12:19:08.467
|
# Question
Title: Add a group of options in a Magit transient
I would like to add a group of options to a transient, but I cannot figure out the `POS` parameter I should use.
```
(transient-append-suffix 'magit-push "-n" ;; after the last option of the first group
["My group"
'("-M" "My option" "--my-option")
])
```
does not work, it throws this error: "Cannot place \["My group"\] into magit-push at -n; suffixes and groups cannot be siblings".
```
(transient-append-suffix 'magit-push '(0) ;; after the first group
["My group"
'("-M" "My option" "--my-option")
])
```
does not throw any error, but when I try to open the push transient, I have this error: "No key for quote".
What is the correct way to add my custom group after the first group?
# Answer
> 6 votes
I found the issue, the infixes in the group should not be quoted:
```
(transient-append-suffix 'magit-push '(0) ;; after the first group
["My group"
("-M" "My option" "--my-option")
])
```
---
Tags: magit
---
|
thread-30196
|
https://emacs.stackexchange.com/questions/30196
|
How to search in multiple files with Emacs without grep?
|
2017-01-25T10:15:18.930
|
# Question
Title: How to search in multiple files with Emacs without grep?
There is a folder with many sub-folders, files and I would like to search for a given piece of text in all of these files with Emacs on a Windows 10 machine. (I know about M-x grep, but it does not work in Windows environment.)
Is there any way to start such recursive search from within Emacs on Windows 10 without installing additional software or extensions?
(The question marked as a "possible duplicate" is different. My question is about searching in files' contents. The another question is about searching for files.)
# Answer
> 8 votes
The Elisp package `elgrep` is a swiss army knife for searching files. It is available on melpa. There are no dependencies on external tools as long as you do not search the contents of pdf documents.
Only an excerpt of the features:
* By default you can do a simple regexp search in the files of the specified directory.
* You can recurse into subdirectories. The minimal and maximal recursion depth can be set.
* You can specify a regexp for the names of the files that should be searched.
* You can specify a regexp for the names of the files that should be excluded from the search.
* You can split files into records by regular expressions. By default the full file is one record. You can also use Elisp functions for finding the beginning and/or end of a record.
* You can specify multiple search expressions as preconditions that must be present in the record to generate matches for the first regular expression.
Preconditions can be negated by a leading `!`. A negated precondition must not occur in the record to be selected for output.
* The search function can be changed. E.g., with `cexp-search-forward` from the library `cexp` you easily get a powerfull BibTeX database query.
* You can display the search results with specified context.
Example: The buffer is narrowed to a record when that record is searched. So you can specify `elgrep/point-min` and `elgrep/point-max` as context boundaries to display the full record if it matches.
By default only the line with the match is shown.
* You can edit the search results and write the edited stuff back to the corresponding files if the files are editable in Emacs.
* Search queries are automatically saved. They are preserved in the `elgrep-call-list` if you name them. This list is saved to disk at exiting Emacs and reloaded when `elgrep` is loaded.
Example of the buffer with the search results:
The Elgrep menu settings that returned these search results (only a few are modified):
# Answer
> 7 votes
You can use Windows' builtin `findstr` command with `M-x rgrep`:
```
(when (eq system-type 'windows-nt)
(with-eval-after-load 'grep
;; findstr can handle the basic find|grep use case
(grep-apply-setting 'grep-find-template
"findstr /S /N /D:. /C:<R> <F>")
(setq find-name-arg nil)))
```
It's not as versatile as `grep`, but it's fine for searching for fixed strings. Also note that Emacs sometimes suggests globs like `*.[ch]` but you need to use `*.c *.h` instead (use `C-q SPC` to enter the space).
# Answer
> 7 votes
you can try the xah-find package. https://github.com/xahlee/xah-find
it is pure elisp, and designed just for emacs without external grep tools.
# Answer
> 2 votes
You could try Emacs Helm which is available to install from MELPA Stable. The `Helm` framework allows you to easily and intuitively work with files, directories and buffers. Moreover, it provide simple access to common Helm commands such as `grep`, `find`, `locate`, etc...
---
Tags: search
---
|
thread-53278
|
https://emacs.stackexchange.com/questions/53278
|
Commands with Keybindings only
|
2019-10-22T12:38:52.633
|
# Question
Title: Commands with Keybindings only
When I run `helm-M-x` and enter characters, I like to see only those commands which has key-bindings. How I can achieve that? I like to have reverse functionality as well, ie.. commands without key-bindings.
# Answer
> 2 votes
You can use the following command which is independent of the used completion framework because it uses `completing-read`:
```
(defun execute-binding+ (arg)
"Completing read a command and execute it.
With ARG non-nil only present commands without a key binding
otherwise only those which have one."
(interactive "P")
(let ((cmd (completing-read
"Command: "
obarray
(lambda (sym)
(and (commandp sym)
(let ((key (where-is-internal sym nil t)))
(if arg (not key) key)))))))
(when cmd
(setq cmd (intern cmd))
(setq this-command cmd)
(setq real-this-command cmd)
(command-execute cmd 'record))))
```
As requested here is a version which shows the key bindings inline:
```
(defun execute-binding+ (arg)
"Completing read a command and execute it.
With ARG non-nil only present commands without a key binding
otherwise only those which have one."
(interactive "P")
(let ((coll nil))
(mapatoms (lambda (sym)
(when (commandp sym)
(let ((key (where-is-internal sym nil t)))
(cond ((and arg (not key))
(push sym coll))
((and (not arg) key)
(push (format "%s (%s)" sym
(key-description key))
coll)))))))
(let ((cmd (completing-read "Command: " coll)))
(setq cmd (intern (car (split-string cmd))))
(setq this-command cmd)
(setq real-this-command cmd)
(command-execute cmd 'record))))
```
---
Tags: key-bindings, helm, m-x
---
|
thread-53277
|
https://emacs.stackexchange.com/questions/53277
|
How to export to PDF with blocks that respect indentation AND subscripts?
|
2019-10-22T12:35:59.777
|
# Question
Title: How to export to PDF with blocks that respect indentation AND subscripts?
How can I export so that both subscripts and indentation are respected? For example, using QUOTE will respect special characters like subscripts, but will ignore spacing. The opposite is true of EXAMPLE or SRC blocks.
```
#+BEGIN_QUOTE
let x_m be the constraints over x_n variables
set all x_n = false
for x_i \in right-hand sides of x_m while equation X is FALSE:\\
x_i = true\\
if X is true, return TRUE\\
return FALSE
#+END_QUOTE
```
# Answer
Export to pdf is handled by LaTeX, and `org-mode` only manages a small subset of the possible options. `EXAMPLE` blocks are exported as `verbatim` environments, which will change none of your text - it respects all your whitespace, but will not process any macros (such as your subscripts).
On the other hand, `quote` blocks are exported as `quote` environments. These do process macros, but impose LaTeX spacing algorithms.
There is no halfway. If you were writing in pure LaTeX, you would have all kinds of options. `org-mode` doesn't support them, but you can include raw LaTeX in your org-mode file, and it will be respected during export (as long as it's not in an `example` block). This being the case, you can insert a bit of LaTeX to get what you want. A relatively simple approach would be:
```
#+BEGIN_QUOTE
let x_m be the constraints over x_n variables
set all x_n = false
for x_i \in right-hand sides of x_m while equation X is FALSE:\\
\hspace*{2em} x_i = true\\
\hspace*{2em} if X is true, return TRUE\\
return FALSE
#+END_QUOTE
```
The output looks fine, but it's a bit ugly in your org mode file.
> 1 votes
---
Tags: org-mode, org-export
---
|
thread-17635
|
https://emacs.stackexchange.com/questions/17635
|
a function to grep specified files?
|
2015-10-25T06:31:08.980
|
# Question
Title: a function to grep specified files?
My Emacs customizations reside in a few separate .org files, all in the directory `~/emacs-prelude/personal`. I'm always searching these files to find and change settings.
How can I define a function `search-my-emacs-configutation-files` to search the full text of these files?
It seems like the most obvious way would be to do a `helm-projectile-grep`, but Projectile seems to think the "project" is the entire Emacs-Prelude directory (including all my packages) when in fact I want to search only the subdirectory Personal which has my customizations.
`helm-cmd-t` seemed promising but it seems like it searches only filenames.
`helm-do-grep` works, but it asks me for the directory each time. I'd like to be able to call this function using a single keystroke.
# Answer
> 3 votes
There are many ways to do what you need, here is one by using helm's `helm-do-grep-1`.
```
(defun search-my-emacs-configutation-files ()
(helm-do-grep-1 '("~/emacs-prelude/personal/*.org")))
```
If you even have `.org` files under some sub-directories under `~/emacs-prelude/personal/`:
```
(defun search-my-emacs-configutation-files ()
(helm-do-grep-1 '("~/emacs-prelude/personal") :recurse nil '("*.org")))
```
---
From `C-h f helm-do-grep-1`:
> (helm-do-grep-1 TARGETS &optional RECURSE ZGREP EXTS DEFAULT-INPUT INPUT)
The 1st argument TARGETS is a list of files (including directories).
# Answer
> 3 votes
The package elgrep is a quite powerful search tool. I just listed the features in an answer to a similar question.
Recursive search for occurences of regexp matches in specified files is only one of its simplest applications.
After installation from melpa you get a comfortable settings dialog window using the menu bar:
`Tools``Search Files (Elgrep)`.
The following settings are sufficient to search the org files in directory `~/KB/Soft/Emacs/elgrepTest/` and its subdirectories for the regexp `\(one\|second\|third\) section`:
Expression: Regexp: `\(one\|second\|third\) section`
Directory: `~/KB/Soft/Emacs/elgrepTest/`
File Name Regular Expression: `\.org\'`
Recurse into subdirectories `[X]`
A picture of the buffer with the search results:
The nice thing that fits perfectly your usecase is that Elgrep lists the calls run over the menu in an `elgrep-call-list` that is part of the `*elgrep-menu*` buffer:
You can copy the `Form` entry, paste it into a command and adapt it to your needs.
```
(defun my-elgrep-call (regexp)
"Just run Elgrep for my config files."
(interactive (list (read-regexp "Search my config files for: ")))
(elgrep/i "~/KB/Soft/Emacs/elgrepTest/" "\\.org\\'" regexp :recursive t))
```
Alternatively you can also name the call list entry, e.g. with `Search Config` and reuse it whenever you want. The call list entries are stored on disk when you leave Emacs and recovered at the start of the next session.
When you want to search your config files next time just press the `[Set]` button of the call list entry `Search Config`. The settings of the call list entry are adopted in the menu. Then you can change the regexp and press `[Start Elgrep]`.
Naming the call list entry is important since the first call list entry is overwritten by the next Elgrep call if it is unnamed. This way the user decides which call list entries to keep.
The previous search is quite booring. Let us try somewhat more interesting.
Assume you have the convention that each Elisp Org source block that contains a function definition should also containe some informative message. You want to check whether there are some source blocks that contain a function definition but no message call. Thereby, stuff commented out or appearing in strings is irrelevant.
The following Elgrep settings define a search for *records* in Org files that contain matches for the regexp `(defun` and no matches for the regexp `(message`. The `!` before `(message` in the input field negates the match.
The *records* are delimited by matches for regular expression that mark the beginning and the end of Elisp source code blocks.
The *context* is chosen such that the full records are printed in the `*elgrep*` buffer with the search results.
The search function is chosen such that it only accepts matches in Elisp code and not in comments or strings. Therefore, we search with the `emacs-lisp-syntax-table` active.
Expression: List of regexps:
\[INS\] \[DEL\] Regexp: `(defun`
\[INS\] \[DEL\] Regexp: `!(message`
\[INS\]
Directory: `~/KB/Soft/Emacs/elgrepTest`
File Name Regular Expression: `\.org\'`
Recurse into subdirectories `[X]`
Beginning of Record: Regexp: `^[[:space:]]*#\+begin_src[[:space:]]+emacs-lisp`
End of Record: Regexp: `^[[:space:]]*#\+end_src\>`
Context Lines Before The Match: Regexp: `\``
Context Lines After The Match: Regexp: `\'`
Search function: `(lambda (&rest args) (with-syntax-table emacs-lisp-mode-syntax-table (apply #'elgrep/re-search-code args)))`
When you click on `[Start Elgrep]` Elgrep executes the search, shows the results, and presents your settings as command in the call list:
```
(elgrep/i "/mnt/c/Users/Tobias.Zawada/Weiterbildung/Soft/Emacs/elgrepTest" "\\.org\\'"
("(defun" "!(message")
:recursive t :r-beg "^[[:space:]]*#\\+begin_src[[:space:]]+emacs-lisp" :r-end "^[[:space:]]*#\\+end_src\\>" :c-beg "\\`" :c-end "\\'" :search-fun
(lambda
(&rest args)
(with-syntax-table emacs-lisp-mode-syntax-table
(apply #'elgrep/re-search-code args))))
```
You can copy that entry and use it in your self-made Elisp command. But, there is actually little need to define your own command since you can re-use the call list entry in the elgrep menu.
---
Tags: helm, projectile, rgrep
---
|
thread-52782
|
https://emacs.stackexchange.com/questions/52782
|
Unusual behavior when overriding `calculate-lisp-indent'
|
2019-09-22T14:58:44.340
|
# Question
Title: Unusual behavior when overriding `calculate-lisp-indent'
I've modified `calculate-lisp-indent` as a better solution to the indentation questions here, here and here. By "modified" I mean I overrode the function with advice. After doing this when I restarted emacs and I tried to indent a lisp form, I'd get the error `void-variable calculate-lisp-indent-last-sexp`.
Here's where things get interesting. You may be inclined to think that's it's some problem with the code I added to `calculate-lisp-indent`. But after failing to figuring out what was wrong with the code I added (which by the way didn't even mention `calculate-lisp-indent`), I tried overriding `calculate-lisp-indent` with a function that has the exact same body as `calculate-lisp-indent`. What happened then? I got the same error. Wierd.
Ok, now I started looking at the code for `lisp-indent-function` and I could not find where the variable `calculate-lisp-indent-last-sexp` was set. It looked as if it was just unbound.
Check out the beginning of the `lisp-indent-function`. `calculate-lisp-indent-last-sexp` was used but not defined.
```
(let ((normal-indent (current-column))
(orig-point (point)))
(goto-char (1+ (elt state 1)))
(parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
...
```
A small digression: go to say I'm not sure why `parse-partial-sexp` is doing here. Based on it's documentation I thought it just returned the list, but I don't see the value it's returning being stored anywhere. Does it have any (undocumented) side-effects?
So my first though was `calculate-lisp-indent-last-sexp` must be a global variable. But when I tried to describe it with `describe-variable` I couldn't find it.
Also super interesting. I noticed that after restarting emacs and getting the void variable error, if I re-evaluated the function I wrote to override `calculate-lisp-indent` then I don't get errors and my changes to `calculate-lisp-indent` take effect as I would expect.
```
;; If I re-evaluate this, then the indentation works and I get no errors.
(defun void~calculate-lisp-indent (&optional parse-start)
"Has same body as `calculate-lisp-indent`."
...)
```
What is going on here?
EDIT: After starting emacs with the advice I performed a few checks.
```
(foundp #'void~calculate-lisp-indent) ; => t
(advice-member-p #'void~calculate-lisp-indent #'calculate-lisp-indent) ; => a non-nil value
```
This confirms the advice is a defined function and that it is advising `calculate-lisp-indent`. I don't understand why re-evaluating it makes a difference.
# Answer
I am currently discussing a potential patch for as an answer to this question.
The code that answers my original question looks like this:
```
(if (or
(= (point) calculate-lisp-indent-last-sexp)
(eq (char-after (1+ containing-sexp)) ?:)
(eq (char-before containing-sexp) ?')
(let ((quoted-p nil)
(point nil)
(positions (nreverse (butlast (elt state 9)))))
(save-excursion
(while (and positions (not quoted-p))
(setq point (pop positions))
(setq quoted-p
(or (eq (char-before point) ?')
(goto-char (1+ point))
(looking-at-p "[[:space:]\n]*quote\\_>")))))
quoted-p))
;; Containing sexp has nothing before this line
;; except the first element. Indent under that element.
nil
;; Skip the first element, find start of second (the first
;; argument of the function call) and indent under.
(progn (forward-sexp 1)
(parse-partial-sexp (point)
calculate-lisp-indent-last-sexp
0 t)))
```
This patch should be put in the body of `calculate-lisp-indent` (I don't show it in the body here for brevity). It should go where I denote `<<CODE GOES HERE>>`.
```
(defun calculate-lisp-indent ()
...
(cond ((looking-at "\\s(")
;; First element of containing sexp is a list.
;; Indent under that list.
)
((> (save-excursion (forward-line 1) (point))
calculate-lisp-indent-last-sexp)
;; This is the first line to start within the containing sexp.
;; It's almost certainly a function call.
<<CODE GOES HERE>>>
(backward-prefix-chars))
(t ...))
...)
```
Here is a demonstration of how this patch works:
```
;; Quoted list
'(hello hi ho
ho hi)
;; Backquote is not touched
`(hello hi
ho)
;; Nested quoted list
'((hello hi ho
hello))
;; Explicitly quoted list
(quote (a b c
d e f))
```
I will try to update this post in case some detail of this patch changes. You can also see this link to see my progress on this patch.
> 0 votes
# Answer
Maybe this will help with part of your question. It seems to be a multi-part question, i.e., multiple questions (it's generally better to ask one question at a time).
1. `C-h f calculate-list-indent` tells you the function is defined in `lisp-mode.el`. Clicking on `lisp-mode.el` in `*Help*` visits that library.
2. Searching for `calculate-lisp-indent-last-sexp` in `lisp-mode.el` shows that it is declared as a global/special variable, i.e., a variable that is scoped dynamically. That declaration is not a definition - there is no default value assigned, and there is no doc string.
```
(defvar calculate-lisp-indent-last-sexp)
```
3. That explains why `describe-variable` describes it only to the extent of saying that its value is void. The help function doesn't try to say where it was declared (it could be declared in any number of places), and it doesn't show any doc for it because there is none.
4. Searching further for that variable shows that it is **bound** in function `calculate-lisp-indent`.
```
(let ((indent-point (point))
state
;; setting this to a number inhibits calling hook
(desired-indent nil)
(retry t)
calculate-lisp-indent-last-sexp containing-sexp)
...)
```
5. When a dynamically scoped variable is bound with `let` it is bound for the *duration* of the calling code (the `let`). It is not bound *lexically* by the `let`. This means that it remains bound for the *duration* of any code invoked in the `let` body. That includes the invocation of `lisp-indent-function`: `(funcall lisp-indent-function indent-point state)`.
> 0 votes
---
Tags: indentation, variables, advice, dynamic-scoping, nadvice
---
|
thread-41346
|
https://emacs.stackexchange.com/questions/41346
|
My left pinky hurts. Can I press another key to act as Control?
|
2018-05-05T12:36:39.200
|
# Question
Title: My left pinky hurts. Can I press another key to act as Control?
My left pinky hurts due to repetitively pressing the `C` button when using Emacs org mode. Not working with Emacs is out of the question, but it needs some rest.
I would like to change the`C` key for something else for a while. Could I use, say, the ',' button instead?
# Answer
> 8 votes
Emacs pinky is a common issue, there are severals way to deal with it:
1. swap Control key to something else (usually Caps Lock).
2. Use your palm instead of pinky to press Control key.
3. Use an ergonomic keyboard.
You can check emacs wiki to see how other users do. https://www.emacswiki.org/emacs/RepeatedStrainInjury
# Answer
> 4 votes
You can define a key that applies a modifier to the next key in Emacs.
```
(define-key function-key-map "," 'event-apply-control-modifier)
(global-unset-key ",")
(defun insert-comma (count)
(interactive "*p")
(insert-char ?, count))
(global-set-key [(control ?,)] 'insert-comma)
(global-unset-key "\e,")
(global-set-key [(control meta ?,)] 'tags-loop-continue)
```
Then pressing `,` then `a` is equivalent to pressing `Ctrl`+`a`. Press `,` twice to insert a comma.
There are limitations. Ctrl+Shift bindings work if you press `,` then `Shift`+`*key*`, but for meta you can't press `Esc` then `,` then `*key*`. If a mode defines its own binding for `,` or `Ctrl`+`,` or `Meta`+`,` then it will override the comma-as-a-modifier bindings. Inserting a comma is no longer a self-insert, which has a few consequences (the same as making a character electric) such as breaking undo sequences, not necessarily doing what you'd expect from a self-insert to the selection, etc.
I don't think there's a way to apply this to a specific mode. You can apply it to a specific terminal (but not to a specific window on a GUI) with `local-function-key-map` but I don't know if that would help you.
See also the Emacs wiki page on sticky modifiers. That doesn't do exactly what you're asking, but one of the features on this page may be an acceptable solution for you.
# Answer
> 1 votes
After using emacs for almost 10 years, I think the best way to avoid emacs pinky is to remember:
**Bind the keys such that you never press two or more keys at the same time with one hand!**
This completely eliminates any hand problems I used to have.
For example, C-x should always be pressed like this: C (right hand) - x(left hand)
Using space or caplock to replace control will delay but not completely prevent your hand problems. The only way to prevent them is to never press two keys at the same time with one hand.
# Answer
> 0 votes
Use the CTRL Key! My professor showed me this in college and I have been using this kbd mapping ever since on any system I use.
* MacOS - built in kbd mapping
* Linux - setxkbmap, or on Ubuntu systems modify /etc/default/keyboard and add "ctrl:nocaps" to keyboard options. (XKBOPTIONS="ctrl:nocaps") or (XKBOPTIONS="ctrl:swapcaps") to swap caps and ctrl. The former will give you ctrl as ctrl and caps as ctrl. This is better than tweak tool because you'll get caps as ctrl in tty's as well.
* Windows - Sharpkeys
Excellent Link: EmacsWiki: Moving the CTRL Key
# Answer
> 0 votes
I just realized that I have used the Ring Finger to press the Ctrl key and that has worked all these years of emacs experience. Hopefully that could mean a new beginning for you.
# Answer
> 0 votes
This problem is actually solved in year 2012 when EVIL is mature.
**Simple solution,**
Please use Spacemacs+Evil. Vim key bindings make sure you type less keys when dealing with text. Use space as leader key so you don't need move finger from its default position too frequently.
In other words, if you don't use key like Ctrl/Alt/Shift/Win/Cmd/Esc, you solve the problem from root cause.
**Advanced solution,**
Please use Evil. Then measure your frequency of key pressing by using package `keyfreq`.
See http://blog.binchen.org/posts/how-to-be-extremely-efficient-in-emacs.html for tech details.
If you want to start optimization immediately without using `keyfreq`, here is my one year data you can use,
https://gist.github.com/redguardtoo/99e69fe3ecfccadeacdb6f1c40978b0c
This solution works on any environment. It also immediately speedup you productivity so you can code much faster. In summary, there is NO side effect at all.
BTW, at the beginning, you only need optimize top 20 commands.
```
6008 13.33% evilmi-jump-items %, <visual-state> %, <normal-state> %
4292 9.53% winum-select-window-2 , 2, M-2
3806 8.45% winum-select-window-1 , 1, M-1
2522 5.60% switch-to-shell-or-ansi-term , x z, C-x C-z
2280 5.06% my-counsel-recentf , r r
1910 4.24% my-multi-purpose-grep , q q
1791 3.98% back-to-previous-buffer , b b
1561 3.46% winum-select-window-3 , 3, M-3
1379 3.06% counsel-etags-find-tag-at-point C-]
1222 2.71% eval-expression , e e, M-:, M-ESC :
1153 2.56% evil-visualstar/begin-search-forward <visual-state> *
971 2.16% my-evil-goto-definition g t
793 1.76% copy-to-x-clipboard , a a
654 1.45% pop-tag-mark C-t
633 1.40% counsel-imenu , i i
616 1.37% paste-from-x-clipboard , z z
539 1.20% winum-select-window-4 , 4, M-4
522 1.16% toggle-full-window , f f
420 0.93% evil-toggle-input-method C-\
371 0.82% git-add-current-file , v a
322 0.71% evilnc-comment-or-uncomment-lines , c i, M-;
302 0.67% backward-delete-char-untabify
295 0.65% my-split-window-vertically , x 2, C-x 2
285 0.63% find-file-in-project-by-selected , k k
279 0.62% delete-other-windows , x 1, , s 1, C-w C-o, C-w o, C-x 1, <menu-bar> <file> <one-window>
278 0.62% langtool-goto-next-error , l l
273 0.61% find-function , h f, C-h C-f, <f1> C-f, <help> C-f
270 0.60% kill-buffer , x k, C-x k
261 0.58% my-split-window-horizontally , x 3, C-x 3
251 0.56% narrow-or-widen-dwim , w w
235 0.52% counsel-find-file , x f
224 0.50% winner-undo , u u, C-c <left>, C-x 4 u
203 0.45% beginning-of-defun , b f, <C-M-home>, C-M-a, ESC <C-home>
202 0.45% c-electric-backspace
201 0.45% evil-a-paren
190 0.42% counsel-describe-variable C-h v, <f1> v, <help> v
187 0.42% org-shifttab
187 0.42% wg-create-workgroup SPC s s
186 0.41% evil-surround-region <visual-state> S
155 0.34% ffip-diff-find-file
154 0.34% flyspell-goto-next-error , f e
153 0.34% counsel-etags-find-tag , f t
152 0.34% ivy-switch-buffer-by-pinyin , x b
```
# Answer
> 0 votes
Left `alt` (i.e., `meta` key in Emacs config) key can be pressed easily using your left thumb, and you can rebind all of your common functions (e.g., cursor movements) to meta-key-based shortcuts instead of the original ctrl-key-based shortcuts. I do that in my init.el file.
---
Tags: key-bindings
---
|
thread-53271
|
https://emacs.stackexchange.com/questions/53271
|
Problem with emacs and sagemath unicode
|
2019-10-22T10:34:19.787
|
# Question
Title: Problem with emacs and sagemath unicode
I am using Emacs (GNU Emacs 24.5.1, which is admittedly old, but the problem also exists on a newer (25 something) Emacs on a different machine) and sage-shell-mode to work with the computer algebra system SageMath.
Unfortunately, Unicode output is garbled.
Here is a picture of how output looks:
and here is a picture of how it should look:
I do not know what other information might be useful. `buffer-file-coding-system` is `utf-8-unix`
# Answer
It turns out that the problem is simply the font. The font "Noto Mono Regular" is beautiful, but is not monospace, whereas "monospace regular" seems to work correctly.
> 1 votes
---
Tags: unicode
---
|
thread-53291
|
https://emacs.stackexchange.com/questions/53291
|
Complex searching and replacing
|
2019-10-23T07:31:53.287
|
# Question
Title: Complex searching and replacing
Suppose I have following pattern:
```
throw "some message";
```
which I'd like to replace with:
```
throw new Error("some message");
```
So, "some message" part should not be changed (or copied as is), and everything around it should be changed with arbitrary strings.
Is there any way to do that in Emacs?
# Answer
> 2 votes
You can use `M-x` `replace-regexp` or `M-x` `query-replace-regexp`. e.g.:
`C-M-%` `throw \(".*?"\);` `RET` `throw new Error(\1);` `RET`
If `"some message"` might contain escaped double-quotes like `"whoops, \"foo\" happened"` then the pattern needs to be more complex; something more like:
```
throw \(""\|".*?[^\]"\);
```
And if there might be embedded newlines as well, `.` doesn't match those, so you would need:
```
throw \(""\|"\(?:.\|<NEWLINE>\)*?[^\]"\);
```
Where in place of `<NEWLINE>` you would need to insert a literal newline character via `quoted-insert` by typing `C-q``C-j`
To learn more about this, start reading here:
`C-h``i``g` `(emacs)Regexps` `RET`
# Answer
> 2 votes
What you need to use is regexp groups. In short, if you put something inside parenthesis in your regexp, you can reuse what's inside the parenthesis when replacing by using \1 (or \n if you have multiple groups). In your case, it would be `throw "\(.*\)"` -\> `throw new Error("\1")`. The package pcre2el makes it easier to work with regexp groups, you can also check visual regexp steroid if you want to visualize your regexp.
# Answer
> 2 votes
The following example of stupid but valid C++ code shows that automatic replacement of `throw EXPRESSION;` by `throw new Error(EXPRESSION);` is not possible in a roboust way without exploiting lexical information from the buffer.
The comments in the source code indicate the problems.
```
#include <string>
int main() {
try {
throw /* some comment */
"some message";
} catch(char* s) {
throw; // re-throw: must not be replaced
}
throw std::string("one ") + std::string("two"); // expression
std::string str = "Please \"throw\" the ball;"; /* stuff after throw must not be replaced */
/* Here we throw in some comment. */ // must not be replaced
throw "first" /* " second"; */ " third";
throw "";
int i = 1;
int j = ( i < 1 ? ( throw "Wrong number ", 0 ) : 2 );
return 0;
}
/*
Local Variables:
compile-command: "g++ /temp/test.cc"
tab-indent-mode: nil
End:
*/
```
The following commented source code handles all those problems. It handles at least in this simple example all occurences of `throw` correctly.
```
(defvar my-replace-throw-expr-delimiter-re "[;,)]")
(defun my-replace-throw ()
"Replace
throw EXPRESSION;
by
throw new Error(EXPRESSION);"
(interactive)
(goto-char (point-min))
(let (beg end)
(while
(progn
(while (and (setq beg (re-search-forward "\\_<throw\\_>" nil 'noErr))
(or (nth 8 (syntax-ppss)) ;; "throw" is part of comment or string
(progn
(forward-comment most-positive-fixnum) ;; skip all comments and whitespace
(looking-at-p my-replace-throw-expr-delimiter-re))))) ;; not a re-throw
beg)
;; we found a throw with syntactically relevant argument
;; now we collect all the sexps that belong to the argument
(setq beg (point))
(while
(progn
(forward-sexp)
(forward-comment most-positive-fixnum) ;; skip all comments and whitespace
(null (looking-at-p my-replace-throw-expr-delimiter-re)))) ;; until we find the end of the throw argument
(cl-assert (looking-at-p my-replace-throw-expr-delimiter-re) nil
"Expected end of expression.")
(let ((str (buffer-substring beg (point))))
(delete-region beg (point))
(insert
(format "new Error(%s)" str))))))
```
Calling `M-x` \`my-replace-throw\` `RET` on the above C++ code gives the following result:
```
#include <string>
int main() {
try {
throw /* some comment */
new Error("some message");
} catch(char* s) {
throw; // re-throw: must not be replaced
}
throw new Error(std::string("one ") + std::string("two")); // expression
std::string str = "Please \"throw\" the ball;"; /* stuff after throw must not be replaced */
/* Here we throw in some comment. */ // must not be replaced
throw new Error("first" /* " second"; */ " third");
throw new Error("");
int i = 1;
int j = ( i < 1 ? ( throw new Error("Wrong number "), 0 ) : 2 );
return 0;
}
/*
Local Variables:
compile-command: "g++ /temp/test.cc"
tab-indent-mode: nil
End:
*/
```
---
Tags: search, replace
---
|
thread-53290
|
https://emacs.stackexchange.com/questions/53290
|
(Company) Doc Buffer ignoring scroll-other-window
|
2019-10-23T06:23:38.267
|
# Question
Title: (Company) Doc Buffer ignoring scroll-other-window
I'm trying to write my own backend for a certain tool language that has no repl. Hence, I thought it would be the best idea to parse the documentation and store it as a hash table (I'm open to other suggestions, I'm fairly new to Emacs). In general this works fine, the problems arise when the documentation is longer than a display. In this case, I would like to use scroll-other-window like anywhere else to scroll the documentation down, but it immediately jumps back to the top.
This is the basic structure of my backend:
```
(defconst my--constants
(list "asdf"
"bsdf"
"csdf"))
(defconst my--doc-buffer
#s(hash-table
size 3
test equal
data("asdf" "Test."
"bsdf" "Doing\nfine."
"csdf" "T\nh\ni\ns\n \ni\ns\n \nw\nh\ne\nr\ne\n \ni\nt\n \ng\ne\nt\ns\n \nr\ne\na\nl\nl\ny\n \nm\ne\ns\ns\ny\n.\n \nE\nv\ne\nn\n \nw\ni\nt\nh\n \ns\nc\nr\no\nl\nl\n-\no\nt\nh\ne\nr\n-\nw\ni\nn\nd\no\nw\n \ni\nt\n \nj\nu\nm\np\ns\n \nb\na\nc\nk\n.")))
(define-derived-mode my-mode prog-mode "My")
(defun my-completion-at-point ()
(let ((bounds (bounds-of-thing-at-point 'word)))
(when bounds
(list (car bounds)
(cdr bounds)
my--constants
:exclusive 'no
:sorted (lambda (cand) t)
:company-doc-buffer
(lambda (cand)
(company-doc-buffer (gethash cand my--doc-buffer)))))))
(add-hook 'completion-at-point-functions 'my-completion-at-point)
```
When `company-show-doc-buffer` is called upon `csdf`, `scroll-other-window` won't do it's job properly. Instead it immediately jumps back to the head.
Are those `\n` linebreaks the wrong approach? Am I missing something else? Unfortunately I couldn't find any other backends that use doc-buffers in an offline table. Is it actually the way to go, to use a company-doc-buffer, or is there a more generic thing available/recommended?
# Answer
> 1 votes
I finally figured out the culprit: `company-quickhelp-mode` was enabled in my setup which evidently triggered the doc-buffer all the time to reload. After disabling, everything works as expected. I'll try to solve this issue also with `company-quickhelp` and add my results here later.
---
Tags: company-mode, doc-strings
---
|
thread-53295
|
https://emacs.stackexchange.com/questions/53295
|
How to count direct or indirect children in org or outline mode
|
2019-10-23T11:22:28.317
|
# Question
Title: How to count direct or indirect children in org or outline mode
I want to count the number of children in a subtree in org-mode. I am able to count the number of recursive children with `(outline-next-heading)`:
```
(defun outline-count-subheadings (&optional recursive)
"Count the number of subheadings below the current heading."
(interactive)
(let ((sum 0)
(end (save-excursion
(ignore-errors
(outline-end-of-subtree)
(point)))))
(when end
(save-excursion
(outline-next-heading)
(setf sum 1)
(while
(< (point) end)
(progn
;; todo: add conditional for recursive argument
(outline-next-heading)
;;(org-forward-heading-same-level 1 nil) ; this does not terminate
;;(outline-forward-same-level 1) ; this errors with "No following same-level heading"
(setf sum (1+ sum))))))
(message (concat "Number of subheadings (" (if recursive "descendants" "direct children") "): " (format "%d" sum)))))
```
But for direct children `(org-forward-heading-same-level 1 nil)` does not terminate the loop and `(outline-forward-same-level 1)` errors with `No following same-level heading`.
What am I doing wrong?
# Answer
# What you tried
`outline-forward-same-level` when called indefinitely will stop at the last direct child of the containing parent heading (and it will signal an error; `org-forward-heading-same-level` will stop at the same place, but it will *not* signal an error). Specifically, it will stop at the *beginning of the line* of the heading that represents the last direct child. `org-end-of-subree` will return the last point of the subtree, meaning the point at the *end of the contents* of the last direct child or, if the child has no contents, the point at the *end of the line* of the last direct child. This means that whether the last direct child has contents or not, repeated calls to `outline-forward-same-level` will necessarily end *before* the point returned by `org-end-of-subtree`. Keeping this in mind, we can see that your condition `(< (point) end)` will never return false. The reason you're getting two results is that both `outline-forward-same-level` and `org-forward-same-level` will not move point past the end of the subtree, which you need to do to fulfill your condition.
Another way of saying this is that both `outline-forward-same-level` and `org-forward-heading-same-level` will always stop before the end of the subtree, so your loop won't end. Your recursive version works because `outline-next-heading` does not stop, so there will be a point where it goes past the last heading.
# How to fix
To fix this you can is to just stop the loop when you get an error from `outline-forward-same-level`. Alternatively, you can check if point hasn't moved which would involve keeping track of the last point in a variable. I will demonstrate the former because it is the most brainless and straight-forward way.
```
(defun outline-count-direct-children ()
"Return the number of direct children in the current heading.
Note that this function modifies match data."
(interactive)
(save-excursion
(let ((sum 0))
(when (and (org-at-heading-p)
;; Make sure we go from parent to child. And indirectly
;; ensure that we're not on the same heading (meaning that
;; there are no more headings after this one).
(< (org-outline-level)
(progn (outline-next-heading)
(org-outline-level))))
(setf sum 1)
(while (condition-case nil (progn (outline-forward-same-level 1) t) (error nil))
(setf sum (1+ sum))))
sum)))
```
> 3 votes
# Answer
In addition to Aquaactress's great answer, here is a function inspired by that solution, along with some logic that calculates both the number of direct children and overall descendants:
```
(defun org-count-subheadings ()
"Count the number of direct and recursive subheadings below the current heading."
(interactive)
(let ((descendants 0)
(children 0)
(heading-level (1+ (org-outline-level)))
(end (save-excursion
(ignore-errors
(outline-end-of-subtree)
(point)))))
(when end
(save-excursion
(while (and (outline-next-heading)
(< (point) end))
(progn
(setf descendants (1+ descendants))
(when (= heading-level (org-outline-level))
(setf children (1+ children)))))))
(message "%d direct children, %d descendants" children descendants)))
```
> 0 votes
---
Tags: org-mode, outline-mode
---
|
thread-53301
|
https://emacs.stackexchange.com/questions/53301
|
Cannot open remote file with TRAMP
|
2019-10-23T16:22:56.857
|
# Question
Title: Cannot open remote file with TRAMP
I'm trying to connect and edit files on my openwrt box. But every time I tried Emacs shows me a blank buffer.
```
C-x C-f /ssh:user:192.168.200.1:/etc/config/network RET
```
the filesystem on openwrt
```
cat /proc/filesystems
nodev sysfs
nodev rootfs
nodev ramfs
nodev bdev
nodev proc
nodev tmpfs
nodev debugfs
nodev securityfs
nodev sockfs
nodev bpf
nodev pipefs
nodev devpts
squashfs
nodev jffs2
nodev overlay
```
edit: Hi I did a typo on the original question.
I've use this /ssh:user@192.168.200.1:/etc/config/network
same error.
If I use /ssh:root@192.168.200.1:/etc/config/ I get into dired mode but when I select the file again blank buffer.
Doing the same on the terminal outside emacs all works.
# Answer
It is the wrong syntax. Use `/ssh:user@192.168.200.1:/etc/config/network`
> 0 votes
# Answer
### Try switching to different protocol, e.g. `ssh` to `scp`
For example,
`/ssh:username@hostname:/path/`
would become
`/scp:username@hostname:/path/`
> **Tip:** Another advantage of switching from `ssh` to `scp` is improved uploading and downloading times for larger files. However I don’t think you can use `scp` with the `TRAMP` multi-hops feature.
> 0 votes
---
Tags: tramp
---
|
thread-51857
|
https://emacs.stackexchange.com/questions/51857
|
Change the status of task from todo to done after clocking out
|
2019-07-26T06:33:41.357
|
# Question
Title: Change the status of task from todo to done after clocking out
After org-clock-out the current todos, I have to manually change its status from todo to done.
How could automate the process.
If a clocking task was clocked-out, it's status would be changed to done automatically.
# Answer
Customize `org-clock-out-switch-to-state` variable:
> Set task to a special todo state after clocking out. The value should be the state to which the entry should be switched. If the value is a function, it must take one parameter (the current TODO state of the item) and return the state to switch it to.
Also you can run `org-clock-out` with a universal prefix:
> With a universal prefix, prompt for a state to switch the clocked out task to, overriding the existing value of `org-clock-out-switch-to-state`.
> 1 votes
# Answer
I've found that sometimes I wanted to change the TODO status to something different to DONE and I've created a tiny hook to choose the state on clocking out:
```
;; Adjust TODO after clocking out
(add-hook 'org-clock-out-hook
(lambda ()
(org-todo
(upcase
(completing-read "Is the task done, todo, inreview or wont_do: " '("done" "todo" "inreview" "wont_do"))))))
```
As you might see, my statuses are TODO, DONE, INREVIEW and WONTDO (and also INPROGRESS, but it doesn't make sense after clocking out)
The hook triggers on clocking out and ask the user (with autocompletion) to choose among the possible TODO states. To make things easy I change to uppercase so I don't need to press shift and the letters of the states)
I hope it helps
> 0 votes
---
Tags: org-mode
---
|
thread-53287
|
https://emacs.stackexchange.com/questions/53287
|
How do I center the title when exporting org file to HTML
|
2019-10-23T02:58:55.503
|
# Question
Title: How do I center the title when exporting org file to HTML
```
#+TITLE: Hello World
#+AUTHOR: A. U. Thor
#+HTML_HEAD: <link rel="stylesheet" type="text/css" href="style.css"/>
#+HTML_DOCTYPE: html5
```
currently gives me this as output where the title is centered to the left.
# Answer
> 3 votes
In your `style.css` add `.title {text-align: center;}` to center the document title in the exported html file.
Classes used when exporting are documented in the org manual: CSS-Support. Or inspect the generated html file to see what element and class are used. For the document title this will be the following:
```
<h1 class="title">Hello World</h1>
```
---
It's also possible to **modify the CSS style definitions inside the org file directly** as follows:
1. Add a #+HTML\_HEAD\_EXTRA to the top section in your org file. This will be appended to the HTML document’s head:
```
#+HTML_HEAD_EXTRA: <style type="text/css">.title {text-align: center;}</style>
```
2. Use inline html to include raw html:
```
@@html:<style type="text/css">.title {width: 270px;}</style>@@
```
3. Use a html export code block to include raw html:
```
#+begin_export html
<style type="text/css">.title {width: 270px;}</style>
#+end_export
```
---
Tags: html
---
|
thread-53315
|
https://emacs.stackexchange.com/questions/53315
|
Emacs busy while evaluating R in ESS
|
2019-10-24T08:25:53.313
|
# Question
Title: Emacs busy while evaluating R in ESS
When using Emacs with ESS, when I evaluate functions that take longer to complete (reading in larger files or executing SQL queries), the whole Emacs becomes busy (freezes, hangs, crashes - whatever you call it), and I can't continue editing, using the menu etc until the R session is finished. This seems weird to me, because the R process that is busy is (or should be) completely separate from the main Emacs process. Is there any way to simply send the long block of code to R process and watch it execute, while continuing working with Emacs?
# Answer
> 13 votes
While doing due research on this, I stumbled upon a small section in the ESS manual:
> The default value of ess-eval-visibly (t) means that ESS calls block Emacs until they finish. This may be undesirable, especially if commands take long to finish. Users who want input to be displayed and Emacs not to be blocked can set ess-eval-visibly to 'nowait. This sends the input to the iESS buffer but does not wait for the process to finish, ensuring Emacs is not blocked.
This is exactly what I wanted, and evaluating (eventually adding to my emacs.el)
```
(setq ess-eval-visibly 'nowait)
```
does the trick. I was very glad to find it, and thought to post it here in case someone didn't get the exact wording to find this answer in the official ESS manual.
---
Tags: ess, r
---
|
thread-53304
|
https://emacs.stackexchange.com/questions/53304
|
Treat all numbers as floats
|
2019-10-23T18:53:30.840
|
# Question
Title: Treat all numbers as floats
Is there a way to get elisp to automatically treat all numeric variables as floating points without having to repeatedly use the `float` function?
For example to a division function that outputs the "true" quotient is
```
(defun divide ( x y )
(/ (float x) y))
```
But I'd rather not have so many `float` functions floating around (even if, given the name, that's a part of the function's essence ;) ).
# Answer
The following Elisp code demonstrates how you can define your own wrapper macro `with-float/` that treats all explicit occurences of `/` in its body as division of floats.
Division operators that are used in functions called within the body of `with-float/` are the original operators.
```
(defmacro with-float/ (&rest body)
"Evaluate BODY with / for float arguments."
(declare (debug body))
`(cl-macrolet ((/ (x &rest args)
`(,(symbol-function #'/) (float ,x) ,@args)))
,@body))
(defun using-the-old-/ (x y)
(/ x y))
(defun using-float/ (x y)
(with-float/
(/ x y)))
(append
(list (using-float/ 1 2))
(with-float/
(list
(/ 1 2)
(using-the-old-/ 1 2))))
```
The last form (i.e., the `append`) returns `(0.5 0.5 0)`.
> 3 votes
# Answer
For numeric calculation there is a parallel universe within Elisp: Calc.
The division operator `/` within `defmath` works with the floating numbers of Calc.
Nevertheless, the interface of Calc with the Elisp world is a bit complicated. You need to convert floating point numbers to strings. These strings are then converted by Calc to their Calc-internal representation.
This is not a problem if you stay in the `defmath` "environment" for your complicated maths calculations.
```
(defmath mydiv (x y)
"Divide x by y within `defmath'."
(/ x y))
(calc-eval "mydiv(1,2)")
```
The `calc-eval` form returns 0.5.
You can convert a float number `X` to Calc format by `(math-read-number (number-to-string X))` and a Calc float `Y` to an Emacs float by `(read (math-format-value Y))`.
> 3 votes
---
Tags: variables, numbers
---
|
thread-53319
|
https://emacs.stackexchange.com/questions/53319
|
How to disable evil-mode everywhere?
|
2019-10-24T12:34:02.417
|
# Question
Title: How to disable evil-mode everywhere?
I have recently installed emacs doom, and I tried to customise it with some custom keybindings. I have found that Evil is just not something I want. I can disable it on a per-buffer basis with `M-x turn-off-evil-mode`, but I do not want to have to type that command everytime I open a file
How can I disable evil mode everywhere? I don't want it.
PS: The Emacs doom documentation apparently used to explain how to this, but the link points to nowhere
# Answer
More explanations how to remove Evil are in `.emacs.d/modules/editor/evil/README.org` and to quote it:
> You must do two things to remove Evil:
>
> 1. Remove `:editor evil` from `~/.doom.d/init.el`,
> 2. Run *doom refresh* to clean up lingering dependencies and refresh your autoloads files.
> 3. \[OPTIONAL\] You may want to assign new values to `doom-leader-alt-key` and `doom-localleader-alt-key`. These are bound to `C-c` and `C-c l` by default.
Read also all text there, you must make effort to implement Emacs keybinding everywhere.
One word of caution - in time normal Emacs keybindings will induce some pain for your fingers (as for me also) and a normal way to avoid such is to use Evil mode, since `C- ...` commands are replaced by some others keybindings not using your left thumb.
Edit: *doom refresh* was replaced by *doom sync* in newest updates.
> 11 votes
---
Tags: evil
---
|
thread-51542
|
https://emacs.stackexchange.com/questions/51542
|
Running Anaconda Python within emacs on Windows
|
2019-07-11T15:08:37.783
|
# Question
Title: Running Anaconda Python within emacs on Windows
Oct. 2021 update: I am at my wit's end over this. Still Windows 10, official GNU emacs 27.2. Anaconda installed in c:\users\\\[username\]\Anaconda3. No venv's, I just use the base conda environment. Please please tell me what exactly to type in my .emacs file, so that "M-x run-python" starts the anaconda python, properly activates so "import numpy" works. Please! I've flailed around w/ pyvenv.el, conda.el, I give up.
I have a Windows 10 machine, with the official GNU emacs Windows build, and Anaconda Python 3.7.3. I can't get Python to properly run within emacs. Whenever I start Python, I get the message:
```
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Warning:
This Python interpreter is in a conda environment, but the environment has not been activated. Libraries may fail to load. To activate this environment please see https://conda.io/activation
Type "help", "copyright", "credits" or "license" for more information.
```
And numpy, scipy, etc won't load. I have tried several things with the pyvenv and elpy packages, all to no avail. From a DOS prompt, I type 'activate' to activate the conda env. I haven't setup any venv's of my own.
# Answer
Provided that you added the folders paths of your conda install in Windows' %PATH% variable\[\*\], the following should work :
1. `M-x shell`
2. In the shell, run `conda activate base`. This will load the environment and allow you to use the libraries (like numpy).
3. In the same shell, run `python -i` (or `ipython -i`). The -i forces a prompt. Without it, the shell hangs in Emacs, I don't know why (it doesn't in cmd).
---
I personally automated this process by creating a batch file called `my-python.bat`. I placed it in a folder named `my-batch-files` which I have referenced in %PATH% \[\*\]. Here's the bat file :
```
@echo off
conda activate base && python -i
```
That way you can call directly `my-python` from the shell — whether it be on Emacs or on cmd — and have a working ipython shell, with all DLLs loaded.
Plus, if you change `python-shell-interpreter` to `my-python`, you get the default functions from python-mode `run-python` (C-c C-p) and `python-shell-send-buffer` (C-c C-c) working.
**Caveat** : At this time, images' display (with matplotlib.pyplot) still does not work properly. I'm working on it. If someone has ideas...
---
<sub>\[\*\] Windows -\> Environment variables -\> System Variables -\> Path -\> Edit. The paths should look like this (check them beforehand !) : `C:\Users\YOUR_USER_NAME\AppData\Local\Continuum\anaconda3\Scripts` and `C:\Users\YOUR_USER_NAME\AppData\Local\Continuum\anaconda3`.</sub>
<sub> You'll have to relaunch the shell (and Emacs !) for the environment variables to be taken into account. You can check the variable value by typing `echo %PATH%` in your shell. </sub>
> 1 votes
# Answer
This solved my issue of numpy failing to load on import when using Anaconda3/python on Windows 10 from my Emacs session:
https://github.com/ContinuumIO/anaconda-issues/issues/10884#issuecomment-499805821
> -1 votes
---
Tags: python, microsoft-windows
---
|
thread-52751
|
https://emacs.stackexchange.com/questions/52751
|
Cannot generate previews with latex-preview
|
2019-09-20T12:39:28.787
|
# Question
Title: Cannot generate previews with latex-preview
I am trying to use `preview-latex` but, when I generate previews, these are not loaded in Emacs gtk buffer, even though previews are correctly produced in the `.pdf` output file.
The error produced is the following:
```
/usr/local/texlive/2019/bin/x86_64-linux/rungs -dOutputFile\=\(main.prv/tmpysAeuO/pr1-23.png\) -q -dDELAYSAFER -dNOPAUSE -DNOPLATFONTS -dPrinted -dTextAlphaBits\=4 -dGraphicsAlphaBits\=4 -sDEVICE\=png16m -r119.04x119.353
GS>{<</PermitFileReading[(main.pdf)(main.prv/tmpysAeuO/preview.dsc)]>> setuserparams .locksafe} stopped pop {DELAYSAFER{.setsafe}if}stopped pop/.preview-BP currentpagedevice/BeginPage get dup null eq{pop{pop}bind}if def<</BeginPage{currentpagedevice/PageSize get dup 0 get 1 ne exch 1 get 1 ne or{.preview-BP 0.101961 0.101961 0.101961 setrgbcolor clippath fill 0.929702 0.929702 0.921889 setrgbcolor}{pop}ifelse}bind/PageSize[1 1]>>setpagedevice/preview-do{/.preview-ST[count 4 roll save]def dup length 0 eq{pop}{setpagedevice}{ifelse exec}stopped{handleerror quit}if .preview-ST aload pop restore}bind def /GS_PDF_ProcSet GS_PDF_ProcSet dup maxlength dict copy dup begin/graphicsbeginpage{//graphicsbeginpage exec 0.929702 0.929702 0.921889 3 copy rg RG}bind store end readonly store (main.prv/tmpysAeuO/preview.dsc)(r)file /.preview-ST 1 index def dup 0 setfileposition 22544()/SubFileDecode filter cvx exec .preview-ST dup dup 23313 setfileposition 53()/SubFileDecode filter cvx<<>>preview-do
Error: /typecheck in --setfileposition--
Operand stack:
GS_PDF_ProcSet GS_PDF_ProcSet GS_PDF_ProcSet 24994 24994 24994 24939 24939 24939 25104 25104 25104 24886 24886 24886 24831 24831 24831 24778 24778 24778 24725 24725 24725 24670 24670 24670 24615 24615 24615 24561 24561 24561 24509 24509 24509 24453 24453 24453 24397 24397 24397 24344 24344 24344 24288 24288 24288 24235 24235 24235 24180 24180 24180 24126 24126 24126 24073 24073 24073 23965 23965 23965 23912 23912 23912 23313
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- %loop_continue --nostringval-- --nostringval-- false 1 %stopped_push .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval--
Dictionary stack:
--dict:739/1123(ro)(G)-- --dict:0/20(G)-- --dict:77/200(L)--
Current allocation mode is local
Current file position is 30
GS<67>
```
What can I do to get it working?
I am running Emacs 26.1, texlive 2019, and auctex 12.1.2.
# Answer
> 1 votes
I have the exact same problem, error message and symptoms on a system running Arch Linux (kernel 5.3.7-arch1-1-ARCH), texlive 2019, Emacs 26.3 (build 1) and auctex 12.1.2. Everything is updated regularly.
I came across this question on Reddit and the author seems to have encountered the same issue. They report that disabling `TeX-PDF-mode` (either by `C-c C-t C-p` or via adding `(setq TeX-PDF-mode nil)` to the configuration) should solve the issue for the MELPA version of `auctex`.
This is the version which I use so I applied this configuration but the previews were still not functional.
Another solution is documented in the second reply (by user `u/Lockywolf`). They point out that a confirmed workaround is to download an older release of `Ghostscript` and use that for generating the previews.
My currently installed version of `Ghostscript` is `9.50` so I downloaded the older release `9.27` (`ghostscript-9.27-linux-x86_64.tgz`) from their GitHub releases as instructed on the official website. I extracted the executable and moved it to a convenient place in my home directory (e.g., `~/bin/`). Finally, I added the new path to my `init.el` configuration with `(setq preview-gs-command "~/bin/gs-927-linux-x86_64")`. After restarting emacs, the previews seem to work as expected.
Please note that I am unaware whether this workaround impacts negatively the system in terms of security, performance or quality of the produced documents.
---
Tags: auctex, preview-latex, gtk3
---
|
thread-53296
|
https://emacs.stackexchange.com/questions/53296
|
navigate into the project
|
2019-10-23T13:40:16.540
|
# Question
Title: navigate into the project
I have lost my emacs config and I try to reconfigure my .init.el on my work station.
I have install helm and defined :
```
(global-set-key (kbd "C-x C-f") 'helm-find-files)
```
I have the good windows, but in my last configuration i was able to navigate through my project with the keyboard arrow.
example :
C-x C-f --\> /home/foo/bar/
left arrow --\> /home/foo/
right arrow --\> /home/foo/bar/
In my emacs, actually, this behaviour is not reproducted. What should I do to have it ?
# Answer
> 1 votes
You have to add `(customize-set-variable 'helm-ff-lynx-style-map t)` in your .emacs.
---
Tags: helm, helm-projectile
---
|
thread-53273
|
https://emacs.stackexchange.com/questions/53273
|
How to transform abbrevated dates in org table
|
2019-10-22T11:01:13.317
|
# Question
Title: How to transform abbrevated dates in org table
The input column represents the year without 201 and month and day without leading zeros. I must transform these into full date strings.
After a couple of hours to take step 1, I'm wondering if there is a more elegant way to achieve the steps left:
1. Year: Find first first digit from left: Append 201 before (done)
2. Month: Find 5th digit from 1 to 9: Append a 0 before
3. Day: Find last digit from right which is between 1 to 9: Append a 0 after
4. Insert hyphen after year, month and date
```
|-------+----------+------------|
| input | output | expected |
|-------+----------+------------|
| 9725 | 2019725 | 2019-07-25 |
| 811 | 201811 | 2018-01-01 |
| 71212 | 20171212 | 2017-12-12 |
|-------+----------+------------|
#+TBLFM: $2='(baz @0$1)
```
```
(defun baz (cell)
(concat "201" cell))
```
Explanation: The input represents the batch processing of approx. thousand grocery receipts. The goal was to hit as few key strokes as possible.
# Answer
> 1 votes
If you don't mind using the date command, you can try the code below which I think addresses the four points you describe. It works fine with your example, however AFAICT it's impossible to distinguish between 11-1 and 1-11, so here I'm assuming the month is always two digits when the date is 7 digits long.
```
(defun fix-date-string (date)
(let ((yy (substring date 0 4))
(mm (substring date 4 5))
(dd (substring date 5 6))
(mmdd (substring date 4)))
(cond ((= (length date) 6)
(concat yy "0" mm "0" dd))
((= (length date) 7)
(concat yy "0" mmdd))
(t date))))
(defun baz (date)
(let* ((it (concat "201" date))
(it (fix-date-string it))
(it (format "date -d '%s'" it))
(it (shell-command-to-string it))
(it (string-trim it))
(it (date-to-time it))
(it (format-time-string "%F" it)))
it))
```
---
Tags: org-mode, org-table
---
|
thread-53325
|
https://emacs.stackexchange.com/questions/53325
|
Emacs keybindings / invocation for Apple iMac keyboard, similar to LMI or Knight?
|
2019-10-24T16:23:09.053
|
# Question
Title: Emacs keybindings / invocation for Apple iMac keyboard, similar to LMI or Knight?
Does anyone have a HOWTO on creating efficient keybindings and invocation of Emacs for the iMac Bluetooth keyboard pictured here?
Specifically one or more of the following use cases:
* Invocation of Emacs in ssh terminal session to VM with VT100 emulation within Terminal.app.
* Invocation of Emacs with X-mode in terminal session to VM within Terminal.app.
* Invocation of Emacs in Mac OS within Terminal.app
* Invocation of XEmacs in Mac OS
As you can see from above, I'm trying to invoke Emacs from within a VM for security reasons.
I'm seeking similar meta and control keybindings as the LMI or Knight keyboard pictured and a way to switch back and forth without impact OSX keybindings. For instance Meta should be Fn, Control or Option on the iMac Bluetooth keyboard. Command should be Control on the iMac Bluetooth keyboard.
I'm hoping some hard core Emacs LISP / Scheme users have such keybindings.
Thank you
# Answer
Have you tried using `customize-group` `ns` to interactively modify the keys to be as you want them? It's not possible change the role of FN in application settings, but Command and Control can be switched. Typically, one would set `Ns Command Modifier` to Meta, but to accomplish what you want, you could set it to Control and then set `Ns Control Modifier` to Meta.
The `ns` group corresponds to GNUstep/macOS specific features, so it's available in Emacs versions such as Emacs for OS X.
Another tricky element is that terminal emulators have their own shortcuts using modifier keys. You may need to use a more customizable terminal emulator like iTerm to set the modifier key behavior to be agreeable with Emacs. When I open Emacs in the terminal, Cmd doesn't work as Meta anymore, and instead I have to use Alt. So I've customized iTerm with a few custom Cmd+Key shortcuts to send Meta+Key (^\[ + key)
> 0 votes
---
Tags: key-bindings, terminal-emacs
---
|
thread-53321
|
https://emacs.stackexchange.com/questions/53321
|
Are there TRAMP mode log files? If so, how to access them?
|
2019-10-24T14:34:02.047
|
# Question
Title: Are there TRAMP mode log files? If so, how to access them?
Having here some troubles with TRAMP mode and already set `(customize-set-variable 'tramp-verbose 6 "Enable remote command traces")` in `.emacs` file.
But main problem is that Emacs is stuck in TRAMP mode, and debug buffer can't be accessed.
Hangs while copying large files via scp to remote to local network, it hangs on Encoding in base64. Already set (setq tramp-inline-compress-start-size "800000000"), (setq tramp-copy-size-limit "800000000") and (customize-set-variable 'tramp-verbose 6 "Enable remote command traces").
Anyway there would be log files to access?
# Answer
> 1 votes
Just do it as brother up there said, we are having similar problem here and `CRTL + g` works swiftly, then just check debug buffer.
---
Tags: tramp, logging
---
|
thread-53336
|
https://emacs.stackexchange.com/questions/53336
|
Force function evaluation when setting variable value?
|
2019-10-25T00:53:48.863
|
# Question
Title: Force function evaluation when setting variable value?
I have these functions defined in my `early-init.el`. I'm trying to change the location of where my backups are saved and keep getting a `Wrong type argument stringp (djm/emacs-cache "backups/")`.
**`early-init.el`**
```
(Defconst user-emacs-cache "~/.cache/emacs/")
(eval-and-compile
(defun djm/emacs-path (path)
(expand-file-name path user-emacs-directory)))
(eval-and-compile
(defun djm/emacs-cache (path)
(expand-file-name path user-emacs-cache)))
```
**`init.el`**
```
(Use-package files
:ensure nil
:custom
(auto-save-file-name-transforms '((".*" (djm/emacs-cache "backups/") t)))
(backup-directory-alist '(("." . (djm/emacs-cache "backups/")))))
```
I change the place of a lot of files in my init file. How can I make something like this work without hardcoding it?
# Answer
> 1 votes
I ended up finding a suitable solution on another SO answer found here:
How to evaluate the variables before adding them to a list?
> `(quote ARG)`
>
> Return the argument, without evaluating it. `(quote x)` yields `x`. Warning: `quote` does not construct its return value, but just returns the value that was pre-constructed by the Lisp reader...
Hence, you either need to backquote or use a function that evaluates the arguments.
Thus, I was able to fix the error by doing:
```
(Use-package files
:ensure nil
:custom
(auto-save-file-name-transforms `((".*" ,(djm/emacs-cache "backups/") t)))
(backup-directory-alist `(("." . ,(djm/emacs-cache "backups/")))))
```
I'm still interested in learning best practices or a more idiomatic away to achieve this. I will accept an answer showing this.
---
Tags: init-file, functions, start-up
---
|
thread-53338
|
https://emacs.stackexchange.com/questions/53338
|
What is a better way to write this function?
|
2019-10-25T02:37:34.183
|
# Question
Title: What is a better way to write this function?
```
(cl-defun filename-from-buffer (&key get-ext get-path)
(let ((filename (buffer-name))
(pathname (buffer-file-name)))
(setq ret (car (split-string filename "\\.")))
(when get-path
(setq ret (car (split-string pathname "\\."))))
(when get-ext
(setq ret filename))
(when (and get-ext get-path)
(setq ret pathname))
ret))
```
I am fairly new to Emacs and Lisp (eLisp) and I wanted a function that would return the name of the file which is open in the current buffer. The function should take some optional arguments determining whether we want the full path, the extension or just the sole name of the file.
I feel like my implementation is pretty naive and it depends on the order of lines as well because I could not figure out how to do an `if-else` chain and return within. So is there a more elegant/more secure or just a better way to do this? By better, I mean something that uses the functionality of language which is already provided, an implementation that does not depend on the order of cases and/or something that does branching in a better way.
# Answer
You can use `cond`, which corresponds to "if"-"else if"-"else" chains in other languages. It picks the first clause whose condition is non-`nil`.
Here we don't need a temporary variable, since we're just going to return the value from the `cond` clauses directly. The last clause has `t`, the "true" value in Lisp, as its condition, so it will be picked if none of the preceding clauses were picked.
```
(cl-defun filename-from-buffer (&key get-ext get-path)
(let ((filename (buffer-name))
(pathname (buffer-file-name)))
(cond
((and get-ext get-path)
pathname)
(get-path
(file-name-sans-extension pathname))
(get-ext
filename)
(t
(file-name-sans-extension filename)))))
```
---
Emacs Lisp also has `if`, but you only get an "if" clause and an "else" clause, no "else if":
```
(if some-condition
value-if-true
value-if-false)
```
Though you could achieve that by nesting several `if`s in each other, it's more elegant to use `cond` in such a situation. Nested `if`s would look like this:
```
(if (and get-ext get-path)
pathname
(if get-path
(file-name-sans-extension pathname)
(if get-ext
(file-name-extension filename)
(file-name-sans-extension filename))))
```
> 0 votes
---
Tags: functions
---
|
thread-53341
|
https://emacs.stackexchange.com/questions/53341
|
How to show commit authors in Magit section "Recent commits"?
|
2019-10-25T08:42:34.887
|
# Question
Title: How to show commit authors in Magit section "Recent commits"?
The "Recent commits" section in the status view shows short commit checksums plus the subject of the commit. How can I also show the author of each commit?
# Answer
Turn on the "log margin" using `L L`. As you can see the `L` prefix features other margin related bindings as well.
This is mostly intended for buffers showing only logs or to be enabled only briefly. Of course you can also permanently enable it for the status buffer, but then you also permanently waste space in the margin of lines that have nothing that they could display there.
To enable the margin permanently and to control what is shown by default and how, see the options in the `magit-margin` group.
Also see the Log Margin section in the manual.
> 5 votes
---
Tags: magit
---
|
thread-53332
|
https://emacs.stackexchange.com/questions/53332
|
What is the equivalent of doing a plain `git reset <sha>` in magit?
|
2019-10-24T21:14:29.717
|
# Question
Title: What is the equivalent of doing a plain `git reset <sha>` in magit?
I sometimes want to undo a commit without losing the changes, but just placing them back into an uncommitted and unstaged state. To do that at the cli, I do just `git reset <sha-of-previous-commit>`.
How would I do the same in magit?
# Answer
> 7 votes
Use `x` or `X s` to do so.
Using the `X` prefix has the benefit that it shows you all the available `git reset` variants.
This is also documented in the Resetting section of the manual.
---
Tags: magit, git
---
|
thread-53005
|
https://emacs.stackexchange.com/questions/53005
|
Magit merging changes manually
|
2019-10-07T12:23:44.460
|
# Question
Title: Magit merging changes manually
When I do merge preview `m p` I see a log of other branch changes for each affected file. Changes marked like this:
```
@@ -20,6 + 22,7 @@
- <change>
+ <change>
```
To merge only a particular file I can do from command line:
```
git checkout another_branch -- ./path/to/file
```
(btw, is there a way to do it in Magit?)
BUT, suppose, I want to merge only specific changes from the log, and not the entire file. Is there any way to do that in magit, or git cli? Ideally I'd love to check the changes that I want to merge manually.
# Answer
> To merge only a particular file I can \[use `git checkout`\] from command line:
This does *not* perform a merge. This does not only apply the changes from the other branch, it also discards changes that have been made on *your* branch since the other branch diverged.
> I want to merge only specific changes from the log
Show the diff appropriate changes. For each change that you want to apply move to it and press `a` to apply it. This may fail if there is a conflict, in which case `C-u a` should work.
"Selective applying" works the same way as "selective staging" using `s`; you can act on a complete file, hunk, or even just parts of a hunk using the region.
For more information see sections of the manual titled Staging and Unstaging, Applying and Merging.
> 4 votes
---
Tags: magit, git
---
|
thread-53310
|
https://emacs.stackexchange.com/questions/53310
|
What is causing this AUCTeX preview fatal error, or how can I find that out?
|
2019-10-24T04:41:08.947
|
# Question
Title: What is causing this AUCTeX preview fatal error, or how can I find that out?
This is a minimal test file:
```
\documentclass{article}
\begin{document}
\[1+1=2\]
\end{document}
```
The content of texput.log is the following:
```
This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019) (preloaded format=pdflatex 2019.10.7) 23 OCT 2019 23:49
entering extended mode
restricted \write18 enabled.
file:line:error style messages enabled.
%&-line parsing enabled.
**\nonstopmode\nofiles\PassOptionsToPackage{active,tightpage,auctex}{preview}\AtBeginDocument{\ifx\ifPreview\undefined\RequirePackage[displaymath,floats,graphics,textmath,sections,footnotes]{preview}[2004/11/05]\fi} \input {\detokenize{ _region_.tex }}^^M
! Emergency stop.
<read *>
<*> ...5]\fi} \input {\detokenize{ _region_.tex }}
^^M
*** (cannot \read from terminal in nonstop modes)
Here is how much of TeX's memory you used:
8 strings out of 492166
160 string characters out of 6125377
59039 words of memory out of 5000000
4473 multiletter control sequences out of 15000+600000
3640 words of font info for 14 fonts, out of 8000000 for 9000
1141 hyphenation exceptions out of 8191
5i,0n,6p,268b,10s stack positions out of 5000i,500n,10000p,200000b,80000s
! ==> Fatal error occurred, no output PDF file produced!
```
The problem appeared after one time I ran `brew upgrade` in terminal. I guess it is because the latest ghostscript has some incompatibility issue with AUCTeX. I have searched a lot and tried a lot. Here are what I have done:
1. I use Mac. There is a known problem with the path of ghostscript. This line is in my init file: `(setq preview-gs-command "/usr/local/bin/gs")`. It should be correct.
2. I have tried to manually install old versions of ghostscript, like 9.21 or 9.25. They used to solve the problem, but not this time.
3. I uninstalled ghostscript installed with brew and manually installed 9.25. Not working.
System: MacOS Catalina 10.15
Emacs: GNU Emacs 26.3 (build 1, x86\_64-apple-darwin18.2.0, NS appkit-1671.20 Version 10.14.3 (Build 18D109)) of 2019-09-02
AUCTeX: 12.1.2
ghostscript: 9.25
# Answer
This time the culprit is not GS but the latest updates to LaTeX kernel. This issue is fixed in AUCTeX repo. Just wait for the new AUCTeX release which should happen quit soon and install it from ELPA then.
> 1 votes
---
Tags: auctex, osx, preview-latex
---
|
thread-53331
|
https://emacs.stackexchange.com/questions/53331
|
Emacs Org-mode + Letter class = Unknown latex class 'letter'
|
2019-10-24T21:01:16.563
|
# Question
Title: Emacs Org-mode + Letter class = Unknown latex class 'letter'
I want to use Emacs with org-mode to export notes using 'letter' class. Texlive is installed in a Mac, and have many classes to export. But Emacs in org-mode only work with: article, report and book:
```
#+LATEX_CLASS: letter
```
But when I go to export I get the message:
```
Unknown LaTeX class 'letter'
```
If use 'article' and open the generated .tex file changing 'article' with 'letter' and exec from terminal 'pdflatex' passing the .tex file as a param then export a PDF correctly using the letter class. How can I use 'letter' class or others that come with Texlive inside of Emacs and Org-mode?
Thank you.
# Answer
Although the answer by @Robert is perfectly correct, just a more detailed answer: Org is only "aware" of (i.e., can only handle/export) the LaTeX classes defined in the variable `org-latex-classes`. If you want Org to handle more classes than the default setting, you have to add manually the support for those classes, by customizing the value of this lisp variable. For example, you can add the following lines in your `init.el` (or `.emacs`) file:
```
(add-to-list 'org-latex-classes
'("letter"
"\\documentclass{letter}"
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
```
The first link posted by Robert explains how to better customize (if needed) the support of section headers for this class.
> 10 votes
# Answer
see https://orgmode.org/manual/LaTeX-header-and-sectioning.html#LaTeX-header-and-sectioning You can customize org-latex-classes like https://superuser.com/questions/896741/how-do-i-configure-org-latex-classes-in-emacs HTH
> 2 votes
---
Tags: org-mode, latex
---
|
thread-53353
|
https://emacs.stackexchange.com/questions/53353
|
How to get correct list numbering with code blocks items in Org-babel?
|
2019-10-25T13:14:22.460
|
# Question
Title: How to get correct list numbering with code blocks items in Org-babel?
Here is a minimal working example of Org file for LaTeX export:
```
#+OPTIONS: toc:nil
* A list with R source blocks
1. This is the first item.
#+begin_src R :results output :session *R* :exports both
x <- 2
print(2*x)
#+end_src
2. This is the second item.
* Local Variables :noexport:
Local Variables:
org-latex-listings:nil
End:
```
Here is the output I get:
As you can see, the numbering of items in org lists is "broken" if one of the items contains a source block. Is there a way to avoid that, and to have the second item correctly labeled "2." ?
Thanks!
# Answer
Insert three spaces before `#+begin_src` and `#+end_src` to shift the source block on the same level as the items. You do not need to indent the source code.
Without indent Org thinks the source block starts a new paragraph below the list.
> 0 votes
---
Tags: org-mode, latex, org-babel
---
|
thread-53234
|
https://emacs.stackexchange.com/questions/53234
|
Emacs 26.3 cannot call R
|
2019-10-18T17:15:00.367
|
# Question
Title: Emacs 26.3 cannot call R
After updated to macOS Catalina (10.15) I've been trying to use R in Emacs 26.3. However, Emacs is not fetching R by using `M-x R` (Emacs says `[No match]`).
I already checked the paths for both R and Emacs in the Terminal, both are in `/usr/local/bin`. Also, I checked `M-x getenv PATH` within Emacs. This is the result:
```
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/Library/Apple/bin:/Library/TeX/texbin:/opt/X11/bin:/Applications/Emacs.app/Contents/MacOS/bin-x86_64-10_14:/Applications/Emacs.app/Contents/MacOS/libexec-x86_64-10_14
```
Can anyone help me with this please? Any ideas to fix the problem? Please let me know if you need more info.
# Answer
> 2 votes
The command `M-x R` is provided by the package ESS, which is available via the Melpa repository. You need to install this package before you can start the R process this way.
There was a period in early 2019 when the `R` command was broken in ESS, but it has since been fixed, so installing the current release of ESS should restore the `R` command.
---
Tags: osx, ess, r
---
|
thread-53306
|
https://emacs.stackexchange.com/questions/53306
|
Color for important entry in global TODO list
|
2019-10-23T20:51:36.213
|
# Question
Title: Color for important entry in global TODO list
In Org Agenda, I use Org priorities to know when I should get on something (A=now, B=soon or C=later).
I use `:STYLE:` property with a custom `important` value for some entries (no matter when I need to do it).
I would like to color the line for such entries in the global TODO list in the agenda buffer.
I see no help in `:STYLE: habit` related customization.
How could I do that?
# Answer
> 0 votes
Here's one way to fontify all entries matching `:STYLE: important`.
```
(defun fontify-important-entries ()
;; Move the point to the start of the buffer.
(goto-char (point-min))
;; Then keep moving down one line until the end of the buffer.
(while (progn (forward-line 1) (not (eobp)))
;; Now get the text property at the start of each line. If there
;; are no markers, do nothing.
(when-let (marker (org-get-at-bol 'org-marker))
(let* ((buffer (marker-buffer marker))
(pos (marker-position marker))
prop)
;; From the agenda buffer, move to the org file.
(with-current-buffer buffer
(widen) (goto-char pos)
;; The point is at the heading, so get the value of the
;; STYLE properties and set it to prop.
(setq prop (org-entry-get nil "STYLE")))
;; Now move back to the agenda buffer and check if the value
;; of prop matches the string important.
(when (string= prop "important")
;; If it does, change the face of that line/entry.
(add-text-properties (point-at-bol)
(point-at-eol)
'(face org-habit-overdue-future-face)))))))
(add-hook 'org-agenda-finalize-hook 'fontify-important-entries)
```
---
Tags: org-mode, org-agenda
---
|
thread-53366
|
https://emacs.stackexchange.com/questions/53366
|
I can turn on minor modes like electric pair modes in my init, but they’re not having effect unless manually reactivated
|
2019-10-25T21:40:18.633
|
# Question
Title: I can turn on minor modes like electric pair modes in my init, but they’re not having effect unless manually reactivated
So I can put a line like, `(setq-default global-linum-mode t)` or `(setq-default electric-par-mode t)` in my init file, and I can check with C-h v that the variables are in fact set to t (they are), but unless I actually M-x them on inside a file, they’re not having any effect. What might be going on?
I’m on an ssh terminal to a Debian Raspberry Pi, if relevant.
# Answer
You can get help for a particular variable via `C-h v global-linum-mode`. This will show you:
> global-linum-mode is a variable defined in ‘linum.el’. Its value is nil
>
> Documentation:
> Non-nil if Global Linum mode is enabled.
> See the ‘global-linum-mode’ command
> for a description of this minor mode.
> **Setting this variable directly does not take effect;**
> either customize it (see the info node ‘Easy Customization’)
> or call the function ‘global-linum-mode’.
So you can either set the value via the customization menu, or call the function `(global-linum-mode)` in your init, instead of using `(setq-default global-linum-mode t)`.
There is a similar message waiting for you behind `C-h v electric-pair-mode`.
> 0 votes
---
Tags: customize, minor-mode, linum-mode, electric-pair-mode
---
|
thread-31702
|
https://emacs.stackexchange.com/questions/31702
|
Can't get out of minibuffer completion
|
2017-03-25T19:47:54.823
|
# Question
Title: Can't get out of minibuffer completion
Since upgrading from v. 24 to v. 25 \[OSX 10.11.6\] I find myself frequently fighting with minibuffer completion, as typing a tab after doing switch-to-buffer. ^G just beeps, and the completions redisplay. The only way I know to exit the minibuffer in this situation is to pick one of the completions, either with the mouse or by navigating with keys. I have a pretty simple setup with respect to switch-buffer. I don't think I use any buffer libraries that would affect his, and have not changed buffer handling for several versions. Any suggestions about what is causing this and how I can get out of minibuffer completion without choosing one of the completions?
# Answer
> 9 votes
Is it possible there is an active recursive edit in the completion minibuffer? `C-]` by default is `abort-recursive-edit`. Alternatively `keyboard-escape-quit` or `ESC ESC ESC` might help?
# Answer
> 1 votes
I was seeing the same thing, but I knew that for me it had started sometime *after* I'd upgraded to and had been using Emacs 25. In my case, the problem turned out to be my recent addition of the following to my `~/.emacs` file:
```
(set-frame-parameter nil 'unsplittable t)
```
The above was one of several things I had used to try to undo some *other* behavior changes that Emacs 25 brought in. In this case, it wasn't the right thing to try.
This also might explain why I didn't seem to get stuck in the minibuffer when I was running with my full `~/.emacs` configuration, yet in `--no-window-system (-nw)` mode. There, as I understand it, frames aren't even a thing.
# Answer
> 1 votes
Aha! This has been making me crazy for a long time. Today I spent some more time searching and exploring. I stumbled on the answer after doing ^H-m when in the minibuffer. The fourth keybinding listed is "q", quit-window. Typing q when completions are displayed closes the completion buffer and returns to the minibuffer, where ^G aborts normally.
I don't understand why it was so difficult for me to figure this out, or why there aren't a lot of people complaining about this.
---
Tags: debugging, completion, minibuffer
---
|
thread-53357
|
https://emacs.stackexchange.com/questions/53357
|
eval-expression on (setq helm-debug t) does not change describe-variable output
|
2019-10-25T15:11:24.530
|
# Question
Title: eval-expression on (setq helm-debug t) does not change describe-variable output
I'm running this version of Emacs:
```
GNU Emacs 26.3 (build 2, x86_64-pc-linux-gnu, GTK+ Version 3.24.11) of 2019-09-23, modified by Debian
```
Installed on Ubuntu 19.10 via apt, and not built from source.
I'm trying to set the `helm-debug` variable so that I can see what Helm is doing to debug a problem (`helm-locate` is not showing files that exist in a directory whose parent element has `.git` in it).
So in the past, I could use `M-:` (mapped to `eval-expression`) and type in an expression, which I did with this:
```
(progn (setq helm-debug 'xxx) (message "helm-debug == %S" helm-debug))
```
And I get what I expect to see in the message area of:
```
"helm-debug == xxx"
```
And, I go back in and run `M-:` again to check on the value like this:
```
helm-debug
```
I see `xxx` as the resulting value. All good so far.
But then, when I type `C-h v` (mapped to `describe-variable`), and then type in `helm-debug`, and I see this:
```
helm-debug is a variable defined in ‘helm.el’.
Its value is nil
Documentation:
If non-‘nil’, write log message to ‘helm-debug-buffer’.
Default is ‘nil’, which disables writing log messages because the
size of ‘helm-debug-buffer’ grows quickly.
```
Why is it reporting `nil`, when I have clearly set it inside the `eval-expression` call?
For reference, the `defvar` for this variable resides in `~/.emacs.d/elpa/helm-core-20191013.626/helm.el` in my setup (meaning Helm mode has been recently upgraded)
```
(defvar helm-debug nil
"If non-`nil', write log message to `helm-debug-buffer'.
Default is `nil', which disables writing log messages because the
size of `helm-debug-buffer' grows quickly.")
```
# Answer
> 1 votes
It seems it's intended:
```
helm-internal calls
helm-log-save-maybe calls
(setq helm-debug nil)
```
thus whenever a helm session ends, `helm-debug` will be reset to nil. I guess it's because the log buffer can grow too quickly.
Instead of changing `helm-debug` directly, according to helm's own help (you can get it by type `C-h m` within any helm session, I have pasted the related section below), you can use `C-h C-d`:
> ### Debugging Helm
>
> Helm exposes the special variable `helm-debug`: setting it to non-nil will enable Helm logging in a special outline-mode buffer. **Helm resets** **the variable to nil at the end of each session**.
>
> For convenience, C-h C-d allows you to turn on debugging for this session only. To avoid accumulating log entries while you are typing patterns, you can use C-! to turn off updating. When you are ready turn it on again to resume logging.
>
> Once you exit your Helm session you can access the debug buffer with `helm-debug-open-last-log`. It is possible to save logs to dated files when `helm-debug-root-directory` is set to a valid directory.
>
> Note: Be aware that Helm log buffers grow really fast, so use `helm-debug` only when needed.
---
Tags: helm, debugging, variables, help, eval-expression
---
|
thread-53359
|
https://emacs.stackexchange.com/questions/53359
|
org-mode headings to org-table
|
2019-10-25T18:28:41.190
|
# Question
Title: org-mode headings to org-table
I have a big org file with lot of topics, and every topic have a books subheading. I would like write a function that can generate a list of all books in org-table. I was trying with (org-map-entries) but no luck so far ;)
# Answer
> 3 votes
Something like this. Call it with `M-x my-org-books-to-table RET` while the org buffer with your books is active to insert the table at point:
```
(defun my-org-books-to-table ()
"Generate a list of books and insert as org-table."
(interactive)
(let ((item "books")
items)
;; Map through all headings with item (text of the headline) "books".
(org-map-entries
(lambda ()
(let ((lvl (number-to-string (1+ (org-outline-level)))))
;; Map through children of heading found. Add to books unless its
;; heading text matches "books".
(org-map-entries
(lambda ()
(let* ((olp (org-get-outline-path t t))
(txt (car (last olp)))
(title (nth 0 olp)))
(push (list title txt) items)))
(concat "LEVEL=" lvl "+ITEM<>\"" item "\"") 'tree)))
(concat "ITEM=\"" item "\""))
(setq items (nreverse items))
(setq items (append (list '(title topic) 'hline) items))
(insert (concat (orgtbl-to-orgtbl items nil) "\n"))))
```
---
Tags: org-mode, org-table
---
|
thread-53378
|
https://emacs.stackexchange.com/questions/53378
|
How to diff against a git branch?
|
2019-10-26T16:21:00.393
|
# Question
Title: How to diff against a git branch?
I'm currently using `(vc-root-diff nil)` however, I'd like to spesify a branch.
Calling `(vc-root-diff t)` prompts for the revision, and the path.
Is there a way to diff against a branch without, manually entering it in every time?
# Answer
This can be done using:
`(vc-root-version-diff nil "master" nil)`
* The first `nil` could be replaced by `(vc-root-dir)`.
* The second one *could* be replaced by `HEAD` however this doesn't include local changes to the tree, so it needs to be `nil`.
> 1 votes
---
Tags: diff, diff-mode
---
|
thread-52903
|
https://emacs.stackexchange.com/questions/52903
|
Problem Committing with Magit
|
2019-09-30T02:56:39.520
|
# Question
Title: Problem Committing with Magit
I'm a relatively new convert to emacs and a very new convert to Mac. After installing Emacs using the ESS installer (Version 18.10.2).
When I attempt to state a file for commit I receive the following error.
```
GitError! There was a problem with the editor '/Applications/Emacs.app/Contents/MacOS/bin/emacsclient --socket-name=/var/folders/s2/mjvyfw3d13zd8swxf8ds92c40000gn/T/emacs501/server'. [Type `$' for details]
```
Pressing `$` yields the following.
```
0 git … add -u -- inst/process.R
1 git … commit --
hint: Waiting for your editor to close the file...
Waiting for Emacs...
*ERROR*: Wrong type argument: stringp, nil
error: There was a problem with the editor '/Applications/Emacs.app/Contents/MacOS/bin/emacsclient --socket-name=/var/folders/s2/mjvyfw3d13zd8swxf8ds92c40000gn/T/emacs501/server'.
Please supply the message using either -m or -F option.
0 git … add -u .
1 git … commit --
hint: Waiting for your editor to close the file...
Waiting for Emacs...
*ERROR*: Wrong type argument: stringp, nil
error: There was a problem with the editor '/Applications/Emacs.app/Contents/MacOS/bin/emacsclient --socket-name=/var/folders/s2/mjvyfw3d13zd8swxf8ds92c40000gn/T/emacs501/server'.
Please supply the message using either -m or -F option.
```
* My EMACS Version
```
GNU Emacs 26.2 (build 1, x86_64-apple-darwin18.2.0, NS appkit-1671.20 Version 10.14.3 (Build 18D109))
of 2019-04-12
```
When run with `M-x toggle-on-debug-error` I don't seem to get any different output.
```
GitError! There was a problem with the editor '/Applications/Emacs.app/Contents/MacOS/bin/emacsclient --socket-name=/var/folders/s2/mjvyfw3d13zd8swxf8ds92c40000gn/T/emacs501/server'. [Type `$' for details]
1 git … commit --
hint: Waiting for your editor to close the file...
Waiting for Emacs...
*ERROR*: Wrong type argument: stringp, nil
error: There was a problem with the editor '/Applications/Emacs.app/Contents/MacOS/bin/emacsclient --socket-name=/var/folders/s2/mjvyfw3d13zd8swxf8ds92c40000gn/T/emacs501/server'.
Please supply the message using either -m or -F option.
```
More information. From the below advice I was able to determine that commenting out the below lines in my `emacs.d/init.el` file allows magit to work properly.
```
;; (add-hook 'find-file-hook 'my-r-style-hook)
;; (defun my-r-style-hook ()
;; (when (string-match (file-name-extension buffer-file-name) "[r|R]$")
;; (ess-set-style 'RStudio)))
```
# Answer
Okay. I have it working now. The problem was in my attempt at a hook to set ess-set-style to RStudio automatically.
Thanks to another stackoverflow topic I saw that there was a specific `ess-mode-hook` I should be using
https://stackoverflow.com/questions/7502540/make-emacs-ess-follow-r-style-guide
Modifying my `init.el` file with the following fixes my issue with magic.
```
(add-hook 'ess-mode-hook
(lambda ()
(ess-set-style 'RStudio)))
```
Thanks to everyone for their patience in helping me muddle through this.
> 1 votes
# Answer
Some type error has occurred. Based on basically "when committing I get `Wrong type argument: stringp, nil`" it is very hard to know where exactly that error occurred so without you helping us help you that's all we can say.
Except maybe adding general debugging advice. You should start by trying to reproduce the issue starting from `emacs -Q`. We provide a tool to make that easier, see https://magit.vc/manual/2.11.0/magit/Debugging-Tools.html.
> 0 votes
---
Tags: magit, osx, ess
---
|
thread-53383
|
https://emacs.stackexchange.com/questions/53383
|
Python shell warning about readline and completion?
|
2019-10-26T21:18:51.040
|
# Question
Title: Python shell warning about readline and completion?
`*Warning*`:
> Warning (python): Your ‘python-shell-interpreter’ doesn’t seem to support readline, yet ‘python-shell-completion-native-enable’ was t and "python3" is not part of the ‘python-shell-completion-native-disabled-interpreters’ list. Native completions have been disabled locally.
I only get it in specific cases and I am not sure what is causing it. I am reading some data like this,
```
# !/usr/bin/env python3
import pickle
from variables import objects_address
photos = pickle.load(open(objects_address + '2019-10-19 21:18:23.dat', 'rb'))
```
There is more in this file but in order to narrow the problem I commented all of it. But, the warning persists. After this I do some manipulations to the array of photo objects which `photos` is and ask for a `Y/n` to save the photos with manipulations using `input()`. The program does not halt at this point if I get the warning and it just continues execution. I made this test file,
```
# !/usr/bin/env python3
import pickle
# from geocoder import ip
n = [1,2,3]
pickle.dump(n, open('TEST.TEST', 'wb'))
x = pickle.load(open('TEST.TEST', 'rb'))
print(x)
name = input('What is your name? ')
print('That\'s a nice name, ' + name + '!')
```
This file runs and acts perfectly fine; takes input and all that. Although, I tried putting `from geocoder import ip` in this file and that reproduced the warning. If you add this import to my test file (or even a file with just this one line), we get the same warning.
Here is the output of the test file (with the import that causes the warning):
```
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> [1, 2, 3]
What is your name? That's a nice name, import codecs, os;__pyfile = codecs.open('''/tmp/py8974PaE''', encoding='''utf-8''');__code = __pyfile.read().encode('''utf-8''');__pyfile.close();os.remove('''/tmp/py8974PaE''');exec(compile(__code, '''/tmp/py8974PaE''', 'exec'));!
```
Here is output without the import that causes the warning (I omitted the version info),
```
What is your name? Tom
That's a nice name, Tom!
>>> python.el: native completion setup loaded
```
Note that in my original file where I read data, I am not importing this geocoder. It was in a neighbouring file where I made the test file and I ran it randomly and realised that it also causes the warning.
I have tried different solutions which people suggested about this warning but non of them worked. I am running `GNU Emacs 25.2.2` on `Ubuntu 18.04.3 LTS`
This is my `use-package` configurations for elpy in my `.emacs`:
```
;; elpy
(use-package elpy
:ensure t
:defer t
:init
(elpy-enable)
(setq elpy-rpc-python-command "python3")
(defun my-python-shell-run ()
"Run python and pop-up its shell.
Kill process to solve the reload modules problem."
(interactive)
(when (get-buffer-process "*Python*")
(set-process-query-on-exit-flag (get-buffer-process "*Python*") nil)
(kill-process (get-buffer-process "*Python*"))
;; If you want to clean the buffer too.
(kill-buffer "*Python*")
;; Not so fast!
(sleep-for 0.5))
(run-python (python-shell-parse-command) nil nil)
(python-shell-send-buffer)
;; Pop new window only if shell isnt visible in any frame.
(unless (get-buffer-window "*Python*" t)
(python-shell-switch-to-shell)))
:hook (elpy-mode . (lambda ()
(highlight-indentation-mode -1)
(linum-mode t)))
:bind (:map elpy-mode-map
("C-e" . 'elpy-format-code)
("C-w" . 'elpy-pdb-debug-buffer)
("M-w" . 'elpy-pdb-toggle-breakpoint-at-point)
("C-l C-p" . 'elpy-pdb-break-at-point)
("C-c C-c" . 'my-python-shell-run)
("C-h f" .'python-eldoc-at-point)
("M-<backspace>"
. (lambda ()
(interactive)
(with-current-buffer
(process-buffer (elpy-shell-get-or-create-process))
(comint-clear-buffer))))))
```
# Answer
> 2 votes
AFAIU that warning only realizes if you call TAB at the end of a symbol, which will try completion.
It's just a warning. If Python3's module `pyreadline` is not installed. Emacs' own completion will not work in Python3. This warning would not happen if native completion for Python3 is disabled as a member of `python-shell-completion-native-disabled-interpreters`.
Either installing `pyreadline` or customizing `python-shell-completion-native-enable` to nil should switch the warning off. If not, please consider filing a bug-report.
Commentary section of python.el explains the details:
Shell completion: hitting tab will try to complete the current word. The two built-in mechanisms depend on Python's readline module: the "native" completion is tried first and is activated when `python-shell-completion-native-enable' is non-nil, the
current`python-shell-interpreter' is not a member of the `python-shell-completion-native-disabled-interpreters' variable and`python-shell-completion-native-setup' succeeds; the "fallback" or "legacy" mechanism works by executing Python code in the background and enables auto-completion for shells that do not support receiving escape sequences (with some limitations, i.e. completion in blocks does not work). The code executed for the "fallback" completion can be found in `python-shell-completion-setup-code' and`python-shell-completion-string-code' variables. Their default values enable completion for both CPython and IPython, and probably any readline based shell (it's known to work with PyPy). If your Python installation lacks readline (like CPython for Windows), installing pyreadline (URL \`http://ipython.org/pyreadline.html') should suffice. To troubleshoot why you are not getting any completions, you can try the following in your Python shell:
> > > import readline, rlcompleter
If you see an error, then you need to either install pyreadline or setup custom code that avoids that dependency.
---
Tags: python, elpy, warning, inputs
---
|
thread-53390
|
https://emacs.stackexchange.com/questions/53390
|
Hi-lock code syntax
|
2019-10-27T05:11:44.893
|
# Question
Title: Hi-lock code syntax
I write Hi-lock code at the beginning of tex and org buffers, but it doesn't always behave as I expect it to. What does the number 0 mean in the following? What does it mean when it is 1, instead?
```
% Hi-lock: (("[HH]umpty" (0 (quote hi-red-b) prepend)))
% Hi-lock: (("[DD]umpty" (0 (quote hi-green) prepend)))
```
# Answer
It refers to the regexp group that should be highlighted. 0 means the entire regexp. 1 means the first group etc.
A group is specified using `\(` and `\)`. For example:
```
"\\(Humpty\\)\\(Dumpty\\)" (1 'hi-red-b prepend) (2 'hi-green prepend))
```
In this example, Humpty is subgroup 1 and Dumpty 2. They will be colored red and green, respectively.
Note that regexp:s are written using elisp strings, so the backslash needs to be quoted -- in other words the string `"\\("` yields the regepx `\(`.
This is described in the elisp manual, in the section Search Based Fontification. The format typically used is the `(matcher highlighters ...)` form, with highlighters on the form *subexp-highlighter*, documented above.
> 4 votes
---
Tags: font-lock, hi-lock
---
|
thread-53391
|
https://emacs.stackexchange.com/questions/53391
|
Adding `**` to head of lines with numbers in the beginning
|
2019-10-27T06:35:12.843
|
# Question
Title: Adding `**` to head of lines with numbers in the beginning
I have the following contexts:
```
4. Pattern-Matching Conditional: How to use pcase and friends.
5. Iteration: while loops.
6. Generators: Generic sequences and coroutines.
```
and intent add `**` to the head of each lines thus try replace-regexp
`^\([::digit::]\) → ** \1`
However, nothing happened.
What's the problem with my solution?
# Answer
> 2 votes
The character class name should be enclosed between `[:` and `:]`(see emacs manual), the correct pattern is
```
^\([[:digit:]]\)
```
Since you have a single group you can skip the parentheses and refer to the whole match with `\&`, e.g:
```
^[[:digit:]] → ** \&
```
---
Tags: regular-expressions
---
|
thread-53380
|
https://emacs.stackexchange.com/questions/53380
|
Replace a block of code with another
|
2019-10-26T19:18:01.393
|
# Question
Title: Replace a block of code with another
How can I replace a block of code with another, akin to `query-replace`/`query-replace-regexp`?
For example:
Replacing the following block:
```
for(A) {
if(B) {
s1;
} else {
C;
}
}
```
with
```
for(M) {
if(N) {
s1;
} else {
O;
}
}
```
# Answer
> 1 votes
You could use iedit for that.
image source: iedit github repository
You should select your block of code and activate `iedit-mode` (`C-;`) to edit it.
> When Iedit mode is turned on, all the occurrences of the current region in the buffer (possibly narrowed) or a region are highlighted. If one occurrence is modified, the change are propagated to all other occurrences simultaneously.
>
> If region is not active, ‘iedit-default-occurrence’ is called to get an occurrence candidate, according to the thing at point. It might be url, email address, markup tag or current symbol(or word).
>
> In the above two situations, with digit prefix argument 0, only occurrences in current function are matched. This is good for renaming refactoring in programming.
After install `iedit-mode` from MELPA, I encourage you to read the full help (`C-h f` `iedit-mode`).
# Answer
> 0 votes
The `query-replace-regexp` does the job.
---
Tags: replace
---
|
thread-53373
|
https://emacs.stackexchange.com/questions/53373
|
stock alternatives to popup?
|
2019-10-26T11:51:50.507
|
# Question
Title: stock alternatives to popup?
I am using `popup-tip` and `popup-menu*` from the http://melpa.org/#/popup library in my extension, but I'd like to use something in stock Emacs so that I can remain zero dependencies.
The built in `popup-menu` (i.e. `x-popup-menu`) and `x-show-tip` don't work for me because they are mouse-centric (i.e. they show the popup at the mouse location) but I need `point` centric (i.e. popup where the point is) because that's where the user's gaze is centered when the popup appears.
# Answer
> 1 votes
The only problem you mention with the "stock" solutions are the positioning. For `popup-menu` you can provide the position you got from `posn-at-point` so it appears "at point" instead of "at mouse position". For `x-show-tip` you need a bit more plumbing to take out the x/y position out of the "posn" and pass it to `x-show-tip`.
# Answer
> 0 votes
I did a little POC that I derived from showtip. It does not depend on any external libs:
```
(defvar tip-timeout 1)
(defvar tip-parameters
'((name . "tip")
(internal-border-width . 2)
(border-width . 1)
(no-special-glyphs . t)
(foreground-color . "white")
(border-color . "white")
(background-color . "gray")))
(defun tip-frame-parameter (&rest args)
(let ((fp (apply #'frame-parameter args)))
;; this seems to be a bug on my system
;; (frame-parameter nil 'left) => (+ -1)
(if (numberp fp) fp 0)))
(defun tip-posn-at-point (&optional pos window)
"Return xy positions of top left corner of glyph a POS.
POS is relative to top left corner of frame containing WINDOW and
defaults to the pos of point in the selected window."
(let* ((window (or window (selected-window)))
(xy (posn-x-y (posn-at-point pos window)))
(edges (window-inside-pixel-edges window)))
(cons (+ (car xy) (car edges))
(+ (cdr xy) (cadr edges)))))
(defun tip (text &optional pos timeout window fg bg)
"Show TEXT in tooltip.
Show tooltip at buffer position POS which defaults to point in
WINDOW which defaults to the selected one.
Hide tooltip after TIMEOUT which defaults to `tip-timeout'.
FG, BG can be used to override foreground and background color
parameters of `tip-parameters'."
(let* ((xy (tip-posn-at-point pos window))
(params tip-parameters)
(left (+ (tip-frame-parameter nil 'left)
(car xy)))
(top (+ (tip-frame-parameter nil 'top)
(cdr xy)
(- (+ (if menu-bar-mode 25 0)
(if tool-bar-mode 35 0)
;; WHY?
40)
(if header-line-format
(frame-char-height) 0)))))
(when (stringp fg)
(setf (alist-get 'foreground-color params) fg)
(setf (alist-get 'border-color params) fg))
(when (stringp bg)
(setf (alist-get 'background-color params) bg))
(x-show-tip text
(selected-frame)
(append params `((left . ,left)
(top . ,top)))
(or timeout tip-timeout))))
```
---
Tags: popup
---
|
thread-53382
|
https://emacs.stackexchange.com/questions/53382
|
Punctuation abbrevs for writing prose, and automatic full stops at the end of line?
|
2019-10-26T21:13:05.910
|
# Question
Title: Punctuation abbrevs for writing prose, and automatic full stops at the end of line?
I'm a beginner Emacs user, and English isn't my first language so please bear with me.
I use Emacs for writing prose, and I need help with punctuation.
To put it short, I want to turn this:
--hello strangerRET
into this:
–Hello stranger.
I want to use dashes instead of quotations to write dialogue, either an en-dash and an em-dash. With other software, I have simply made an auto correction from two short dashes -- to a longer dash. But with Emacs an abbrev needs a space in the end, which I don't want to put there, also I haven't figured out how to make abbrevs with punctuation only.
I also need this to work with some form of automatic capitalization mode so that the mode understands the dash as the beginning of a word like it does with a quotation mark.
The reason I do it like this is the keyboard I use and the fact I have this method in my muscle memory from using it elsewhere.
Also, I'd like to get a fullstop at the end of a line if no other punctuation exists there.
One more thing, I know there is some key command that you can use to delete a selected block of text where it just sends it to the bottom of the buffer rather than killing it. Can somebody point me to it?
# Answer
One approach is to redefine the return command. Here is a command the does what you want I think. Then, I redefine in the org-mode keymap (you could do this in some other map if you use it.
```
(defun dash-return (&optional ignore)
(interactive "P")
(if ignore
(org-return)
(let ((p (point)))
(goto-char (line-beginning-position))
(cond
;; not on a quote so go back and return
((not (looking-at "--"))
(goto-char p))
;; on a quote, so
(t
;; replace -- with –
(setf (buffer-substring (point) (+ 2 (point))) "–")
;; Capitalize the first word
(capitalize-word 1)
;; Make sure there is a period at the end, skip spaces back t0 end.
(goto-char (line-end-position))
(skip-chars-backward " ")
(when (not (looking-back "[!?.]" 1))
(insert "."))))
(org-return))))
(define-key org-mode-map (kbd "RET") 'dash-return)
```
This should act like org-return when not on a line that starts with -- I think, and you can use C-u ret to avoid the reformatting.
For the other command you mentioned, I am not familiar with one, but here is a simple way to get that:
```
(defun send-region-to-end (r1 r2)
(interactive "r")
(let ((text (buffer-substring r1 r2)))
(delete-region r1 r2)
(save-excursion
(goto-char (point-max))
(insert "\n\n" text))))
```
> 0 votes
---
Tags: text-editing, writing, capitalization
---
|
thread-53400
|
https://emacs.stackexchange.com/questions/53400
|
When `emacs` is started, use `emacsclient` instead if there is a server
|
2019-10-27T17:37:57.927
|
# Question
Title: When `emacs` is started, use `emacsclient` instead if there is a server
Most modern editors don't have a separate `<editor>client` binary. Instead, the main binary acts as a client to open a new window/the file given as an argument when possible.
Is there a way to accomplish the same in Emacs? I know about `emacsclient` but 1. it's not a drop-in replacement and 2. using it comfortably requires additional setup beyond copying `.emacs.d` to a machine -- e.g. adding a desktop file for `emacsclient`.
I'm envisioning something like this:
```
;; Start of init.el
(if (server-running-p)
;; Open given file in existing server
(server-start))
```
# Answer
Nowadays several megabytes are no problem for a client program. So maybe the problem of the size of Emacs is no longer that relevant.
With Emacs 27 you can run stuff in `~/.emacs.d/early-init.el` before the initial frame opens. There you can try:
```
(require 'server)
(if (server-running-p "server")
(let ((file-name (expand-file-name (car (cdr command-line-args)))))
(unwind-protect
(server-eval-at "server" `(find-file ,file-name))
(kill-emacs)))
(message "Server not running."))
(server-start)
```
If you run `emacs somefile` when the Emacs server is already running `somefile` should be opened in the server.
This is just a proof of principle. The handling of the argument is very rudimentary. One has to refine the argument handling if one wants to use that principle for production.
I only have `emacs26` on my machine. Therefore, I cannot test the `early-init.el`-approach. If I put the above code into `~/.emacs` it opens the file given on the command line in the already running server but the client opens an initial frame before it runs the code. So there is some kind of flicker.
> 4 votes
# Answer
The `alternative-editor` option supports this. The following invocation does what you describe:
```
emacsclient -a""
```
This opens emacsclient, and starts the server if it isn't already running.
See the manual for details: https://www.gnu.org/software/emacs/manual/html\_node/emacs/Invoking-emacsclient.html
> 1 votes
# Answer
Would something like this work for you? You can save it as a script in `PATH` and run it instead of `emacs` or `emacsclient`.
```
#!/bin/bash
export REAL_EMACS_START=1
emacsclient $@ || emacs $@
```
**EDIT**:
If you want user to run `emacs` directly and achieve similar result, you can add the following to the top of `init.el`:
```
(unless (getenv "REAL_EMACS_START")
(call-process-shell-command
(format "export REAL_EMACS_START=1; (%sclient || %s) &" invocation-name invocation-name))
(kill-emacs))
```
> 0 votes
---
Tags: emacsclient, server
---
|
thread-53407
|
https://emacs.stackexchange.com/questions/53407
|
Insert trigonometric function to org file
|
2019-10-28T09:20:09.703
|
# Question
Title: Insert trigonometric function to org file
When inserting trigonometric function or other mathematics formulas,
I usually insert an image to org file as
Is it possible writing such a formula to org.
# Answer
Yes, by using Latex and preview that. Have a read at the org-mode manual org-latex-preview section.
There are embedded formulae like `$\sin(r) = 3\sin\left(\frac r3\right)-4\sin^3\left(\frac r3\right)$` or displayed formulae like
```
\begin{align}
\sin(r) = 3\sin\left(\frac r3\right)-4\sin^3\left(\frac r3\right)
\label{eq:MyFirstLaTeXEquation}
\end{align}
```
You can refer to the label in the last equation by `\eqref{eq:MyFirstLaTeXEquation}`.
LaTeX syntax is used in the formulae.
> 2 votes
---
Tags: org-mode, math
---
|
thread-22736
|
https://emacs.stackexchange.com/questions/22736
|
Org-mode: How to disable automatic doc-view on emacs-25
|
2016-06-03T13:35:17.223
|
# Question
Title: Org-mode: How to disable automatic doc-view on emacs-25
On
> GNU Emacs 25.1.50.2 (x86\_64-pc-linux-gnu, GTK+ Version 3.10.8) of 2016-04-25
> Org-mode version 8.2.10 (release\_8.2.10 @ /usr/share/emacs/25.1.50/lisp/org/)
opening a pdf file link (f.ex. `[[./9.pdf]]`) via `C-c C-o` automatically opens that file in docview-mode.
**How can this be disabled?** (Or is this a bug? Where to submit?)
# Answer
It happens because doc-view was added to `mailcap-mime-data`; I am using
```
(defun ensc/mailcap-mime-data-filter (filter)
""
(mapcar (lambda(major)
(append (list (car major))
(remove nil
(mapcar (lambda(minor)
(when (funcall filter (car major) (car minor) (cdr minor))
minor))
(cdr major)))))
mailcap-mime-data))
(defun ensc/no-pdf-doc-view-filter (major minor spec)
(if (and (string= major "application")
(string= minor "pdf")
(member '(viewer . doc-view-mode) spec))
nil
t))
(eval-after-load 'mailcap
'(progn
(setq mailcap-mime-data
(ensc/mailcap-mime-data-filter 'ensc/no-pdf-doc-view-filter))))
```
to remove corresponding entry.
This does not solve only the `org-mode` problem but allows e.g. to display PDFs in `gnus` using an external viewer.
> 3 votes
# Answer
> I wanted it to use the previous behavior: the system's pdf viewer.
Then restore the original value of the variable `org-file-apps` to contain:
```
((auto-mode . emacs)
("\\.pdf\\'" . default))
```
So whatever is the default viewer on your linux system will be used. To go back to doc-view, put this in your init file:
```
(add-to-list 'auto-mode-alist '("\\.pdf\\'" . doc-view-mode-maybe))
```
In any case, as others have pointed out, you'll have to bisect your init file to see what or where your defaults are being changed.
> 3 votes
# Answer
Assume you are using a Linux distro.
There are several ways to achieve the effects you want and each of them comes with advantages and disadvantages.
The simplistic way to achieve this is to set `org-file-apps` to:
```
((auto-mode . emacs)
("\\.mm\\'" . default)
("\\.x?html?\\'" . default)
("\\.pdf\\'" . "evince $s"))
```
The advantage of this approach is that it works and is just a change of variables, which is straightforward. The disadvantage is that you must specify which command to use for the types of file concerned. Another disadvantage is that the *evince* process is actually a child process of the running Emacs itself and this means the PDF reader has also to be closed when you exit Emacs.
After reading the documentation for `org-file-apps`, I am tempted to set it to:
```
((auto-mode . emacs)
(t . "xdg-open %s") ;; This does NOT work.
("\\.mm\\'" . default)
("\\.x?html?\\'" . default)
("\\.pdf\\'" . default))
```
The command `xdg-open` is used on most Linux distros for opening file with default app. See xdg-open.
The reason why it doesn't work can be answered by this line of code from `org-open-file`.
```
(start-process-shell-command cmd nil cmd)
```
The function `start-process-shell-command` actually executes `cmd` and then communicates with it using *pty* instead of *pipe*. See the doc for `process-connection-type`.
To walk around this, we can, however, use a function instead of a command string for default action.
```
(defun xdg-open (file link)
(let ((process-connection-type)) ; using pipe instead pty
(start-process
"xdg-open" nil "xdg-open" file)))
```
And set `org-file-apps` to:
```
((auto-mode . emacs)
(t . xdg-open)
("\\.mm\\'" . default)
("\\.x?html?\\'" . default)
("\\.pdf\\'" . default))
```
This way, whatever reader launched by `xdg-open` will not be a child process of running Emacs. They are independent of each other.
In fact, `xdg-open` is a very useful function by its own. You probably want to use `M-x xdg-open` or bind it to whatever key you like. To do that, you have to update it to:
```
(defun xdg-open (file &optional link) ; link is unused
(interactive "fFilename: ")
(let ((process-connection-type)) ; using pipe instead pty
(start-process
"xdg-open" nil "xdg-open"
(expand-file-name file)))) ; maybe unexpanded
```
Note that we have to expand the filename if we want to use `xdg-open` outside of `org-open-file`. The reason why previous version don't need to expand is that `org-open-file` expands the filename for us.
So far so good. And finally here comes my favorite approach using advising function.
By reading the source code of `org-open-file` carefully, we can find that it actually uses `find-file-other-window` to open the file as a fallback option. See L8579 of `org.el` and L235 of `ol.el`.
We can advise the function `find-file-other-window` with `xdg-find-file` (defined below) and leave the variable `org-file-apps` untouched.
```
(defun xdg-find-file (orig-fun &rest args)
(let* ((filename (car args)))
(if (cl-find-if
(lambda (regexp) (string-match regexp filename))
'("\\.pdf\\'" "\\.docx?\\'"))
(xdg-open filename)
(if (not (file-directory-p directory))
(make-directory directory t))
(apply orig-fun args))))
(advice-add 'find-file-other-window :around 'xdg-find-file)
```
In fact, we can also advise `find-file` around `xdg-find-file` so that it becomes Emacs-wide default action for opening PDF and Word file with system default application.
```
(advice-add 'find-file :around 'xdg-find-file)
```
The advantage of this approach is that this is an Emacs-wide solution. Not only `org-mode` calls `find-file` and `find-file-other-window`, but also many other Emacs packages relies on these two functions. Now I can even open a PDF with system default app by `C-x C-f`. In addition, I can control what kind of files to open with system default app.
To know more about advising function, see (elisp) Advising Functions.
> 2 votes
# Answer
The thing that determines what mode a file opens in is auto-mode-alist. So we just need to add something to that list that will tell Emacs to use a different mode.
What mode do you want .pdf files to open as? For this answer, I'll assume you want to use `fundamental-mode`. This won't render the pdf well, but you will be able to view the contents of the pdf. Add this code to your init file, and eval it or restart Emacs:
```
(add-to-list 'auto-mode-alist '("\\.pdf\\'" . fundamental-mode))
```
As mentioned, you'll want to replace `fundamental-mode` with the mode you want pdfs to open in.
> 0 votes
---
Tags: org-mode
---
|
thread-53410
|
https://emacs.stackexchange.com/questions/53410
|
How to get rid of ido-find-file
|
2019-10-28T10:59:06.837
|
# Question
Title: How to get rid of ido-find-file
I have recently switched from obsolete ibuffer-mode to ido mode, and it replaced `C-x C-f` command to ido-find-file with completions. I don't need it. How to revert it back to simple `find-file`?
I tried to set in configs:
```
(global-set-key (kbd "C-x C-f") 'find-file)
```
But it didn't help.
# Answer
> 3 votes
You need to delete the remap alist entry from `ido-minor-mode-map-entry`. To do that, run the function below once after enabling `ido-mode`.
```
(defun disable-ido-find-file-remap ()
(interactive)
(dolist (elt ido-minor-mode-map-entry)
(when (and (listp elt) (eq (car elt) 'remap))
(setf (cddr elt) (assq-delete-all 'find-file (cddr elt))))))
```
I looked at the source file `ido.el` to write that function.
*Remark:* if you press `C-f` while in `ido-find-file`, you can use `find-file` (without using my above function).
---
Tags: key-bindings
---
|
thread-53376
|
https://emacs.stackexchange.com/questions/53376
|
Reach to the extreme of font size in one step
|
2019-10-26T12:46:13.637
|
# Question
Title: Reach to the extreme of font size in one step
Usually to view the org or code in a bird view, I will decrease the font size to the extreme of minimal with M-x decrease, C-x z, z, z, z until reach the extreme.
Is it possible to reach the extremes of minimal or max in one step?
# Answer
You can define a new function that minimize the font size and bound it to an unused keybinding.
```
(defun my-text-scale-minimize ()
(interactive)
(text-scale-increase (text-scale-min-amount)))
(global-set-key (kbd "C-c -") #'my-text-scale-minimize)
```
If the font size is too small replace `(text-scale-min-amount)` with a negative integer.
To restore the original size use the built in keybinding `C-x C-0`.
> 1 votes
---
Tags: fonts
---
|
thread-53416
|
https://emacs.stackexchange.com/questions/53416
|
Draw pie chart from orgmode table
|
2019-10-28T14:52:20.113
|
# Question
Title: Draw pie chart from orgmode table
I'm trying to draw a pie chart from an orgmode table. Let's keep it as simple as possible.
```
#+TBLNAME:kuchen
| 100 | ABC |
| 3 | DEF |
| 123 | XYZ |
#+name: pie-chart (kuchen = kuchen)
#+begin_src R :file pie.png
pie(kuchen[,1], labels = kuchen[,2])
#+end_src
```
But the resulting pie.png is 0 Bytes, empty.
Error message:
```
Fehler in pie(kuchen[, 1], labels = kuchen[, 2]) :
Objekt 'kuchen' nicht gefunden
Ruft auf: <Anonymous> -> <Anonymous> -> pie
Ausführung angehalten
```
Translation: error in pie, object 'kuchen' not found, calls -\> -\> pie, execution halted
I found this guide: https://orgmode.org/worg/org-contrib/babel/intro.html#meta-programming-language . But if I simply copy the example given there into emacs and export it to html, the (in the case of the guide:) dirs.png is 0 Byte = empty as well.
At a first glance, this website seemed very helpful as well:
https://orgmode.org/worg/org-tutorials/org-R/org-R.html
But the given »actions« on a »intable« don't include any »pie« command.
Any ideas how to get a pie chart from an orgmode table?
If the table needed a third column with percentage, no problem. Any solution welcome.
# Answer
As mentioned in my comment, you need to pass the variable as a `:var` header on the `#+begin_src` line, *not* on the `#+name:` line. But you also need to specify that the results be output to a graphics file. The following worked for me:
```
#+TBLNAME:kuchen
| 100 | ABC |
| 3 | DEF |
| 123 | XYZ |
#+name: piechart
#+begin_src R :results file graphics :file pie.png :var kuchen=kuchen
pie(kuchen[,1], labels = kuchen[,2])
#+end_src
#+RESULTS: piechart
[[file:pie.png]]
```
> 4 votes
---
Tags: org-mode, r
---
|
thread-53418
|
https://emacs.stackexchange.com/questions/53418
|
Can I prevent export of an org subtree?
|
2019-10-28T15:22:53.203
|
# Question
Title: Can I prevent export of an org subtree?
I would like to have a section of my document for "Prep" - basically scripting stuff you need to have system wide in order run the document. It's not really relevant to anyone reading the document and I'd like to just have the entire subtree not included in exports. How would I do that?
# Answer
> 3 votes
As mentioned in my comment, there are tags that can be used to control the export of a (sub)tree: a tree that is tagged "noexport" will (by default) not be exported: e.g.
```
* Document
** Exported section
This section is not tagged, so it will be exported by default.
** Hidden section :noexport:
This section is tagged "noexport", so it will /not/ be exported.
```
The set of such tags is actually configurable, either globally through the value of `org-export-exclude-tags`, which is just a list of strings, or through the `EXCLUDE_TAGS` file-wide setting:
```
#+EXCLUDE_TAGS: noexport hidden classified
```
You can then use any of these tags to keep the tree from being exported.
As always, the manual is indispensable. These tags are discussed in the Export Settings section.
---
Tags: org-mode, org-export
---
|
thread-53429
|
https://emacs.stackexchange.com/questions/53429
|
What is this error? "Symbol's value as variable is void: nxml-mode-map"
|
2019-10-28T19:34:05.450
|
# Question
Title: What is this error? "Symbol's value as variable is void: nxml-mode-map"
I want to create a command and a keybind to scan with `tidy` a full buffer. The keybinding has to be active only when editing XML files.
In my `~/.emacs.d/init.el` file I've added the following lines:
```
(defun tidy-xml ()
"Tidies the XML content in the buffer using `tidy'"
(interactive)
(shell-command-on-region
(point-min) (point-max)
"tidy -i -w 72 -q -xml"
(current-buffer)
t
"*Error*"
t))
(define-key nxml-mode-map "\C-c t" 'tidy-xml)
```
But when I open Emacs it returns the following warning:
```
Warning (initialization): An error occurred while loading ‘/home/jim/.emacs.d/init.el’:
Symbol's value as variable is void: nxml-mode-map
```
I'm not able to see where the error is. Can you give me a hand?
# Answer
> 2 votes
The variable `nxml-mode-map` is defined in the library `nxml-mode`. This library is not yet loaded when you try to execute the form `(define-key nxml-mode-map "\C-c t" 'tidy-xml)`.
Replace that line with:
```
(eval-after-load "nxml-mode"
(lambda ()
(define-key nxml-mode-map "\C-c t" 'tidy-xml)))
```
That will delay the execution of the form contained in the lambda until the library `nxml-mode` is loaded.
---
Tags: init-file
---
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.