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-55784
|
https://emacs.stackexchange.com/questions/55784
|
How to check if a region is selected by mouse?
|
2020-02-25T18:50:04.513
|
# Question
Title: How to check if a region is selected by mouse?
Usually a mouse selected region is highlighted and a region set by (set-mark-command) is not highlighted. But I don't know a programmatic way to check it.
Could anyone help?
# Answer
> 1 votes
I think you have `transient-mark-mode` switched off. Without `transient-mark-mode` you do not get a highlighted region after setting `mark` with `C-SPC` and successive motion commands.
If the region is not highlighted, it is not active and `(region-active-p)` returns nil.
Even if the region is not active `(point)` and `(mark)` can give differing positions. That is the situation without `transient-mark-mode` when you have set `mark` with `C-SPC` and moved `point` away from that position.
See also `use-region-p` to neglect empty active regions.
# Answer
> 2 votes
Use **`(mouse-region-match)`**. `C-h f mouse-region-match` says:
> `mouse-region-match` is a compiled Lisp function in `mouse.el`.
>
> `(mouse-region-match)`
>
> Return non-`nil` if there's an active region that was set with the mouse.
# Answer
> 1 votes
Not 100% sure what you want to check for but if you wish to do something when the mouse has selected a region then here is one way to do it using Emacs advice functionality.
```
(defun register-mouse-select(&rest args)
(message "mouse select"))
(advice-add 'mouse-set-region :after #'register-mouse-select)
;;(advice-remove 'mouse-set-region #'register-mouse-select)
```
---
Tags: region, highlighting, mouse
---
|
thread-55757
|
https://emacs.stackexchange.com/questions/55757
|
query-replace{-regexp} fails in linux in a non-X terminal when I am in anything other than text mode
|
2020-02-24T22:59:57.903
|
# Question
Title: query-replace{-regexp} fails in linux in a non-X terminal when I am in anything other than text mode
I am running emacs 26.1 under linux. It has been working fine for over a year. Recently, I upgraded a lot of packages on my machine, but I did not upgrade nor alter emacs in any way. Now, `query-replace` and `query-replace-regexp` are failing when I run either of them in a non-X terminal with the `-nw` emacs command-line flag when not in `text-mode`. This failure never used to occur before my system upgrades. And it turns out that `query-replace{-regexp}` still work fine in all cases when I start emacs in an X window.
For example, suppose I have the following data in a file called `test.txt` ...
```
AAAA
BBBB
CCCC
DDDD
```
If I run `emacs -nw test.txt`, then position to the top of the file and run `(query-replace "AAAA" "XXXX")`, it works. However, if I run `(emacs-lisp-mode)` and then run `(query-replace "AAAA" "XXXX")` in the same way, I get this result (with `debug-on-error` set) ...
```
Debugger entered--Lisp error: (args-out-of-range #<buffer test.txt> 0 1)
buffer-substring-no-properties(0 1)
perform-replace("AAAA" "XXXX" t nil nil nil nil nil nil nil nil)
query-replace("AAAA" "XXXX")
eval((query-replace "AAAA" "XXXX") nil)
eval-expression((query-replace "AAAA" "XXXX") nil nil 127)
funcall-interactively(eval-expression (query-replace "AAAA" "XXXX") nil nil 127)
call-interactively(eval-expression nil nil)
command-execute(eval-expression)
```
However, if I leave off `-nw` and do all the same things in an X-Window instance of emacs, `(query-replace ...)` always works.
In other words, with `emacs test.txt` (*i.e.*, no `-nw` flag), I never get this problem with `query-replace`, no matter what mode I am running in.
This is not only specific to `emacs-lisp-mode`. The error with `query-replace` in a non-X terminal buffer also occurs for `sh-mode` and some other modes.
Does anyone know what could be causing this error and what I have to do to fix it?
Thank you in advance.
UPDATE:
This error does not occur when I am running from my system console (*i.e.*, no X services running at all). The errors I saw did occur in `xterm` and `urxvt` windows under my X desktop manager, even when I have explicitly unset `DISPLAY`.
It seems like there is something about running within an X desktop manager which is confusing emacs with regard to buffer attributes when running with `-nw`, even with `DISPLAY` unset.
And again, this problem only started happening a short time ago after updating a number of software components, but with *no* changes to emacs, at all. I have rebooted a few times since then, to no avail.
FURTHER UPDATE:
This error does not occur when I run `(replace-string "AAAA" "XXXX")`.
# Answer
> 1 votes
I ended up fixing the issue by building and starting to use `emacs-28.0.50`: https://github.com/emacs-mirror/emacs
I had to update some ancient, deprecated constructs in some of my old startup files so that this version of emacs would run. But in any case, this problem with `query-replace{-regexp}` doesn't exist in 28.0.50.
I still don't understand how making system changes outside of emacs could have caused this problem to suddenly appear in my stable-for-over-a-year `emacs-26.1`, but ...
```
Mine not to make reply,
Mine not to reason why,
Mine but to do and die.
```
(Apologies to Alfred, Lord Tennyson)
PS: `emacs-27.0.60` also works fine for me, without this problem.
# Answer
> 1 votes
FWIW (this isn't an answer; just more context)
In 26.3, the only call to `buffer-substring-no-properties` in `perform-replace` is:
```
(setq search-string-replaced (buffer-substring-no-properties
(match-beginning 0)
(match-end 0))
...)
```
So to get `buffer-substring-no-properties(0 1)` in the backtrace, we need `(match-beginning 0)` to return zero.
We're well into C code at that point, and establishing whether anything can ever set `search_regs.start[0]` to zero.
`perform-replace` does plenty with the match data, so I've not tried to figure out how that might happen.
---
Tags: buffers, query-replace, query-replace-regexp
---
|
thread-53723
|
https://emacs.stackexchange.com/questions/53723
|
Export table to CSV file without prompt
|
2019-11-14T05:50:48.500
|
# Question
Title: Export table to CSV file without prompt
I want to have tables that I can easily export to files. In this regard I want to associate a file path and a format to tables. This page in the docs is most relevant: https://orgmode.org/manual/Built\_002din-table-editor.html
I tried this to set the file path:
```
#+TABLE_EXPORT_FILE: 'data/observations.csv'
| day | observation |
|------------------+-------------|
| <2019-11-14 Thu> | cold |
| <2019-11-14 Thu> | warm |
```
And then running `org-table-export` but I still get the prompt asking for a file.
I am fine with a per-file setting of the file format, i.e.:
```
# Local Variables:
# mode: org
# org-table-export-default-format: orgtbl-to-csv
# End:
```
But it would be nice to set that as well on a per table basis.
I also would like a way to run this for all tables at once (ideally in combination with `org-babel-tangle`). I'll ask another Q for that if you want the points :)
# Answer
> 1 votes
The following Elisp code couples Org table export to csv/tsv with `org-babel-tangle`.
Tables with the following affiliated attribute are exported to data files on `org-babel-tangle`:
`#+ATTR_TANGLE: DATAFILE`
You can also specify the export type:
`#+ATTR_TANGLE: ("DATAFILE" "TYPE")`
```
(defun org+-tangle-table-at-point ()
"Tangle Org table at point.
The table is ignored if it is not preceeded by a line like:
#+ATTR_TANGLE: DATAFILE
or
#+ATTR_TANGLE: (\"DATAFILE\" \"TYPE\")"
(interactive)
(unless (org-at-table-p)
(user-error "Not at Org table"))
(let* (type
(data (org-element-context))
(parent (org-element-property :parent data))
file)
(while parent
(setq data parent)
(setq parent (org-element-property :parent data)))
(when (and (setq prop (org-element-property :attr_tangle data))
(setq file (read prop)))
(cond
((symbolp file)
(setq file (symbol-name file)))
((stringp file)) ;; keep it that way
((consp file)
(setq type (nth 1 file)
file (car file)))
(t
(user-error "Unexpected format of table to be tangled")))
(org-table-export file (or type org-table-export-default-format))
t)))
(defun org+-tangle-tables (fun &optional arg target-file lang)
"Tangle Org tables in current buffer.
For around advice with `org-babel-tangle' as FUN.
See `org-babel-tangle' for the args ARG, TARGET-FILE and LANG.
Currently, only one table per file is possible."
(cond
((equal arg '(4)) ;; at point
(if (org-at-table-p)
(org+-tangle-table-at-point)
(funcall fun arg target-file lang)))
((equal arg '(16))
(funcall fun arg target-file lang))
(t
(funcall fun arg target-file lang)
(let ((table-count 0))
(org-with-wide-buffer
(goto-char (point-min))
(while (re-search-forward "^[ \t\r]*|" nil t)
(goto-char (match-beginning 0))
(when (org+-tangle-table-at-point)
(cl-incf table-count))
(goto-char (org-table-end)))
)
(message "Tangled %d tables from %s." table-count (buffer-name))))))
(advice-add 'org-babel-tangle :around #'org+-tangle-tables)
```
Example Org source file with two exported tables:
```
#+ATTR_TANGLE: /tmp/test.dat
#+NAME: myTable
| test | table |
| first | row |
| second | row |
| third | row |
Some intermediate text.
Some src block:
#+BEGIN_SRC emacs-lisp :tangle /tmp/test.el
"Here I am."
#+END_SRC
#+ATTR_TANGLE: ("/tmp/test1.dat" "orgtbl-to-csv")
| another | table |
|---------+-------|
| 11 | 12 |
| 21 | 22 |
```
# Answer
> 2 votes
The doc you linked says:
> You may also use properties `TABLE_EXPORT_FILE` and `TABLE_EXPORT_FORMAT` to specify the file name and the format for table export in a subtree.
They are properties and not keywords. So you set them in the properties drawer of the subtree.
Example:
```
* Section with table
:PROPERTIES:
:TABLE_EXPORT_FILE: data/observations.csv
:TABLE_EXPORT_FORMAT: orgtbl-to-csv
:END:
| day | observation |
|------------------+-------------|
| <2019-11-14 Thu> | cold |
| <2019-11-14 Thu> | warm |
```
---
Tags: org-mode, org-export, org-table
---
|
thread-55795
|
https://emacs.stackexchange.com/questions/55795
|
How to configure a command to open in same-window unless already open in active frame?
|
2020-02-26T05:18:48.823
|
# Question
Title: How to configure a command to open in same-window unless already open in active frame?
I can use display-buffer-alist to configure a command to open in the same window:
```
(add-to-list 'display-buffer-alist '("*grep*" display-buffer-same-window))
```
The problem in this case, however, is if I then open a result and subsequently run a new search without closing the original window, Emacs will open a second view of the search results in the current buffer. That gives me two redundant views of the same results, which is obviously not my intention.
I would like this to be a bit smarter, in that if the buffer is already visible in the current frame, it should merely reuse it (or change focus to it), and display in the current window otherwise.
How can I achieve this behavior?
# Answer
> 1 votes
`display-buffer-alist` actions can be multiple functions (a list of functions), the first one which returns non nil is used.
So you can use:
```
(add-to-list 'display-buffer-alist '("*grep" (display-buffer-reuse-window
display-buffer-same-window)))
```
More info:
Emacs manual about ready availabe display-buffer actions
---
Tags: buffers, display-buffer-alist
---
|
thread-54798
|
https://emacs.stackexchange.com/questions/54798
|
How to refresh emacs server after changes to init file or packages?
|
2020-01-09T11:56:52.630
|
# Question
Title: How to refresh emacs server after changes to init file or packages?
I recently managed to get Emacs server to work. But after I worked on my init file and changed some code in one elpa package, the changes were not visible.
I did the load-file for `~/.emacs`, and bytecompiled the elpa directory. After this I could see the changes when I started `emacs -nw` from the terminal, but now when using `emacsclient`.
How could this be resolved? If I have to shut down and rerun the server, how do I do it? ( I set it to start at login with systemd)
# Answer
> 5 votes
Assuming you started it with `systemctl --user enable emacs.service`, you can restart it with:
`systemctl --user restart emacs`
That would kill all instances of `emacsclient` connected to the systemd emacs dameon, and restart the daemon.
All other systemctl commands work similarly, you can do `systemctl --user status emacs` to see logs.
# Answer
> 0 votes
The reason why `emacs -nw` worked, was because you started an complete new emacs instance which read the the whole config. The command `'emacs'` from bash would have done the same.
Beside restarting the whole emacs server and loosing all open buffers (as mentioned in another answer), you can also eval the recently changed code, from within an emacs client.
Functions like `M-x eval-buffer`, `M-x eval-defun` (`C-M-x`) or `M-x eval-last-sexp` (`C-x C-e`) will help you with that.
Evaling `defuns` again will owerwrite their old definition. When evaluating elisp code again, there are some catches because things like `defvar` behave special. (i.e. `defvar` does not change the value if it is non void)
So, restarting the whole emacs server would be the 100% solution unless you know what you are doing.
# Answer
> 0 votes
One way you can do it manually assuming systemctl isn't configured for emacs as suggested previously is to connect to the server instance using emacsclient as you usually do and then close it down:-
I use this:-
```
(defun server-shutdown ()
"Save buffers, Quit, and Shutdown (kill) server"
(interactive)
(save-some-buffers)
(kill-emacs))
(global-set-key (kbd "C-c x") 'server-shutdown)
```
Note, you can't hope to realistically update a running instance fully and properly without restarting. You are inviting trouble. Re-reading your startup will almost certainly not work for you.
As a side note, I hadn't realised that emacs26 on Debian 10 was indeed configured as a systemctl service - it is. Nice. Note that that call to (kill-emacs) is what the emacs.service "stop" directive actually calls too when invoking the following:-
```
systemctl --user stop emacs
```
Note that if you use the code I listed above to (kill-emacs) from a key binding AND emacs is configured and started as a service then it will automatically restart unless you use systemctl to stop it as shown just above.
For those that have an emacs.service in /usr/lib/systemd/user then you can enable this to autostart when you login (on Debian so your mileage may vary):-
```
systemctl --user enable emacs
```
And this will install a local use specific service link.
# Answer
> 0 votes
```
$ systemctl --user restart (or stop) emacs
```
is the kosher way from the pov of systemd.
For the Emacs user however, it will abruptly terminate the "service" losing all unsaved buffers – particularly the currently not visible ones.
Since this is highly undesirable, what I have is `kill-emacs` bound to a char (`X`) in `Buffer-menu-mode-map`.
Then instead of `C-x C-c` (which doesn't work as a full-kill for emacs-as-a-service) I use `C-x C-b` (look around) And `X` if all-clear.
---
# Added later
...but should have started with this :
`C-x C-c` which normally does `save-buffers-kill-emacs` instead does `save-buffers-kill-terminal` for emacs-service. This makes C-x C-c ineffective for a "reboor". M-x kill-emacs will however do what you wish but risks losing unsaved buffers.
---
Tags: emacs-daemon
---
|
thread-55744
|
https://emacs.stackexchange.com/questions/55744
|
Limit font-lock highliting to first N chars of line
|
2020-02-24T11:45:07.277
|
# Question
Title: Limit font-lock highliting to first N chars of line
I write regex for `font-lock` and I know that the date should appear in first 40 chars of line.
How can I limit search beyond some limit?
I tried to add `^.\\{0,40\\}XXX` but Emacs regex `.` is greedy and regex requires non-trivial rewriting to workaround greediness.
**UPDATE** I'm using `font-lock-add-keywords`
**UPDATE @Stefan** I have regex that skip optional date part, the only time part is required. With prefix `.\\{0,40\\}` date part is ignored (not highlighted). I can't use `[^-]` or `[^-[:digit:]]` because it is for log files and I don't know prefix in advance.
**My goal is to limit regex trying to parse long lines.**
**UPDATE 3** My regex:
```
(defvar log4-hi-time-keywords
'(("^.\\{0,40\\}\\(\\(:?[0-9]\\{2\\}?[0-9]\\{2\\}.[0-9]\\{2\\}.[0-9]\\{2\\}.\\|\\<\\)[0-9]?[0-9]:[0-9][0-9]:[0-9][0-9]\\>\\(:?\\.[0-9]\\{3\\}\\)?\\)" 1 'log4-hi-time-face))
"Highlight regex for partial ISO date.")
(font-lock-add-keywords nil log4-hi-time-keywords)
```
With addition of `^.\\{0,40\\}` only time part of `2020-02-23 13:39:03.215` is highlighted.
I hope regex isn't that scary.
# Answer
I think this is a job for a function in font-lock. It looks like your regular expression matches 0-40 characters, then a date, which does not sound like what you want at all. You want a date in the first 40 characters.
Here is a partial solution that matches dates like 2020-02-26 in the first 40 characters. If the date match goes outside the 40 chars, then it just searches again. This is lightly tested and seems to do what you want. You can replace the regexp with your more complex one, and the desired face.
```
(defun date-match (limit)
"Match date in the first 40 chars."
(when (re-search-forward "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\)" limit t)
(if (> (current-column) 39)
;; date is past 40 char, so search again
(date-match limit)
;; return non-nil so it continues
t)))
(font-lock-add-keywords
nil
'((date-match 0 font-lock-warning-face)))
```
> 1 votes
---
Tags: regular-expressions, font-lock
---
|
thread-55801
|
https://emacs.stackexchange.com/questions/55801
|
In Org-Mode, how to export to ASCII, maintaining capitalisation of the heading
|
2020-02-26T11:48:17.370
|
# Question
Title: In Org-Mode, how to export to ASCII, maintaining capitalisation of the heading
Whenever I export to ASCII, the heading always converts to all capitals. How can I maintain the original capitalisation?
# Answer
`upcase` is hard-coded into `org-ascii-template--document-title` of Org-version 9.2.6. The following Elisp code neutralizes that `upcase` by temporarily setting `upcase` to `identity`.
Note that one of the preconditions of the advice is that the source code of `ox-ascii` is available to Emacs. That is the case if you have installed the Melpa version of Org or you have installed the Elisp source package for Emacs. Under Ubuntu the Emacs Elisp source package is `emacs26-el`.
```
^;; -*- lexical-binding:t -*-
;; Lexical binding can become relevant for generalized variables
;; (see doc string of `gv-ref').
(require 'cl-lib)
(defcustom org+-ascii-upcase-title nil
"Default value for :"
:type 'boolean
:group 'org-export-ascii)
(eval-after-load 'ox-ascii
'(eval ;; Avoid expansion of `cl-pushnew' for place `org-export-backend-options' before ox-ascii is loaded.
'(cl-pushnew (list :ascii-upcase-title nil "ascii-upcase-title" 'org+-ascii-upcase-title)
(org-export-backend-options (org-export-get-backend 'ascii))
:test #'equal :key #'car)))
(defun org+-ascii-ignore-upcase (fun info)
"Neutralize `upcase' if :ascii-upcase-title is not set when calling FUN with INFO."
(if (assoc-string (plist-get info :ascii-upcase-title) '(yes t on))
(funcall fun info)
(cl-letf (((symbol-function 'upcase) #'identity))
(funcall fun info))))
(advice-add 'org-ascii-template--document-title :around #'org+-ascii-ignore-upcase)
```
You can switch on upcasing the title by the following option in your org file:
```
#+OPTIONS: ascii-upcase-title:t
```
Instead of `t` also the values `on` and `yes` work. Any other value such as `no` switches upcasing off. You can customize the default with the Elisp variable `org+-ascii-upcase-title`.
Tested with Emacs 26.3 and Org 9.2.6.
> 6 votes
---
Tags: org-mode, org-export
---
|
thread-55803
|
https://emacs.stackexchange.com/questions/55803
|
Using `C-n` and `C-p` to iterate as cycle in `find-file` instead of up/down arrow keys
|
2020-02-26T12:08:28.133
|
# Question
Title: Using `C-n` and `C-p` to iterate as cycle in `find-file` instead of up/down arrow keys
Following answer related to “Open Recent” in Emacs indicates that
> After you press C-x C-f, press up and down to navigate the history of opened files.
---
I have added following lines but they do not show cycle behavior like `up`, `down` arrow keys
It says: `beginning of history` or `end of defaults no next item`
```
(define-key minibuffer-local-map (kbd "C-n") 'next-history-element)
(define-key minibuffer-local-map (kbd "C-p") 'previous-history-element)
```
**\[Q\]** Instead of using `up` or `down` arrow keys, is it possible to use keybinding as `C-n`(down) and `C-p`(up) to iterate after typing `C-x C-f`?
# Answer
**Answer** (just giving Fish):
Yes of course it is, this is Emacs.
Bound to `up` and `down` during `find-file` are the commands `previous-line-or-history-element` and `next-line-or-history-element`. So you should try to bind these functions to `C-n` and `C-p`.:
```
(define-key minibuffer-local-map (kbd "C-n") #'next-line-or-history-element)
(define-key minibuffer-local-map (kbd "C-p") #'previous-line-or-history-element)
```
**Meta** (teaching how to fish):
Question: How did I know which function is bound? Answer: I used the built in help functions. You can always press `C-h k` and then the key to get the documentation of that keystroke. So I found out what the bound functions are. Question: How can I see what key shortcuts are available, currently? Answer: press `C-h m` it shows you the current mode documentation and key shortcuts.
**Related**:
Get familiar with the emacs help system here you can see available help commands
Consider using following packages (install them via MELPA and the package manager)
* ivy swiper counsel this enhances/replaces many default commands with more comfortable and autocompleting commands
* helpful a much improved help system
> 2 votes
---
Tags: isearch, history-variables
---
|
thread-55775
|
https://emacs.stackexchange.com/questions/55775
|
How can I resume swiper-isearch with the next line selected?
|
2020-02-25T13:48:26.197
|
# Question
Title: How can I resume swiper-isearch with the next line selected?
What I'm trying to do is have `swiper-isearch` resume the last search with the next element selected. The definition of next is the next element from where my cursor currently is.
You can read my original post below for how I was trying to use `ivy-resume` and `ivy-next-line` to achieve this, but it didn't work — it always resumed with the originally selected item still pre-selected.
---
*Original Post:*
# How can I resume ivy with the next line selected?
I want to issue a keyboard command that resumes the last ivy listing, but instead of resuming at the line it left off at, I want to resume with the next line selected. I thought this would be simple enough if I did the following:
```
(defun my-ivy-resume-with-next-line ()
"Resume the last completion and move current line down one."
(interactive)
(ivy-resume)
(ivy-next-line))
(global-set-key (kbd "s-g") 'my-ivy-resume-with-next-line)
```
When I hit my keyboard command, ivy resumes right where it left off — it does not go to the next line. I'm not sure if there's some simple elisp functionality that I should know to fix this, or if `ivy-resume` is doing something weird. My guess would be that maybe `ivy-next-line` is being called in my main buffer and not the newly created minibuffer from `ivy-resume`. (If that's the case, then this is a question of how to call that command in the context of the minibuffer.)
---
### Notes:
I have also tried various variations of the following for the message body per suggestions in the comments:
`(minibuffer-with-setup-hook (:append #'ivy-next-line) (ivy-resume))`
Nothing seemed to work for me in my testing. However, after hearing they were working for others, I changed which function I was using to create the initial ivy listing and it worked. So the minibuffer hook is working for me when ivy has been called using `counsel-find-file` but not when using `swiper-isearch`. My primary use case for this is to resume swiper and go to the next found item, so I still need help.
---
Software versions
* swiper 20200220.1026
* ivy 20200220.1043
* Emacs 26.3
* MacOS 10.15.3
# Answer
> 5 votes
I found a solution to what I was trying to do:
```
(defun my-swiper-isearch-again ()
"Start swiper-isearch with the last thing searched for."
(interactive)
(swiper-isearch (car swiper-history)))
(global-set-key (kbd "s-g") 'my-swiper-isearch-again)
```
Now when I press "s-g" the previous swiper search starts again from the point of the current cursor and moves then to the next item that matches the search.
---
Tags: minibuffer, ivy
---
|
thread-55702
|
https://emacs.stackexchange.com/questions/55702
|
Creating a local advice for a function
|
2020-02-22T13:05:29.357
|
# Question
Title: Creating a local advice for a function
I want to slightly modify the behaviour of a function, `old-function` whose source I cannot modify.
I can do that simply by
```
(defun my-new-function (old-fn a b c)
(if (evaluate-my-condition)
(funcall old-fun (my-transform a) b c)
(funcall old-fun a b c)))
(advice-add #'old-function :around #'my-new-function)
```
This works well. However, I would rather have this functionality as a buffer-local minor-mode since I rarely need this modified functionality.
Since `advice-add` works globally (as is pointed out here), is there another way to achieve this?
# Answer
> 7 votes
Let us collect the facts:
* The function cell of a symbol is **not** buffer-local. Therefore, if you want to change the behavior of the function buffer-locally you **need** a buffer-local variable or a hook-variable. A hook-variable has local values in buffers where `add-hook` with non-nil `LOCAL` argument is applied to them.
* Since you have no access to `old-function` whose behavior you want to modify you have only two options:
+ Redefinition
+ Advising
The promoted method is advising. So we stick to it.
* There are many variants how you can couple the advice and the buffer-local variable to get the desired effect.
Perhaps the simplest method:
```
(defun old-fun (a b c)
(interactive "sa: \nsb: \nsc: ")
(message "{(old-fun %s %s %s) in buffer %s}"
a b c
(current-buffer)))
(defun my-transform (a)
"Special transformation when `my-minor-mode' is active."
(message "{(my-transform %s) in buffer %s}" a (current-buffer)))
(define-minor-mode my-minor-mode
"Replace `old-fun' with `my-special-fun'.")
(defun around-old-fun (fun a b c)
"Override advice which replaces `old-fun' with `my-new-functions'.
Falls back to `old-fun' when no function is registered at `my-new-functions'."
(if my-minor-mode
(funcall fun (my-transform a) b c)
(funcall fun a b c)))
(advice-add 'old-fun :around #'around-old-fun)
```
The appearance of the advice in the doc-string of `old-fun` is a nuisance you have to endure in buffers where `my-minor-mode` is not active.
---
Appendix:
The simple implementation of `symbol-function` does not allow for buffer-local values:
```
DEFUN ("symbol-function", Fsymbol_function, Ssymbol_function, 1, 1, 0,
doc: /* Return SYMBOL's function definition, or nil if that is void. */)
(Lisp_Object symbol)
{
CHECK_SYMBOL (symbol);
return XSYMBOL (symbol)->u.s.function;
}
```
In contrast there follows the definition of `symbol-value`:
```
Lisp_Object
find_symbol_value (Lisp_Object symbol)
{
struct Lisp_Symbol *sym;
CHECK_SYMBOL (symbol);
sym = XSYMBOL (symbol);
start:
switch (sym->u.s.redirect)
{
case SYMBOL_VARALIAS: sym = indirect_variable (sym); goto start;
case SYMBOL_PLAINVAL: return SYMBOL_VAL (sym);
case SYMBOL_LOCALIZED:
{
struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (sym);
swap_in_symval_forwarding (sym, blv);
return (blv->fwd.fwdptr
? do_symval_forwarding (blv->fwd)
: blv_value (blv));
}
case SYMBOL_FORWARDED:
return do_symval_forwarding (SYMBOL_FWD (sym));
default: emacs_abort ();
}
}
DEFUN ("symbol-value", Fsymbol_value, Ssymbol_value, 1, 1, 0,
doc: /* Return SYMBOL's value. Error if that is void.
Note that if `lexical-binding' is in effect, this returns the
global value outside of any lexical scope. */)
(Lisp_Object symbol)
{
Lisp_Object val;
val = find_symbol_value (symbol);
if (!EQ (val, Qunbound))
return val;
xsignal1 (Qvoid_variable, symbol);
}
```
The line
```
struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (sym);
```
in `find_symbol_value` retrieves the buffer local value of the symbol.
---
Tags: advice, nadvice
---
|
thread-12477
|
https://emacs.stackexchange.com/questions/12477
|
How can I force "list-buffers" to use the other window
|
2015-05-18T00:33:42.403
|
# Question
Title: How can I force "list-buffers" to use the other window
When I type C-x C-b (i.e. the command list-buffers), how can I force it to list buffers in the other window? i.e. I typically have my screen split into 2 buffers. I am editing one buffer. I want a command which *always* lists buffers in the other window.
p.s. list-buffers used to always do this. But somewhere between emacs 24.3 and 24.5 it changed, so now it sometimes puts the buffer list in the current window.
# Answer
> 1 votes
I've discovered the command buffer-menu-other-window, which seems to do what I want. It'll take a few hours of use before I'm sure.
# Answer
> 0 votes
Yes, buffer-menu-other-window is the solution, rebind C-x C-b in your `.emacs` file and you can permanently restore the default behavior of earlier emacs releases.
```
(global-set-key "\C-x\C-b" 'buffer-menu-other-window)
```
---
Tags: buffers
---
|
thread-55810
|
https://emacs.stackexchange.com/questions/55810
|
Get window-total-width in another font
|
2020-02-26T20:06:03.473
|
# Question
Title: Get window-total-width in another font
`(window-total-width)` returns the number of columns (characters) that fit in the current window (https://www.gnu.org/software/emacs/manual/html\_node/elisp/Window-Sizes.html). This will take the current font into account. My header line or mode line might have a different font from the text area (window body). How can I get the number of columns (characters) that fit there instead?
# Answer
> 1 votes
```
(/ (window-pixel-width)
(window-font-width nil face))
```
will return the current window width for a given face.
---
Tags: window, fonts
---
|
thread-38306
|
https://emacs.stackexchange.com/questions/38306
|
File is missing: Cannot open load file, No such file or directory, ob-scala
|
2018-01-24T16:14:38.473
|
# Question
Title: File is missing: Cannot open load file, No such file or directory, ob-scala
After upgrading to emacs 27
```
brew install emacs --HEAD
```
I get this on startup
```
$(which emacs) --daemon
...
Warning (initialization): An error occurred while loading ‘/Users/username/.emacs.d/init.el’:
File is missing: Cannot open load file, No such file or directory, ob-scala
To ensure normal operation, you should investigate and remove the
cause of the error in your initialization file. Start Emacs with
the ‘--debug-init’ option to view a complete error backtrace.
....
```
# Answer
Looks like `ob-scala.el` was removed in Org 9.0.10: https://code.orgmode.org/bzg/org-mode/commit/90986a8e2fe881105cc6d869a7592581520646d2
It is now included in the `scala-mode` package on MELPA.
> 1 votes
# Answer
It's worth noting that emacs-scala-mode has removed `ob-scala` as `ensime` (that it depends on) is abandoned:
> 0 votes
---
Tags: org-mode
---
|
thread-55811
|
https://emacs.stackexchange.com/questions/55811
|
Customize org babel execution command in C
|
2020-02-26T21:00:08.290
|
# Question
Title: Customize org babel execution command in C
I have the following C code:
```
#include <stdio.h>
#include <math.h>
int main(){
printf("Square = %d", pow(4,2));
return 0;
}
```
Now if I run this in the shell. I would first compile with: `gcc -lm file.c -o a.out` and then run with `./a.out`.
If I run the above code in org mode within `#+BEGIN_SRC C` and `#+END_SRC`, I would get an error "undefined reference to pow".
Reason is that the compiling command has no link `-lm`. Is there a way to add this to org-babel execution of C code?
# Answer
> 1 votes
Use the `:flags` or `:libs` header to pass flags to the compiler (or libraries to the linker):
```
#+begin_src C :libs -lm
#include <stdio.h>
#include <math.h>
int main(){
printf("Square = %f", pow(4,2));
return 0;
}
#+end_src
```
See the Working with source code/Languages section of the Org mode manual. That contains a link to a page on Worg with links to details about specific headers for each of many languages: the specific page on C/C++/D can be found here.
Note that your program has a bug: `pow()` returns a double, so you need `%f` format, not `%d`.
---
Tags: org-babel, c, math
---
|
thread-55819
|
https://emacs.stackexchange.com/questions/55819
|
Circular list use of "#"
|
2020-02-27T07:10:14.690
|
# Question
Title: Circular list use of "#"
Looking at this, I see
```
(setq x '#1=(a #1#))
```
but this evaluates to `(a #0)`. As I understand, this should be `(a #1=(a #1#))`. But then what syntax makes `#0` mean `#1=(a #1#)`? In general what is `#` doing in the original `setq` form, then the returned list `(a #0)`?
Playing around, I see `(cadr (cadr (cadr x)))` always returns `(a #0)` which makes sense, but deepens the mystery.
# Answer
> 4 votes
The lisp printer needs to be set up to print Circular Objects. To do so you need to eval:
```
(setq print-circle t)
```
Then the output of eval `(setq x '#1=(a #1#))` will print as `#1=(a #1#)` (as expected).
Read more at the Manual
---
If you want to output and re-read Circular Objects, it would be unwise to unroll them while printing, because this would result in an infinite loop. So there has to be some syntactic expression, for how to print and read Circular Objects.
Within Common Lisp `#` often starts a reader macro, which changes the input before the compiler/interpreter sees it. (Some sort of a very sophisticated preprocessor from a C programmers perspective). With that it is possible to transform those expressions into memory objects, i.e. connect last list element with first.
ELisp has no reader macros, but I guess this special case is implemented somewhere in Emacs' C code. Why Elisp does not detect Circular Obejcts by default, I do not know. Probably some legacy and performance reasons.
---
Tags: list, syntax
---
|
thread-14659
|
https://emacs.stackexchange.com/questions/14659
|
CSV to Markdown table
|
2015-08-11T17:01:20.037
|
# Question
Title: CSV to Markdown table
Say we have a CSV in a buffer:
```
foo,bar,hello
1,234,95
8923,901,145
```
Are there any native Emacs or Markdown-mode built-ins in Emacs that can be used to convert it to a Markdown table? It looks like the syntax is quite different:
```
| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
```
# Answer
> 2 votes
The Melpa package archive has `markdown-mode`. My currently installed version is `markdown-mode-20180115.1905`. If you have added melpa to `package-archives` correctly you can install `markdown-mode` via `M-x` `package-install`.
After installation of `markdown-mode` files with extension `.md` are opened in `markdown-mode`.
If that mode is activated you find the submenu `Tables` in the `Markdown` menu. In there you find the menu item `Convert Region to Table`.
If you click that item after selecting the cvs table as region the cvs table is converted to a markdown table.
It is easy to add a header line. Just insert a newline after the first line, type `|-` and press `Tab`. The initial string `|-` is expanded to a full header line.
You only need to add the colons `:` yourself. Each time you modify the table in that way you can re-balance the table by pressing `Tab`.
# Answer
> 0 votes
You can easy to convert CSV To Markdown Table at tableconvert.com
Step 1. Click Import button and paste your valid csv data.
Step 2. Choose markdown output.
At the same time, your csv has been converted to markdown, you can copy the results to the clipboard
---
Tags: elisp-macros, formatting, markdown, csv
---
|
thread-55826
|
https://emacs.stackexchange.com/questions/55826
|
Pressing RET inserts unnecessary whitespace
|
2020-02-27T19:57:39.220
|
# Question
Title: Pressing RET inserts unnecessary whitespace
My Emacs inserts whitespace on the next line if the current line starts with whitespace. IE
```
a<RET>
<--- whitespace
```
This happens across modes (python, text-mode, fundamental-mode), and versions (24.5, 26.3). How do I get turn this off? (to be more like `nano` or `pico` behavior)? This messing with my terminal's copy-paste
# Answer
> 1 votes
In Emacs 25, they changed the default behavior of `RET`. Previously (prior to Emacs 25) `RET` just inserted a newline char (taking you to the beginning of the next line), and `C-j` did what `RET` does now: inserts a newline char and then indents according to the previous line's code.
You can restore the previous default behavior this way (it's what I do):
```
(when (fboundp 'electric-indent-mode)
(electric-indent-mode -1)) ; Use classic `C-j' and `RET'.
```
---
Tags: indentation
---
|
thread-55818
|
https://emacs.stackexchange.com/questions/55818
|
"Backspace" key sometimes also deletes forward in python-mode
|
2020-02-27T02:46:15.083
|
# Question
Title: "Backspace" key sometimes also deletes forward in python-mode
## Start Edit 1
To answer questions.
**Emacs Versions:**
* GNU Emacs 25.2.2 (x86\_64-pc-linux-gnu, GTK+ Version 3.22.21) of 2017-09-22, modified by Debian
* GNU Emacs 26.3 (build 1, x86\_64-w64-mingw32) of 2019-08-29
python-mode version (from `C-c C-v`) on both platforms:
* Using python-mode version 6.2.3
However, `M-x describe-package` for `python-mode` on the Windows shows:
```
python-mode is an installed package.
Status: Installed in python-mode-6.2.3/ (unsigned). Delete
Version: 6.2.3
Summary: Python major mode
Other versions: 6.2.3 (melpa).
[...]
```
Whereas on Linux, `M-x describe-package` for `python-mode` says I can install it (even though I'm using 6.2.3 as per `C-c C-v` above:
```
python-mode is an available package.
Status: Available from melpa -- [Install]
Archive: melpa
[...]
```
**Changing `backspace` behavior**
Changing `normal-erase-is-backspace` so that `backspace` deletes forward results in expected behavior (it deletes forward and not also backward), as far as I can tell, though the macro weirdness persists.
I am updating to the `Melpa` version `20200224.1148` on Linux and trying it out now to see if it changes anything.
**Output of `describe-key`**
**On Linux**
In `python-mode` on Linux, `C-h` deletes backward. I ran `M-x describe-key` on `Backspace` and got:
```
DEL runs the command delete-backward-char (found in global-map), which is an
interactive compiled Lisp function in simple.el .
It is bound to DEL.
(delete-backward-char N &optional KILLFLAG)
This function is for interactive use only;
in Lisp code use delete-char instead.
Delete the previous N characters (following if N is negative).
If Transient Mark mode is enabled, the mark is active, and N is 1,
delete the text in the region and deactivate the mark instead.
To disable this, set option delete-active-region to nil.
Optional second arg KILLFLAG, if non-nil, means to kill (save in
kill ring) instead of delete. Interactively, N is the prefix
arg, and KILLFLAG is set if N is explicitly specified.
When killing, the killed text is filtered by
filter-buffer-substring before it is saved in the kill ring, so
the actual saved text might be different from what was killed.
In Overwrite mode, single character backward deletion may replace
tabs with spaces so as to back over columns, unless point is at
the end of the line.
```
NB, `M-x describe-key` on `C-h` in `python-mode` results in nothing but prints `You can run the command describe-key with C-h k` (in `*Messages*` as well as the mini-buffer)
Whereas running `M-x describe-key-briefly` on `C-h` **AND** `Backspace` prints `DEL runs the command backward-delete-char-untabify` to the mini-buffer.
I am thoroughly confused.
**On Windows**
`C-h k Backspace` works! Go figure. I use the exact same `.emacs` and install packages using the Emacs package manager from `Melpa` on both OSes (they're in a Git repo). Output:
```
<backspace> runs the command py-electric-backspace (found in
python-mode-map), which is an interactive compiled Lisp function in
python-mode.el .
It is bound to <backspace>, <menu-bar> <Python> <Other> <Electric>
<Electric backspace>.
(py-electric-backspace &optional ARG)
Delete preceding character or level of indentation.
When delete-active-region and (use-region-p), delete region.
Unless at indentation:
With py-electric-kill-backward-p delete whitespace before point.
With py-electric-kill-backward-p at end of a list, empty that list.
Returns column reached.
[back]
```
`M-x describe-key` on `Backspace` does the same while `M-x describe-key` on `Backspace` prints `<backspace> runs the command py-electric-backspace`.
## End Edit 1
## Start Edit 2
A few more updates (so far ony trouble shooting on Linux):
* Looking at the output of `M-x describe-bindings` while in `python-mode` clearly shows `<backspace>` bound to `py-electric-backspace`
* Running `M-x py-electric-backspace` always does the right thing
* If I bind `py-electric-backspace` from within the buffer to some other key (e.g. by running `M-x eval-expression` then `(define-key python-mode-map "\C-n" 'py-electric-backspace)`), it works as expected.
* Removing all key-bindings in my `~/.emacs` does not solve this
* `M-x describe-bindings` also shows `<backspace>` mapped to `DEL` under the `Function key map translations:` section.
* Manually setting the `normal-erase-is-backspace` via `M-x set-variable` (`0 = Off`, `1 = Maybe`, `2 = On` or even `t` or `nil`) does nothing to solve the problem but does toggle `Backspace` between `Backspace` and `DEL`.
* Manually running `M-x normal-erase-is-backspace` turns `Backspace` into `C-h`
## End Edit 2
## EDIT 3 {
I don't believe the root of the problem has really been found. This problem manifests independently of any terminals. It also occurs in graphical Emacs. I decided to try to trace what Emacs was doing using a pre-command-hook:
```
(defvar *event-log* nil)
(defun log-commands nil
(let ((buf (current-buffer)))
(cl-push `(,buf ,this-command ,(this-command-keys))
*event-log*)))
(add-hook 'pre-command-hook 'log-commands)
```
This causes Emacs to log every single keypress to an in-memory list.
From there, I opened a Python source file and put the cursor where the block appears:
```
def foobar(baz,qux):
try:
quux.xyzzy()▋
except:
pass
```
From there, I added `.foobar` and then tried to delete it by pressing Backspace twice (enough to reproduce the behavior and also revert back to the correct behavior). The resulting event log, which is in reverse chronological order:
```
(#<buffer foobar.py> python-indent-dedent-line-backspace "^?")
(#<buffer foobar.py> delete-char "^D")
(#<buffer foobar.py> self-insert-command "r")
(#<buffer foobar.py> self-insert-command "a")
(#<buffer foobar.py> self-insert-command "b")
(#<buffer foobar.py> self-insert-command "o")
(#<buffer foobar.py> self-insert-command "o")
(#<buffer foobar.py> self-insert-command "f")
(#<buffer foobar.py> self-insert-command ".")
```
It clearly shows that the same key is being received as two distinct keys, and therefore it's executing two different functions. *Why* this happens remains a mystery, but because it can happen in a GUI session, we can rule out the possibility of terminal settings being to blame. Also note that it's impossible for things like terminal settings or X11 keymap bindings to suddenly change as a result of Emacs keypresses, and even if it was, the behavior would not be consistent between terminals, local X11 sessions, and X11-forwarded sessions.
## }
As the title says. Sometimes when I press `Backspace`, it deletes the character after the cursor (to the right) usually also deleting the character before it (to the left) in `python-mode`. This seems to happen only on some lines and after at least a 0.25 pause (does not happen when typing quickly).
I have only observed this in `python-mode`. At first, I thought it might be the `python-mode` and `elpy-mode` combo, but it persists with `elpy-mode` disabled and unloaded.
This seems to happen more frequently when within an f-string (python), at the end of a line, or at the end of a bracket or parentheses pair. I suspect that it might have something to do with hitting the `backspace` key when python-mode is "thinking" (e.g. trying to autocomplete).
Incidentally, `python-mode` also seems to make keyboard macros useless, causing all sorts of errors. I often find myself setting the buffer to `text-mode`, running a macro, and then setting it back to `python-mode`.
I've tried to set various py-\* variables that have to do with delaying or reducing autocomplete, but they don't seem to do anything.
I was not having all these problems with my old and now deprecated `python-mode`, but it is no more.
Apparently, there is no `python-mode` tag.
# Answer
> 2 votes
## Short Answer
Don't try to create one `.emacs` file for all your environments and conditions under which you might access them unless you have time on your hands.
Longer answer for those who might be in a similar circumstance...
## How to troubleshoot
Thanks to the input from commenters and others. I'm putting things that helped be get to some of the issues.
* Check which keypresses Emacs is getting.
+ In a Linux terminal, you can use `showkey`
+ In Emacs, `command-line-mode` from `Melpa` may help.
+ On Windows, you may also want to check out KeyPose
+ Note `xev` may be useful if you're running Emacs using X11 remotely.
* Check your key-bindings in Emacs:
+ Run `M-x describe-bindings` to list all the key bindings in the current buffer.
+ Run `C-hk<key>` or `M-x describte-key` then press `<key>` where `<key>` is the key you want to check.
+ Try running `M-x normal-erase-is-backspace`
+ Try running `M-x set-variable` on `normal-erase-is-backspace` and setting it:
- 0 = Off
- 1 = Maybe
- 2 = On
+ Check your `.emacs` for any `global-set-key`, `define-key` or similar statements
Know that how (as a GUI or in a terminal with '-nw' etc.), in which environment (Linux, Mac, Windows, WSL) and from where you are accessing it (directly on the computer, through command-line ssh, through PuTTy/MobaXTerm, through RDP, TeamVewier, etc.) and more can affect which keys Emacs ultimately "sees".
## The Root of the Problem
Emacs was receiving different key-presses / characters depending on the system and my attempt to have one universal `.emacs` file to rule them all caused conflicting handling under different circumstances and modes.
For example, I noticed that in one instance (Emacs on Linux using MobiXTerm on Windows) the terminal was sending `^H` (aka `C-h`) instead of the keyboard `Backspace`, while in others (Emacs on Linux under XTerm) it was sending `Backspace` while in others still (Emacs under Ubuntu 18.0.4 under WSL thought remote connection, but not when on the same machine) Emacs was thinking it was getting `Delete`.
*Note:* I noticed the -back-and-forward delete issue also happening in `lisp-mode` during one of my configuration permutation attempts, so it seems at least likely that there would have been other major modes that would have had issues.
Although I am not 100% sure, I believe it was happening when the mode (e.g., `python-mode`), executed some time-delayed hooks for handling `Backspace`, `Delete`, or `C-h`, the disparate configurations caused some oddities. It always required a bit of a time-delay and appeared to happen in `python-mode` at the end-of-line or other mode-specific trigger cases like deleting characters at or around a character "closing" a mode syntax grouping (e.g., `)`,`]`, `}`, `"`, `'`, or backtick)
## My Solution
I was able to "fix" this by having different settings in different environments by making sure that Emacs was getting the keys it thought it was getting and expanding my `.emacs` a bit to do some more checking.
I was able to create a config that detects all scenarios I tested **except** WSL (Windows Subsystem for Linux), but for now, that case is rare enough that I did not bother to test it after testing the keystrokes.
Thanks to everyone for the troubleshooting help.
---
Tags: key-bindings, python, keystrokes, backspace
---
|
thread-55829
|
https://emacs.stackexchange.com/questions/55829
|
How to switch org-babel-execute-src-block to use y-or-n-p?
|
2020-02-28T04:58:21.813
|
# Question
Title: How to switch org-babel-execute-src-block to use y-or-n-p?
In short, I want org-babel's prompt to accept a single y/n keypress instead of typing it out and pressing enter, but I don't want to replace all such prompts globally.
I've seen information on changing to y-or-n-p as the global default via defalias, or turning off the prompt specific to org-babel completely via org-confirm-babel-evaluate, but not how to simply shorten the prompt. I see notes on yes-or-no.el for making functions customizable, but it doesn't seem like that applies to org-babel.
In this particular case (imho), it's important enough to preserve the prompt, but not important enough to justify typing 4 characters to do so each time.
I'm sure there's an easy way to do this, but I'm not finding it.
# Answer
`yes-or-no-p` is hard-coded into `org-babel-confirm-evaluate`. We override it with `y-or-n-p` locally for `org-babel-confirm-evaluate`:
```
(eval-when-compile
(require 'cl-lib))
(defun org+-substitute-yes-or-no-p (fun &rest args)
"Run FUN with ARGS and `yes-or-no-p' locally substituted by `y-or-n-p'."
(cl-letf (((symbol-function 'yes-or-no-p) #'y-or-n-p))
(apply fun args)))
(advice-add 'org-babel-confirm-evaluate :around #'org+-substitute-yes-or-no-p)
```
Note, that I also tried to set `org-confirm-babel-evaluate` to the function
```
(lambda (_lang _body)
(unless (y-or-n-p "Evaluate source block? ")
(signal 'quit '("Evaluation of source block aborted"))))
```
But that does not work nicely. It asks twice for `y-or-n-p` confirmation for each code block.
Tested with `emacs -Q` of version 26.3.
> 3 votes
---
Tags: org-babel, prompt
---
|
thread-55825
|
https://emacs.stackexchange.com/questions/55825
|
Organizing Latex macro file
|
2020-02-27T18:47:21.303
|
# Question
Title: Organizing Latex macro file
I'm looking for a way to organize and share my LaTeX macros file. Ideally, I would like to write an org-mode file to export
* as a documentation file in html or pdf for sharing
* as a bare macros.tex containing only the macros
For instance, the org-file would look like
```
* Number sets
lorem ipsum
#+BEGIN_SRC latex
\def\R{{\mathbf R}}
\def\C{{\mathbf C}}
\def\N{{\mathbf N}}
#+END_SRC
```
The output in LaTeX would contain only
```
\def\R{{\mathbf R}}
\def\C{{\mathbf C}}
\def\N{{\mathbf N}}
```
The output in html would display
> **Number sets**
>
> Lorum ipsem
>
> ```
> \def\R{{\mathbf R}}
> \def\C{{\mathbf C}}
> \def\N{{\mathbf N}}
>
> ```
Any idea ?
# Answer
> 3 votes
Found it. Thanks. The solution is
```
#+BEGIN_SRC latex :tangle yes :exports code
\def\R{{\mathbf R}}
\def\C{{\mathbf C}}
\def\N{{\mathbf N}}
#+END_SRC
```
When using the function *org-babel-tangle* I get my bare .tex file and normal export function of org-more yields the html file.
---
Tags: org-mode, latex
---
|
thread-55832
|
https://emacs.stackexchange.com/questions/55832
|
Emacs occasionally using wrong indent in python
|
2020-02-28T11:13:49.963
|
# Question
Title: Emacs occasionally using wrong indent in python
I have a bunch of python files (ie .py files), which I use Emacs to edit. However I keep having the issue where sometimes emacs will indent regions with 8 spaces instead of 4, and I can't figure out why.
For example, sometimes when I define a function and hit return, Emacs will indent the following code by 8 spaces instead of the usual 4, and pressing `TAB` will only allow me to cycle between 0 indent and 8 spaces. If I manually enter 4 spaces for the first line, then following ones will appear at the same 4-space indentation, but if I then want to say put in a for loop, I will have the same issue again with the following code being indented by 8 spaces relative to the for ...: command.
I can't seem to sort this out by changing anything in my `.emacs` file (though I have only been using Emacs for a few months so maybe I'm doing something wrong!) - I have tried putting in
```
(setq tab-width 4)
```
and
```
(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
(setq indent-line-function #'insert-tab)
```
which I found from answers to other people's questions, and neither of them have any impact. It's also an intermittent problem, it doesn't seem to happen for every file.
Hope someone can offer some help! And I apologise if this is a duplicate question, I searched around but couldn't find anyone else with the exact same issue so I don't think it is!
# Answer
I assume you always want an indentation with 4 spaces even if there are indents of width 8 lurking around in your python file.
Set `python-indent-guess-indent-offset` to nil and keep the default value 4 for `python-indent-offset`.
> 2 votes
# Answer
When taking other people's code, it's important to understand what it does.
For that you can use `C-h o` (aka `describe symbol`). E.g. `C-h o indent-tabs-mode RET` will tell you:
> Indentation can insert tabs if this is non-nil.
and `C-h o tab-width RET`:
> Distance between tab stops (for display of tab characters), in columns. NOTE: This controls the display width of a TAB character, and not the size of an indentation step. This should be an integer greater than zero.
So those won't help fix your problem.
Indentation rules and styles are different for each language, so you need to look for a setting that's specific to `python-mode`. In your case, I think Tobias is right that the most likely problem comes from `python-indent-guess-indent-offset`. Not sure how you could have found it, other than by doing something like `M-x customize-group RET python RET` which lets you see (and change) the customization variables of `python-mode`.
> 1 votes
---
Tags: indentation, python
---
|
thread-37967
|
https://emacs.stackexchange.com/questions/37967
|
How to disable lisp-interaction when starting Emacs?
|
2018-01-08T18:08:25.203
|
# Question
Title: How to disable lisp-interaction when starting Emacs?
When I open Emacs, the `*scratch*` buffer is in Lisp Interaction mode, but I don't want that. How can I make the buffer have a text mode instead of Lisp Interaction?
# Answer
> 15 votes
You can customize the value of `initial-major-mode`, which defaults to `lisp-interaction-mode`. Here's the variable's docstring:
> `initial-major-mode` is a variable defined in `startup.el`. Its value is `lisp-interaction-mode`
>
> Documentation:
>
> Major mode command symbol to use for the initial `*scratch*` buffer.
>
> You can customize this variable.
For the customize interface you can follow the link from `C-h``v` `initial-major-mode` `RET`, or use `M-x` `customize-option` `RET` `initial-major-mode` `RET` to get there directly.
Alternatively you could put something like this in your init file:
```
(setq initial-major-mode 'text-mode)
```
# Answer
> 4 votes
Rather than changing the mode of an Emacs stalwart *Scratch*, configure initial-buffer-choice.
C-h v initial-buffer-choice
---
Tags: start-up, scratch-buffer
---
|
thread-55838
|
https://emacs.stackexchange.com/questions/55838
|
Query replace regexp with a distant match?
|
2020-02-28T20:46:06.720
|
# Question
Title: Query replace regexp with a distant match?
I have a single transcript file for a set of course lectures I am watching. After doing some formatting on the file. I have it broken up into sets of lessons where the main heading is the lesson title and each subheading is the lecture title.
I'm trying to format this file in a way that is easily searchable when taking notes. Here is an example format:
```
--------------------------------------------------------------------------------
L01 - Introduction to Knowledge-Based AI
01 - Introductions
>> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
02 - Preview
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
.
.
.
22 - Final Quiz
Lorem ipsum dolor sit amet.
--------------------------------------------------------------------------------
L02 - Introduction to CS7637
01 - Preview
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
.
.
.
14 - 2x1 Matrices IV
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
33 - Final Quiz
Lorem ipsum dolor sit amet.
________________________________________________________________________________
L03 - Semantic Networks
01 - Preview
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
04 - Exercise Constructing Semantic Nets I
>> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
.
.
.
```
A few things of note:
* Each lesson is preceded by a line of `-` 80 characters long
* Each lesson is titled by `LXX` where `XX` is the lesson number
* The lecture are titled by a leading number.
* These numbers aren't necessarily sequential but monotonically increase.
I would like to be able to prepend all lecture titles with its respective lesson number so that I can query a specific chunk of text while watching the video. So my expected output would be
```
--------------------------------------------------------------------------------
L01 - Introduction to Knowledge-Based AI
L01E01 - Introductions
>> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
L01E02 - Preview
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
.
.
.
L01E22 - Final Quiz
Lorem ipsum dolor sit amet.
--------------------------------------------------------------------------------
L02 - Introduction to CS7637
L02E01 - Preview
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
.
.
.
L02E14 - 2x1 Matrices IV
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
L02E33 - Final Quiz
Lorem ipsum dolor sit amet.
________________________________________________________________________________
L03 - Semantic Networks
L03E01 - Preview
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
L03E04 - Exercise Constructing Semantic Nets I
>> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
.
.
.
```
I think something like a 2-part regexp replace would be something like
```
Find all instances of this match
C-u 80 - C-q C-j C-q C-j \(L[0-9]+\)
Then find all proceding instances of this match
\([0-9]+ - .*$\)
And replace it with
\1E\2
```
Is there a way to do this in emacs?
**UPDATE:**
I've managed to get a small bit of code that only accomplishes the replace a single time and then errors out, it might be a good start though:
```
(with-current-buffer "transcripts.txt"
(re-search-forward "--------------------------------------------------------------------------------
\\(L[0-9]+\\) - .*$")
(setq match (match-string 1))
(re-search-forward "E[0-9]+ - .*$")
(beginning-of-line)
(insert match))
```
# Answer
An advanced usage of `M-x` `query-replace-regexp` (or indeed non-query `M-x` `replace-regexp`) which achieves this is...
Replace: `^\(L?[0-9]+\) -`
With: `\,(if (string-match-p "^L" \1) (setq lesson \1) (concat lesson "E" \1)) -`
> 2 votes
---
Tags: regular-expressions, search, text-editing, replace, query-replace
---
|
thread-55413
|
https://emacs.stackexchange.com/questions/55413
|
org mode: how to expand <s after heading without indentation?
|
2020-02-10T18:04:43.613
|
# Question
Title: org mode: how to expand <s after heading without indentation?
I am using Org Mode version 9.3 with `(require 'org-tempo)` in my configuration.
---
**Observed behaviour:**
**A.**
Given
```
* Heading
<s
```
`TAB` **produces**
```
* Heading
#+begin_src
#+end_src
```
**B.**
Given
```
* Heading
Text
<s
```
`TAB` **produces**
```
* Heading
Text
#+begin_src
#+end_src
```
---
**Desired behaviour:**
Given
```
* Heading
<s
```
`TAB` **produces**
```
* Heading
#+begin_src
#+end_src
```
---
# Answer
For this particular case, the indentation resulting from the expansion of the structure template is probably caused by `org-tempo` respecting `org-adapt-indentation`, which is set to `t` by default. The "B" case appears to work because the indentation is already broken by the first line after the heading.
With `org-adapt-indentation`:
> Org assumes that you write outlines by indenting text in each node to align with the headline (after the stars).
With it TAB will indent to it, drawers and planning info will adapt to it, etc. And `org-tempo` structure templates too.
So, if you don't want this indentation in general, set `org-adapt-indentation` to nil. If you do, Org thus enables you to stick to this consistently in the structure template expansion from `org-tempo`.
There has also been a recent change in the master branch (hopefully soon available more generally) in response to a question about this default value (https://lists.gnu.org/archive/html/emacs-orgmode/2020-02/msg00326.html). When it comes, we'll have also value `headline-data` for `org-adapt-indentation` to indent planning, properties and logbook, but keep the contend unindented.
> 3 votes
# Answer
The package `org-structtempl.el` brings back the old structure template mechanism to Orgmode.
Therewith your desired behavior is the default.
The actual reason for extracting the old code from Org 9.1.14 and putting it in its own package `org-structtempl.el` is that the old mechanism was more general than that one of `org-tempo.el`. For an instance there is no way to mimic the following entry of `org-structtempl-alist` with `org-tempo.el`:
```
("m" "\\begin{align*}\n?\n\\end{align*}")
```
Furthermore, I had heavily customized the structure templates with the help of the advice-mechanism. That suddenly didn't work anymore when Org 9.2 was out. My customization does not interfere with the old functionality. Therefore, I plan to add it to `org-structtempl.el`. With my customization the following substitution is possible:
```
<s emacs-lisp :results silent
(cl-loop for i from 0 upto 3 do
(message "Structure templates are cool.")
)
```
With all that stuff marked as region, it is substituted by the following stuff when pressing `tab`:
```
#+BEGIN_SRC emacs-lisp :results silent
(cl-loop for i from 0 upto 3 do
(message "Structure templates are cool.")
)
#+END_SRC
```
Another feature of my modifications is that `TAB`-completion of a line only containing `<m` asks you for a LaTeX environment and substitutes it for the shortcut `<m`.
You can install `org-structtempl.el` by saving it somewhere into your `load-path` and adding the following lines to your init file:
```
(with-eval-after-load 'org
(require 'org-structtempl))
```
> 1 votes
---
Tags: org-mode
---
|
thread-55844
|
https://emacs.stackexchange.com/questions/55844
|
Weird behavior of LaTeX-section-label for chapter
|
2020-02-29T01:37:34.090
|
# Question
Title: Weird behavior of LaTeX-section-label for chapter
The default value of LaTeX-section-label is:
```
(("part" . "part:")
("chapter" . "chap:")
("section" . "sec:")
("subsection" . "sec:")
("subsubsection" . "sec:"))
```
However, *for chapter*, when typing C-c C-s, we get cha instead of chap:.
```
\chapter{asdf}
\label{cha:asdf}
```
# Answer
> 4 votes
If reftex is enabled and the variable `reftex-plug-into-AUCTeX` is not nil the value of `LaTeX-section-label`is ignored and `reftex-section-prefixes` is used. Its default value is
```
((0 . "part:")
(1 . "cha:")
(t . "sec:"))
```
---
Tags: auctex
---
|
thread-55771
|
https://emacs.stackexchange.com/questions/55771
|
How to include headers when exporting a message as PDF?
|
2020-02-25T12:10:49.207
|
# Question
Title: How to include headers when exporting a message as PDF?
As a follow-up to this question about exporting as PDF, I want to export a message as a PDF. One answer in that thread views the message in a browser window and I can then save as a PDF from the browser:
```
(add-to-list 'mu4e-view-actions '("ViewInBrowser" . mu4e-action-view-in-browser) t)
```
The other is similar but does the work behind the scenes with WebKit HTML to PDF. Here is one example of the output of the latter command:
Both miss the header fields, such as sender, date, and subject, and the message starts immediately at the body.
How can I include message headers when exporting to PDF?
# Answer
This was fixed in version 1.3. You can try the `mu4e~write-body-to-html` function in the master branch.
> 2 votes
---
Tags: mu4e, pdf
---
|
thread-55814
|
https://emacs.stackexchange.com/questions/55814
|
Using TRAMP through CyberArk Privileged Session Manager
|
2020-02-26T23:48:18.767
|
# Question
Title: Using TRAMP through CyberArk Privileged Session Manager
Normally it is very easy to convert ssh and scp commands into tramp format for access via `dired`.
For example
The command line
```
ssh username@hostname
```
will become
```
/ssh:username@hostname:
```
in emacs.
Unfortunately, I'm unsure how to convert even the simplest CyberArk example command for use with tramp:
```
ssh username@target-username@target-hostname@cyberark-psm-hostname
```
### Question
How will I be able to use TRAMP to connect via SSH when proxying through a CyberArk Privileged Session Manager server?
> I found out this week I will not have access to CyberArk PSM for several more months so I will not be able to test any solutions on my own. My hope is that someone in the community has already figured out how to do this and will share their expertise. Thank you!
# Answer
I've never heard of CyberArk Privileged Session Manager, but from your description adding it to `tramp-methods` shouldn't be too hard. The simplest way is probably to add an entry with
```
(add-to-list 'tramp-methods
("psm"
(tramp-login-program "ssh")
(tramp-login-args
(("-l" "username")
("-p" "%p")
("%c")
("-e" "none")
("%u@%h@cyberark-psm-hostname")))
(tramp-async-args
(("-q")))
(tramp-remote-shell "/bin/sh")
(tramp-remote-shell-login
("-l"))
(tramp-remote-shell-args
("-c"))))
```
Then you can use it by opening `/psm:target-username@target-hostname:…`.
> 1 votes
---
Tags: tramp, ssh, proxy
---
|
thread-30204
|
https://emacs.stackexchange.com/questions/30204
|
How to tell Helm to ignore certain files?
|
2017-01-25T20:54:09.653
|
# Question
Title: How to tell Helm to ignore certain files?
There are certain files I never access from Helm, such as those in my global .gitignore file:
```
# Emacs backup files #
##############################
*~
*#
```
etc.
Is there any way of telling Helm to ignore these files?
# Answer
> 4 votes
This doesn't exactly answer your question directly, but if you are working on something Projectile recognizes as a project, you could try using `helm-projectile-find-file` instead of `helm-find-files`. The functionality is rather different (it searches all file names and paths in the project simultaneously, rather than letting you navigate to individual directories in the project), but it does have the benefit that it understands and uses `.gitignore` files.
# Answer
> 10 votes
I'm not sure when this functionality was introduced, but you can exclude files from `helm-find-files` by setting `helm-ff-skip-boring-files` to `t` and making sure the ignored pattern is on `helm-boring-file-regexp-list`. From its documentation:
> Non--nil to skip files matching regexps in `helm-boring-file-regexp-list`. This take effect in `helm-find-files` and file completion used by `helm-mode` i.e `helm-read-file-name`.
And the documentation for `helm-boring-file-regexp-list` says that by default it is built from `completion-ignored-extensions`.
# Answer
> 1 votes
For grepping, there's `helm-grep-ignored-files` and `helm-grep-ignored-directories`. There's nothing like that for `helm-find-files`.
# Answer
> 1 votes
search that respects ignored dirs/files:
1. install `ack` (An alternative to grep. I install via homebrew.)
2. put `--ignore-case` in your `~.ackrc` file (assuming you want to ignore case)
3. bind `helm-projectile-ack` to a key. I do this in my emacs init via:
```
(use-package helm
...
:bind (...
("C-c p s a" . helm-projectile-ack)
)
...
)
```
4. create a `.projectile` file. E.g.,
```
-.dot
-.jcs
-.svg
-.txt
```
use
```
C-c p s a ;; search that respects .projectile ignore
```
or
```
C-c s p g ;; search everything
```
# Answer
> 0 votes
Just to add something in relation to using grep type searching and ignoring/including that might be a help. I use this (and it can be used with git-grep and similar if you locate the correct flags):-
```
(defun helm-projectile-ag-search-all()
(interactive)
(let((helm-ag--extra-options "--skip-vcs-ignores"))
(helm-projectile-ag)))
(defun helm-projectile-rg-search-all()
(interactive)
(let((helm-rg--extra-args "--no-ignore-vcs"))
(helm-projectile-rg)))
```
ie override the default behaviour and do indeed search vcs ignored files... one key bound to helm-projectile-rg directly and the S-thatkey to helm-projectile-rg-search-all.
M projectile use-package is:-
```
(use-package
projectile
:demand t
:config
(use-package
helm-projectile
)
(defun helm-projectile-ag-search-all()
(interactive)
(let((helm-ag--extra-options "--skip-vcs-ignores"))
(helm-projectile-ag)))
(defun helm-projectile-rg-search-all()
(interactive)
(let((helm-rg--extra-args "--no-ignore-vcs"))
(helm-projectile-rg)))
(helm-projectile-on)
(projectile-global-mode)
:bind ("<f2>" . 'projectile-dired)
("<f3>" . 'helm-projectile-rg)
("S-<f3>" . helm-projectile-rg-search-all)
("<f4>" . 'helm-projectile-find-file-dwim)
("<f5>" . 'helm-projectile-switch-to-buffer)
(:map projectile-mode-map ("C-c p" . projectile-command-map))
(:map projectile-command-map ("o" . helm-multi-swoop-projectile))
(:map projectile-command-map ("g" . helm-git-grep))
)
```
---
Tags: helm, helm-selection
---
|
thread-55854
|
https://emacs.stackexchange.com/questions/55854
|
How do I disable savehist-autosave in emacs?
|
2020-03-01T14:20:30.967
|
# Question
Title: How do I disable savehist-autosave in emacs?
Because my emacs editor has become completely unreliable / unusable due to the frequent freezes - I'd like to disable this. But I can't figure out how?
The actual issue is described by myself and others here: https://github.com/syl20bnr/spacemacs/issues/9409
When I tried searching for this online:
This page offers no solution: https://www.gnu.org/software/emacs/manual/html\_node/efaq/Disabling-auto\_002dsave\_002dmode.html
It only directs you to https://www.gnu.org/software/emacs/manual/html\_node/emacs/Auto-Save.html#Auto-Save which also has no solution
# Answer
To disable `savehist-mode`, which is a *global* minor-mode, one can use: `(savehist-mode -1)` When disabling `savehist-mode`, the function `savehist-uninstall` is called ... `savehist-minibuffer-hook` is removed from the `minibuffer-setup-hook`, and `savehist-autosave` is removed from the `kill-emacs-hook`, and the timer `savehist-timer` is canceled.
However, `savehist-mode` is *not* enabled in Emacs 26 by default. Therefore, the better approach would be to find out where in the user-configuration of the original poster `savehist-mode` is being enabled and remove that line of code or comment it out. The easiest method would be to use `grep` and search for the term `savehist-mode`.
`savehist-mode` has been around for ages and it is highly unlikely it is responsible for making Emacs freeze frequently. Turning it off for purposes of troubleshooting, however, may be a worthwhile endeavor.
The best approach is to try and get a backtrace when Emacs freezes. If pressing `C-g` does not suffice, then consider building Emacs from source and launching Emacs under `gdb` ... with the terminal starting directory being the `src` directory so that the `.gdbinit` gets loaded. Then, when Emacs freezes, you can force a backtrace ... which is beyond the scope of this answer.
> 3 votes
---
Tags: auto-save, savehist-mode
---
|
thread-55218
|
https://emacs.stackexchange.com/questions/55218
|
Make 'ctags' detect fortran's "module procedure" pattern?
|
2020-01-31T14:39:50.643
|
# Question
Title: Make 'ctags' detect fortran's "module procedure" pattern?
I am using `ctags` to index fortran files for code navigation in Emacs with `M-.`.
In doing so I have noticed that it doesn't recognize declarations of the form
```
MODULE PROCEDURE MySubroutineName ! or
MODULE SUBROUTINE MySubRoutineName
```
which arise when using the `SUBMODULE` feature.
In "https://stackoverflow.com/questions/3497538/ctags-and-fortrans-interfaces" a similar issue occurred, but there the solution was merely to enable a feature, that isn't enabled by default. For submodules no such feature exists.
Is it possible to make ctags aware of this construct?
# Answer
ctags supports regular expression which could be used to parse tags.
Add below code into `~/.ctags`,
```
--regex-fortran=/^[ \t]*MODULE[ \t]+(PROCEDURE|SUBROUTINE)[ \t]+([a-zA-Z0-9_]+)/\2/s,subroutines/
```
`hello.f` is like,
```
MODULE PROCEDURE MySubroutineName1 ! or
MODULE SUBROUTINE MySubRoutineName2
```
Then run `ctags -e hello.f` to test.
See https://duckduckgo.com/?q=ctags+regular+expression&t=ffab&atb=v202-1&ia=web on regular expression syntax.
Please note exuberant-ctags will load `~/.ctags` by default but universal-ctags loads `~/.ctags.d/*.ctags` instead of `~/.ctags`. So you might need run `ln -s ~/.ctags ~/.ctags.d/1.ctags` if you replace exuberant-ctags with universal-ctags.
> 1 votes
# Answer
The issue occurred, because `ctags` on my system was the "Exuberant Ctags" implementation, whose latest version is from 2009; The language feature I needed support for was standardized only in 2008.
I solved the issue by asking the administrator to install "Universal Ctags", which should be the best-maintained variant of `ctags`.
---
I'll leave this question open in the hope that someone knows a way to add support, when using a newer ctags implementation isn't possible (e.g. tight software guidelines in a company, or when encountering a feature not yet supported out of the box by any implementation).
> 0 votes
---
Tags: ctags, xref, etags, fortran
---
|
thread-46479
|
https://emacs.stackexchange.com/questions/46479
|
How to set a tangled parent directory for each subtree in org mode?
|
2018-12-08T11:34:25.680
|
# Question
Title: How to set a tangled parent directory for each subtree in org mode?
Base on this, one can set a global tangled file.
However, I'd like to set one directory for each subtree, e.g. for a `* Python` subtree, in every code block I can set `:tangle a.py` or `:tangle b.py` instead of `:tangle python/a.py` and `:tangle python/b.py`.
Any help will be appreciated.
# Answer
> 3 votes
# Overview
This answer uses Emacs Org Mode with its noweb syntax and tangling to generate this answer. Included below is the original Org mode file text to use as a starting point.
This answer was tangled using Emacs version 26.3 and Org Mode version 9.3.6.
## Define the org-in-tangle-dir Elisp function
Define the following function in your `init.el` file<sup>1</sup> so that it is reusable in multiple Org files upon the next time you reinvoke Emacs<sup>2</sup>:
```
(defun org-in-tangle-dir (sub-path)
"Expand the SUB-PATH into the directory given by the tangle-dir
property if that property exists, else use the
`default-directory'."
(expand-file-name sub-path
(or
(org-entry-get (point) "tangle-dir" 'inherit)
(default-directory))))
```
You can define that function interactively by marking the entire function definition, and typing:
```
M-x eval-region
```
## Use `org-in-tangle-dir` Elisp function with the `tangle` header argument
Now that the `org-in-tangle-dir` Elisp function is defined in your Emacs, you can use the function to provide the value to the `tangle` header argument in your source blocks in multiple Org files. The documentation states:
> FILENAME Export the code block to source file whose file name is derived from any string passed to the ‘tangle’ header argument. Org derives the file name as being relative to the directory of the Org file’s location. Example: ‘:tangle FILENAME’.
The **key** here is to not hardcode the `FILENAME` but generate it's value dynamically during tangling via the call to `org-in-tangle-dir`.
Each heading can optionally define its own `tangle-dir` property. If it is not defined within the property drawer of that heading, `org-in-tangle-dir` searches all property drawers in each parent heading for the property. If the property is not found in any parent heading, it will use the current working directory of the Org file (which would have the same effect as not specifying `tangle` header argument).
You can set properties into the current heading property drawer using `C-c C-x p` (see org-set-property), and you can enter in `tangle-dir` followed by the path to the tangle directory.
Once you have defined all `tangle-dir` properties you would like to define, type in the `C-c C-v C-t` which calls `org-babel-tangle` to tangle the buffer into the directories given by the `tangle-dir` properties.
It generates the main `tangle-dir` in the top-most heading, and a few subdirectories within that due to the subheadings below it. There is no particular reason why they have to be all within the same directory hierarchy; if you were to put them into other directories you could do so provided your user account has write-access to them.
Here are the resulting files. You would have to "tangle" twice (with `C-c C-v C-t`) to see this output, as the first time generates it and the second time would see that existing output (chicken-and-egg-problem):
```
/tmp/emacs.stackexchange.com.answer
├── answer.txt
├── some.dir.1
│ ├── HelloWorld.py
│ └── some-text-file1.txt
└── some.dir.2
├── some-bash-script2.sh
└── some-text-file2.txt
2 directories, 5 files
Up to 10 lines of each generated file are shown below:
FILE: /tmp/emacs.stackexchange.com.answer/answer.txt
1 # Overview
2
3 This answer uses Emacs Org with its [noweb syntax][1] and [tangling][2] to
4 generate this answer. Included below is the original Org mode file
5 text to use as a starting point.
6
7 This answer was tangled using Emacs version 26.3 and
8 Org Mode version 9.3.6.
9
10 ## Define the org-in-tangle-dir Elisp function
FILE: /tmp/emacs.stackexchange.com.answer/some.dir.1/HelloWorld.py
1 """This is a hello world example document"""
2 print("Hello World from Python!")
FILE: /tmp/emacs.stackexchange.com.answer/some.dir.1/some-text-file1.txt
1 This is the python script to be generated into a text file inside yet another directory
2
3 """This is a hello world example document"""
4 print("Hello World from Python!")
5
6 Executing that script gives the expected output:
7
8 Hello World from Python!
FILE: /tmp/emacs.stackexchange.com.answer/some.dir.2/some-bash-script2.sh
1 #!/bin/bash
2 echo "A Bash script is executing."
FILE: /tmp/emacs.stackexchange.com.answer/some.dir.2/some-text-file2.txt
1 This is the bash script to be generated into a text file inside yet another directory
2
3 echo "A Bash script is executing."
4
5 Executing that script gives the expected output:
6
7 A Bash script is executing.
```
# Example Org file
The Org file used to create this answer is shown below.
```
* TODO Example of per-heading tangled parent directories
:PROPERTIES:
:tangle-dir: /tmp/emacs.stackexchange.com.answer
:ID: bcdcf445-b38b-453b-8531-e6377c673b5d
:END:
Here is the answer text to tangle into the directory given by
`tangle-dir` of this Org heading, into the filename given in the call
to `org-in-tangle-dir` below (notice we are using the `:mkdirp` to ensure
that the output directory is created before writing to it; errors will
occur otherwise):
#+BEGIN_SRC text :noweb yes :tangle (org-in-tangle-dir "answer.txt") :exports none :mkdirp yes
# Overview
This answer uses Emacs Org Mode with its [noweb syntax][1] and
[tangling][2] to generate this answer. Included below is the original
Org mode file text to use as a starting point.
This answer was tangled using Emacs version <<emacs-version()>> and
Org Mode version <<org-mode-version()>>.
## Define the org-in-tangle-dir Elisp function
Define the following function in your `init.el` file<sup>1</sup> so
that it is reusable in multiple Org files upon the next time you
reinvoke Emacs<sup>2</sup>:
<!-- language: lang-el -->
<<org-in-tangle-dir>>
You can define that function interactively by marking the entire
function definition, and typing:
M-x eval-region
## Use `org-in-tangle-dir` Elisp function with the `tangle` header argument
Now that the `org-in-tangle-dir` Elisp function is defined in your Emacs,
you can use the function to provide the value to the `tangle` header
argument in your source blocks in multiple Org files. The
[documentation][2] states:
> FILENAME
> Export the code block to source file whose file name is derived
> from any string passed to the ‘tangle’ header argument. Org
> derives the file name as being relative to the directory of the Org
> file’s location. Example: ‘:tangle FILENAME’.
The **key** here is to not hardcode the `FILENAME` but generate it's
value dynamically during tangling via the call to `org-in-tangle-dir`.
Each heading can optionally define its own `tangle-dir` property. If
it is not defined within the property drawer of that heading,
`org-in-tangle-dir` searches all property drawers in each parent heading
for the property. If the property is not found in any parent heading,
it will use the current working directory of the Org file (which would
have the same effect as not specifying `tangle` header argument).
You can set properties into the current heading property drawer using
`C-c C-x p` (see [org-set-property][3]), and you can enter in
`tangle-dir` followed by the path to the tangle directory.
Once you have defined all `tangle-dir` properties you would like to
define, type in the `C-c C-v C-t` which calls `org-babel-tangle` to
tangle the buffer into the directories given by the `tangle-dir`
properties.
It generates the main `tangle-dir` in the top-most heading, and a few
subdirectories within that due to the subheadings below it. There is
no particular reason why they have to be all within the same directory
hierarchy; if you were to put them into other directories you could do
so provided your user account has write-access to them.
Here are the resulting files. You would have to "tangle" twice (with
`C-c C-v C-t`) to see this output, as the first time generates it and
the second time would see that existing output (chicken-and-egg-problem):
<<show-directory()>>
# Example Org file
The Org file used to create this answer is shown below.
<<this-org-file()>>
<sup>1</sup> https://emacs.stackexchange.com/questions/12938/how-can-i-evaluate-elisp-in-an-orgmode-file-when-it-is-opened/12958#12958
describes using File Local variables to define functions like as done
above, but they are considered by some to be a security risk. Even if
it was not a security risk, you may still find them annoying if you need to
use them in multiple Org files. Also, because they only work at the
end of the file which tends to get appended to with new child
headings, leaving the File Local Variables in the middle of the file
where they are likely to not be missed by Emacs when it loads the
file the next time.
<sup>2</sup>The `org-in-tangle-dir` function could be included into
the Org mode itself in some manner.
[1]: https://orgmode.org/manual/Noweb-Reference-Syntax.html#Noweb-Reference-Syntax
[2]: https://orgmode.org/manual/Extracting-Source-Code.html#Extracting-Source-Code
[3]: https://orgmode.org/manual/Property-Syntax.html#Property-Syntax
#+END_SRC
See child headings below that demonstrate using different `tangle-dir` properties.
** Child heading 1
:PROPERTIES:
:tangle-dir: /tmp/emacs.stackexchange.com.answer/some.dir.1
:ID: 5957bdfc-26f1-43ba-807e-0088b7a86073
:END:
Reusing a trimmed down example from http://ehneilsen.net/notebook/orgExamples/org-examples.html#sec-25-1 :
#+NAME: the-python-script
#+BEGIN_SRC python :noweb yes :tangle :tangle (org-in-tangle-dir "HelloWorld.py") :exports none :mkdirp yes
"""This is a hello world example document"""
print("Hello World from Python!")
#+END_SRC
Because some may have a Conda python in my $PATH that is not in
/usr/bin, this calls the unqualified python to execute it. This reuses
`org-in-tangle-dir` again to locate it:
#+NAME: bashrun-the-python-script
#+BEGIN_SRC bash :results output :exports none :var script=(org-in-tangle-dir "HelloWorld.py")
python $script 2>&1
true # Ignore non-zero exit codes from any bugs in the script
#+END_SRC
Tangle a text file that shows the script and its resulting output:
#+BEGIN_SRC text :noweb yes :tangle (org-in-tangle-dir "some-text-file1.txt") :exports none :mkdirp yes
This is the python script to be generated into a text file inside yet another directory
<<the-python-script>>
Executing that script gives the expected output:
<<bashrun-the-python-script()>>
#+END_SRC
** Child heading 2
:PROPERTIES:
:tangle-dir: /tmp/emacs.stackexchange.com.answer/some.dir.2
:ID: 928b3f4f-b0e4-4647-93f7-11753911319d
:END:
Define a bash script:
#+NAME: the-bash-script
#+BEGIN_SRC bash :results output :noweb yes :tangle :tangle (org-in-tangle-dir "some-bash-script2.sh") :exports none :mkdirp yes :shebang "#!/bin/bash"
echo "A Bash script is executing."
#+END_SRC
Tangle a text file that shows the script and its resulting output:
#+BEGIN_SRC text :noweb yes :tangle (org-in-tangle-dir "some-text-file2.txt") :exports none :mkdirp yes
This is the bash script to be generated into a text file inside yet another directory
<<the-bash-script>>
Executing that script gives the expected output:
<<the-bash-script()>>
#+END_SRC
** Elisp definition of org-in-tangle-dir
This is the Elisp definition of org-in-tangle-dir:
#+NAME: org-in-tangle-dir
#+BEGIN_SRC emacs-lisp :results value
(defun org-in-tangle-dir (sub-path)
"Expand the SUB-PATH into the directory given by the tangle-dir
property if that property exists, else use the
`default-directory'."
(expand-file-name sub-path
(or
(org-entry-get (point) "tangle-dir" 'inherit)
(default-directory))))
#+END_SRC
** this-org-file block
The this-org-file block reads the current Org file:
#+NAME: this-org-file
#+BEGIN_SRC emacs-lisp :var ref-file=(buffer-file-name)
(with-temp-buffer
(insert-file-contents (expand-file-name ref-file))
(buffer-string))
#+END_SRC
** emacs-version block
#+NAME: emacs-version
#+BEGIN_SRC emacs-lisp
;; (emacs-version) function returns a lot of extra info whereas I just need the version number in the emacs-version variable:
emacs-version
#+END_SRC
** org-mode-version block
#+NAME: org-mode-version
#+BEGIN_SRC emacs-lisp
;; (org-version) only returns the version number
(org-version)
#+END_SRC
** show-directory block
:PROPERTIES:
:ID: 019f982f-399c-4c79-b6dd-2b897481563c
:END:
Notice how the value of tangle-dir this returns is not from this
heading (which actually does not have a properties drawer), but from
its parent heading, yeilding the top-most directory:
# #+NAME: show-directory
# #+BEGIN_SRC bash :results output :noweb yes :tangle :tangle (org-in-tangle-dir "show-directory.sh") :exports none :mkdirp yes :shebang "#!/bin/bash" :var tangle_dir=(org-entry-get (point) "tangle-dir" 'inherit) :var reffile=(buffer-file-name)
# echo tangle_dir $tangle_dir
# echo reffile $reffile
# #+END_SRC
#+NAME: show-directory
#+BEGIN_SRC bash :results output :exports none :var tangle_dir=(org-entry-get (point) "tangle-dir" 'inherit)
head_count=10
tree $tangle_dir
echo
echo "Up to $head_count lines of each generated file are shown below:"
echo
for file in $(find $tangle_dir -type f | sort)
do
echo
echo "FILE: $file"
cat -n $file | head -$head_count
done
#+END_SRC
```
<sup>1</sup> How can I evaluate elisp in an orgmode file when it is opened? describes using File Local variables to define functions like as done above, but they are considered by some to be a security risk. Even if it was not a security risk, you may still find them annoying if you need to use them in multiple Org files. Also, because they only work at the end of the file which tends to get appended to with new child headings, leaving the File Local Variables in the middle of the file where they are likely to not be missed by Emacs when it loads the file the next time.
<sup>2</sup>The `org-in-tangle-dir` function could be included into the Org mode itself in some manner.
---
Tags: org-mode, org-export, org-babel
---
|
thread-55862
|
https://emacs.stackexchange.com/questions/55862
|
elpy-goto-definition jump to the center of the terminal window
|
2020-03-02T09:38:04.310
|
# Question
Title: elpy-goto-definition jump to the center of the terminal window
I was using dumb-jump to go to the location where the identifier at point is defined. When it jumps to the function, jumped function shows up on the middle of the terminal window.
---
=\> Instead when I use `elpy-goto-definition` it jumps to the function and shows it on the 1st line on the top of the terminal window.
**\[Q\]** Is it possible to make `elpy-goto-definition` to show the jumped function on the center of the terminal like `dumb-jump`?
# Answer
> 1 votes
Not beeing a user of elpy but looking at elpys source code, I would say you have several options to do this (there are proably more).
Calling `elpy-goto-definition` results in a call to `elpy-goto-location` which at its end calls `(recenter 0)` and this `0` is the culprit.
3 completely separate ways to change that:
*first*
create a new function (my-elpy-goto-definition) which just calls `elpy-goto-definition` and then does `(recenter)` without that `0`. to use it you always call `my-elpy-goto-definition` instead of `elpy-goto-definition` (least intrusive solution, Problem: you need to redefine your shortcut keys)
*second*
copy and paste the whole function `elpy-goto-location` then remove the offending `0` and re-eval that defun, effectively replacing the old function with your modified one. (very intrusive solution, Problem: you will never automatically receive code updates/fixes to that function, you have to include them manually)
*third*
write an advice to either `elpy-goto-definition` or `elpy-goto-location` (depends on how globaly you want this behavior), which calls an `(recenter)` after that function has run. (medium intrusive solution, works automatic, without changing keybindings, I'd probably go with this).
Example code for *third* (advicing `elpy-goto-location`):
```
(defun my-recenter-elpy-goto (&rest r)
(recenter))
(advice-add #'elpy-goto-location :after #'my-recenter-elpy-goto)
```
---
Tags: elpy
---
|
thread-55874
|
https://emacs.stackexchange.com/questions/55874
|
Don't italicize /.../ in this org buffer
|
2020-03-02T15:56:54.877
|
# Question
Title: Don't italicize /.../ in this org buffer
Is it possible to specify that, in a certain org buffer, `/.../` should not be italicized?
# Answer
> 2 votes
You can control the emphasis in the Org buffer by the variable `org-emphasis-alist`.
The doc of this variable says that you must re-load Org after setting this variable to come into effect.
At least for Org 9.2.6 this is not entirely true. You can set it as buffer-local variable and it controls font lock. But, it does not effect HTML-export and LaTeX-export.
See the help for `org-emphasis-alist`. Just remove the `"/"` entry from this list and use it for a buffer-local setting:
```
Local Variables:
org-emphasis-alist: (("*" bold) ("_" underline) ("=" org-verbatim verbatim) ("~" org-code verbatim) ("+" (:strike-through t)))
End:
```
If you pity the lost global modifications of `org-emphasis-alist` you can also use:
```
Local Variables:
eval: (setq-local org-emphasis-alist (cons '("/") (default-value 'org-emphasis-alist)))
End:
```
With the following Elisp code you can also eliminate italic face from HTML export and LaTeX export.
```
;; -*- lexical-binding:t -*-
(defun org+-remove-emphasis (&optional emph)
"Remove EMPH from org mode emphasis.
EMPH defaults to \"/\"."
(unless emph
(setq emph "/"))
(let ((type (assoc-string emph (default-value 'org-emphasis-alist))))
(setq-local org-emphasis-alist
(cons (list emph) (default-value 'org-emphasis-alist)))
(setq-local org-element-object-restrictions
(mapcar
(lambda (r)
(cons (car r)
(cl-remove (cadr type) (cdr r) :test #'string-equal)))
(default-value 'org-element-object-restrictions)))))
```
You use it in the following way:
```
* Local Variables :noexport:
Local Variables:
eval: (org+-remove-emphasis "/")
End:
```
---
Tags: org-mode
---
|
thread-55875
|
https://emacs.stackexchange.com/questions/55875
|
How to tweak dired-create-empty-file to facilitate the easy creation of files
|
2020-03-02T15:58:51.280
|
# Question
Title: How to tweak dired-create-empty-file to facilitate the easy creation of files
I currently have bound the command `dired-create-empty-file` to `f7`. Emacs then prompts me for a file name. When I press `f7` I would like Emacs to automatically create an ORG file and automatically generate a file name for it based on the date and time and then open the new file for editing. I find I prefer to rename files later if necessary than take the time to devise a name for them at the start.
# Answer
You can write your own function and bind it to `F7` instead of binding dired-create-empty-file to it - something like this (lightly tested):
```
(defun my-dired-create-empty-file ()
(interactive)
(let* ((ts (format-time-string "%Y-%m-%dT%H.%M.%S" (current-time)))
(fname (format "%s.org" ts)))
(dired-create-empty-file fname)
(find-file fname)))
```
It probably does not handle the case of an existing file name properly, but if you wait at least one second between generating files, that should not be much of a problem :-).
> 2 votes
---
Tags: org-mode, dired, files, filenames
---
|
thread-55866
|
https://emacs.stackexchange.com/questions/55866
|
Change behaviour of "comment-region" in org-mode tangled source blocks?
|
2020-03-02T10:56:23.813
|
# Question
Title: Change behaviour of "comment-region" in org-mode tangled source blocks?
I am experimenting with using org-mode for some of my startup config, and adding `(org-babel-load-file (concat user-emacs-directory "config.org"))` to my .emacs.
Then I use a structure like the following to embed elisp:
```
** Disable window clutter
#+begin_src emacs-lisp
(setq initial-scratch-message nil)
(setq inhibit-splash-screen t)
(if (fboundp 'scroll-bar-mode) (scroll-bar-mode -1))
(if (fboundp 'tool-bar-mode) (tool-bar-mode -1))
#+end_src
```
Inside the source block, `M-x comment-region` uses a '#' as the comment character. What is the best/easiest way to make `comment-region` adjust to the block it is in?
# Answer
Use https://github.com/redguardtoo/evil-nerd-commenter, run `M-x NUM evilnc-comment-or-uncomment-lines` will comment/uncomment NUM lines under cursor.
Please note `evil` is not required for this command.
See https://github.com/redguardtoo/evil-nerd-commenter/blob/fa40dab8d2f010db17e1e62dfd245c1504d0542f/evil-nerd-commenter.el#L397 for key algorithm.
It's very simple. use `org-edit-src-find-region-and-lang` (Emacs 24.4+) or `org-element-at-point` (Emacs 26.1+) to find the the major mode for current code snippet.
Open a new temporary buffer, insert the code snippet, switch to correct major mode, comment out code, then replace the snippet in org file with the snippet in the temporary buffer.
Here is demo,
> 2 votes
# Answer
From: https://lists.gnu.org/archive/html/emacs-orgmode/2013-11/msg00318.html
```
#+BEGIN_SRC emacs-lisp :results none
;; allow comment region in the code edit buffer (according to language)
(defun my/org-comment-dwim (&optional arg)
(interactive "P")
(or (org-babel-do-key-sequence-in-edit-buffer (kbd "M-;"))
(comment-dwim arg)))
;; make `C-c C-v C-x M-;' more convenient
(define-key org-mode-map
(kbd "M-;") 'my/org-comment-dwim)
#+END_SRC
```
> 1 votes
---
Tags: org-mode, org-babel, comment
---
|
thread-55872
|
https://emacs.stackexchange.com/questions/55872
|
Check agenda of a particular day from calendar
|
2020-03-02T13:18:21.710
|
# Question
Title: Check agenda of a particular day from calendar
In calendar-mode to invoke d on a specified day, it will prompt the activitiesof the day from file ~/diary.
Is it possible to invoke an agenda view of a particular day from calendar?
# Answer
Sure, just press `c` (which is bound to `org-calendar-goto-agenda`) while the cursor is at the date you wish to have a look.
> 3 votes
# Answer
Not a direct answer to your question (@aadcg's answer does that perfectly), but in Emacs you can "look around" and see what keys are bound to what functions in any particular situation (that's part of the "self-documenting" part of the description of Emacs): in this case, while you are in the calendar, say `C-h m`: you'll get all the key bindings available, listed in a separate buffer (which means you can also switch to that buffer and do an interactive search for `org` to find all the keybindings that might have something to do with Org mode).
> 1 votes
---
Tags: org-mode, org-agenda, calendar
---
|
thread-41235
|
https://emacs.stackexchange.com/questions/41235
|
Emacs Terminal vs Emacs GUI: different look & feel for the same theme
|
2018-04-26T05:33:36.833
|
# Question
Title: Emacs Terminal vs Emacs GUI: different look & feel for the same theme
Whenever I install a theme, I notice it odes not appear exactly the same way on Emacs Terminal and Emacs GUI.
For example, I installed this theme recently, and it behaves as the previous ones I installed:
In this situation, for example, I prefer the look and feel shown on the right picture above. I do not use the GUI version of Emacs though, so I would like to get what I see on the right picture, in the Terminal version of Emacs.
Is this a normal behavior?
# Answer
That is normal behavior as usually terminals do not have all the colors GUI has.
Some theme makers try to do their best to find matching colors on terminals that have only 16 or 256 paletted colors or provide separate palettes for different terminals.
Now I believe some new versions of terminals can render 16+M colors but not all terminal applications can do so. Newer version of emacs should be able to do this.
PS. I might be wrong :)
PPS. In your case maybe you can just `export TERM=xterm-256color` in your `.bashrc`
> 4 votes
# Answer
This is normal because most terminals do not support truecolor (24 bit color, specifying 16+ million colors). So the terminal only has 256 colors, while your GUI has more. For instance, macOS's built in terminal program Terminal.app only supports 256 colors (as of 2020-03-02).
However, if you use the right terminal app, and if you invoke a modern version of emacs (26.1+) in the right way, then you can get truecolor in the terminal and it will match what you see in the GUI.
The emacs docs describe how to invoke emacs to use truecolor. You need to create a new record in your terminfo database and then set an environmental variable to point to it. Your terminal app should indicate if it supports truecolor (and this gist collects information about support in various terminal).
FWIW, I got this working with emacs 26.1, so that what I see when connected to a remote ubuntu machine via iTerm2 exactly matches what I see running emacs locally on my Mac in GUI mode.
> 4 votes
---
Tags: themes
---
|
thread-55881
|
https://emacs.stackexchange.com/questions/55881
|
Reading a list of string from a .txt file
|
2020-03-02T20:49:16.600
|
# Question
Title: Reading a list of string from a .txt file
I have a file, `myfile.txt`, whose content is:
```
(query-replace "foo" "Hello" nil (point-min) (poin-max))
```
and this function:
```
(defun comment-string-from-file ()
(interactive)
(let ((STRING (with-temp-buffer
(insert-file-contents "myfile.txt")
(buffer-string))))
(when (string-match (regexp-quote STRING) (buffer-string))
(let ((b (copy-marker (match-beginning 0)))
(e (copy-marker (match-end 0))))
(comment-region b e)))))
```
This function works and, if present, comments, in the current buffer, the string:
```
"(query-replace \"foo\" \"Hello\" nil (point-min) (poin-max))"
```
Now I'd like to do the same thing looping over a file that contains a list of strings, separated by 2 newlines, e.g.
```
(query-replace "foo" "Hello" nil (point-min) (poin-max))
(query-replace "bar" "World" nil (point-min) (poin-max))
(insert "foo\n")
(insert "bar\n")
```
Alternatively, and this should be my first choice, I could use an arbitrary string boundary to allow newlines in my strings, e.g..
```
♦(query-replace "foo"
"Hello" nil (point-min) (poin-max))♦
♦(query-replace "bar"
"World" nil (point-min) (poin-max))♦
♦(insert "foo\n")♦
♦(insert "bar\n")♦
```
The idea is that I don't want to use any kind of escaping in the source file.
How can I do it?
# Answer
The following Elisp function covers all your use-cases. You can choose two newlines as separator regexp `sep`. That is the default. Or you can also choose some other character as separator regexp, such as . Empty strings between two separators are removed from the list `string-list` of regexps matching patterns to be commented-out. So your alternative pattern file syntax should work.
The patterns are combined to one regexp through `regexp-opt`. You can comment all occurrences of the patterns by calling `comment-string-from-file` with prefix arg. Otherwise only the first occurrence of each pattern is replaced (such as your code example indicates).
```
(require 'cl-lib)
(defun comment-string-from-file (file &optional sep all)
"Read patterns separated by SEP from FILE, comment out matching regions.
Comment all matches if ALL is non-nil.
Comment only first one if ALL is nil."
(interactive "fPattern file: \nsSeparator regexp: \nP")
(unless sep
(setq sep "\n\n+"))
(let* ((string (with-temp-buffer
(insert-file-contents file)
(buffer-string)))
(string-list (cl-remove-if
(lambda (str)
(string-match "\\`[[:space:]\n]*\\'" str))
(split-string string sep)))
(re (regexp-opt string-list)))
(save-excursion
(goto-char (point-min))
(while (and
string-list
(re-search-forward re nil t))
(let ((match (match-string 0)))
(comment-region
(match-beginning 0)
(match-end 0))
(unless all
(setq string-list (cl-remove match string-list :test #'string-equal)
re (regexp-opt string-list))))))))
```
> 2 votes
---
Tags: files
---
|
thread-55884
|
https://emacs.stackexchange.com/questions/55884
|
Display sunrise and sunset time from agenda view
|
2020-03-03T01:27:24.637
|
# Question
Title: Display sunrise and sunset time from agenda view
I set the diary file as
```
(setq org-agenda-include-diary t)
(setq org-agenda-diary-file "~/Documents/OrgMode/ORG/src/standard-diary") ;;2020-03-02 10:47:06
(setq diary-file "~/Documents/OrgMode/ORG/src/standard-diary")
```
and the Day info in the diary
```
;;Day info
%%(diary-sunrise-sunset)
%%(diary-lunar-phases)
%%(diary-iso-date)
```
Then check the day view from agenda
```
Tuesday 3 March 2020
3:00...... -----------------------------------------------------
Diary: 3:59...... First Quarter Moon (CST)
6:00...... -----------------------------------------------------
Diary: 6:46...... Sunrise (CST), sunset 6:07pm (CST) at 40.0N, 116.3E (11:21 hrs daylight)
9:00...... -----------------------------------------------------
9:02...... now - - - - - - - - - - - - - - - - - - - - - - - - -
12:00...... -----------------------------------------------------
15:00...... -----------------------------------------------------
18:00...... -----------------------------------------------------
21:00...... -----------------------------------------------------
24:00...... -----------------------------------------------------
```
In the day view the Sunrise time and the sunset time displayed on the same line,
How could place them appropriate the right clock time as
```
Tuesday 3 March 2020
3:00...... -----------------------------------------------------
Diary: 3:59...... First Quarter Moon (CST)
6:00...... -----------------------------------------------------
Diary: 6:46...... Sunrise (CST) - - - - - - - - - - - - - - - - - - - -
9:00...... -----------------------------------------------------
9:02...... now - - - - - - - - - - - - - - - - - - - - - - - - -
12:00...... -----------------------------------------------------
15:00...... -----------------------------------------------------
18:00...... -----------------------------------------------------
18:07...... Sunset 6:07pm (CST) at 40.0N, 116.3E (11:21 hrs daylight)
21:00...... -----------------------------------------------------
24:00...... -----------------------------------------------------
```
# Answer
> 6 votes
`diary-sunrise-sunset` returns a string with both times:
> "Sunrise 6:17am (EST), sunset 5:36pm (EST) at 40.3N, 71.0W (11:19 hrs daylight)"
So use `diary-sunrise` and `diary-sunset` separately:
```
%%(diary-sunrise)
%%(diary-sunset)
```
where these two functions are defined as follows (somewhere in your init file):
```
(defun diary-sunrise ()
(let ((dss (diary-sunrise-sunset)))
(with-temp-buffer
(insert dss)
(goto-char (point-min))
(while (re-search-forward " ([^)]*)" nil t)
(replace-match "" nil nil))
(goto-char (point-min))
(search-forward ",")
(buffer-substring (point-min) (match-beginning 0)))))
(defun diary-sunset ()
(let ((dss (diary-sunrise-sunset))
start end)
(with-temp-buffer
(insert dss)
(goto-char (point-min))
(while (re-search-forward " ([^)]*)" nil t)
(replace-match "" nil nil))
(goto-char (point-min))
(search-forward ", ")
(setq start (match-end 0))
(search-forward " at")
(setq end (match-beginning 0))
(goto-char start)
(capitalize-word 1)
(buffer-substring start end))))
```
Each of these calls `diary-sunrise-sunset` and parses the return value to get one of the two times.
In order for the times to be correct you have to supply your location, e.g.:
```
(setq calendar-latitude 40.3)
(setq calendar-longitude -71)
```
That's somewhere in the Atlantic off of New York City: adjust to taste.
Note that `diary-sunset` does capitalize `sunset` but it also strips the location off, which is fine for me: you'll have to change the parsing a bit in the second function if you want to keep it.
EDIT in response to comment: It's actually not a very good code example to learn elisp from. It's only doing regexp matching and string operations for one. But the biggest problem is that the diary functions in general (and `diary-sunrise-sunset` in particular) require that a variable named `date` be set before you can call them. So to really run them e.g. in the `*scratch*` buffer in lisp-interaction-mode, you have to say something like this:
```
(setq date '(3 14 2020))
(diary-sunrise-sunset)
```
The date is a list of three numbers: the month, the day and the year.
---
Tags: org-mode, calendar, diary
---
|
thread-55886
|
https://emacs.stackexchange.com/questions/55886
|
Emacs + visual line numbers + folding + visual fill column mode
|
2020-03-03T10:36:08.410
|
# Question
Title: Emacs + visual line numbers + folding + visual fill column mode
Relative line numbers for me it's a little bit painful topic. I'm using evil (spacemacs) and I want to jump between lines by in vim style like `10j`, `4k` etc. Is it possible to get line numbers behavior in emacs just like in vim?
There is two mutually exclusive problems for `visual` and `relative` line numbers mode in emacs.
1. Visual line numbers works great with folding. But when test wraps by `visual-fill-column-mode`, visual line numbers assigns a number to non-existent line. And from now I can't just moving between lines correctly because of related picture.
2. In another hand relative line numbers solve the problem above, and it works just fine, but... until the moment when I fold something. Imagine, in picture below I want jump to one of `Another long test topic`. How should I do this?
So, is there any solution for this? I've spent a lot of time to googling it, but my efforts still have no result.
Sorry for my English.
Regards
# Answer
> 2 votes
I've FINALLY got solution for this, but there is not related with line numbers. All what I've done is just set another functions to `j`, `k` for evil. And it works almost perfect.
God, I'm sooo happy now. There is solution for spacemacs
https://github.com/syl20bnr/spacemacs/issues/9557#issuecomment-327976596
---
Tags: evil, code-folding, line-numbers, visual-line-mode
---
|
thread-55892
|
https://emacs.stackexchange.com/questions/55892
|
Yanking does not use top entry in the kill ring
|
2020-03-03T16:21:30.800
|
# Question
Title: Yanking does not use top entry in the kill ring
I want to delete regions without adding them to the kill ring following this thread:
```
(defun backward-kill-word-no-kill-ring ()
"Delete the previous word and remove it from the kill ring."
(interactive)
(backward-kill-word 1)
(setq kill-ring (cdr kill-ring))
)
(global-set-key (kbd "M-DEL") 'backward-kill-word-no-kill-ring)
```
It fails and I don't understand why. If I type `abcd`, copy it with `Cmd-C`, and yank it with `C-y`, Emacs inserts `abcd` and the kill ring, viewed with `C-h v kill-ring RET`, is:
```
(Value:
(#("abcd" 0 4
(fontified t))
...
```
If I type `123`, delete it with `M-DEL`, which calls my function, and then yank with `C-y`, Emacs inserts `https://www.fablabs.io/labs`, which I had copied 30 minutes ago and is no longer an entry in the kill ring, and the kill ring is:
```
Value:
(#("123" 0 3
(fontified t))
#("abcd" 0 4
(fontified t))
...
```
Then I cut text with `C-w` (`kill-region`), yank in another buffer, and it's the same link that comes first and my cut text that comes second (after `M-y`).
Where does `yank` grab its text if not from the kill ring?
## Update
Following Tobias's comment, I had `save-interprogram-paste-before-kill` at `t`, and have the same behavior when I set it to `nil` and start Emacs with `emacs -Q`. When I follow the steps above, after `M-DEL` of `123`, Emacs inserts the last entry from the kill ring, `abcd`. (When I first asked the question, I may have missed that the inserted text was the last entry of the kill ring, even after searching for the string in the kill-ring information buffer.)
## Further udpate
A similar question asks how to delete text without adding to the kill ring. The solution there, as the answer by Tobias here, is more elegant than my first attempt. I edited the question to understand why Emacs is using the last entry in the kill ring instead of the top entry.
## Further update (10 March)
I follow the steps above with `emacs -Q`, copy `abcd` to the clipboard and yank it, copy the function and keybinding and execute it, and after `M-DEL` of `123`, Emacs inserts the last entry from the kill ring, `abcd`.
The kill ring after that insertion is:
```
Value:
("(defun backward-kill-word-no-kill-ring ()
\"Delete the previous word and remove it from the kill ring.\"
(interactive)
(backward-kill-word 1)
(setq kill-ring (cdr kill-ring))
)
(global-set-key (kbd \"M-DEL\") 'backward-kill-word-no-kill-ring)"
#("abcd" 0 4
(fontified t)))
```
The Emacs version is:
```
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
```
The values of `interprogram-paste-function` and `interprogram-cut-function` are the default ones, `gui-selection-value` and `gui-select-text`. The behavior is the same if I use `M-w` instead of `Cmd-C` to copy the first piece, `abcd`, to the kill ring.
# Answer
I don't know why your `kill-ring` gets messed up. It might be that it is some inter-program action that modifies the `kill-ring`.
But the right way to implement deleting instead of killing is:
```
(defun delete-word (arg)
"Delete characters forward until encountering the end of a word.
With argument ARG, do this that many times."
(interactive "p")
(delete-region (point) (progn (forward-word arg) (point))))
(defun backward-delete-word (arg)
"Delete characters backward until encountering the beginning of a word.
With argument ARG, do this that many times."
(interactive "p")
(delete-word (- arg)))
```
Note, that I just copied the stuff from `simple.el` and replaced `kill` with `delete`.
> 2 votes
---
Tags: yank, kill-ring, kill-text
---
|
thread-55891
|
https://emacs.stackexchange.com/questions/55891
|
kill rectangle not working on Mac (missing file/library)
|
2020-03-03T16:03:25.160
|
# Question
Title: kill rectangle not working on Mac (missing file/library)
I just upgraded to emacs 26.2 using homebrew on my MAC (update: I had actually done a global "brew update" and assumed it had also updated emacs) and now kill-rectangle with `C-x r k` no longer works, and instead gives me an error:
```
Cannot open load file: No such file or directory, rect
```
Any idea how I can get it back as it is a super useful feature...
# Answer
Comments on the question post made me understand that the `rect` library was missing. I looked into brew and tried a
```
brew upgrade emacs
```
and surprise surprise it told me that emacs was not installed, so it seems that my emacs was a default "build in" prior to me switching to use homebrew and my global **brew upgrade** command had not actually upgraded emacs but instead had somehow messed up the syncing of library versions.
```
brew install emacs
```
installed v26.3 and was all I needed to put things right.
> 1 votes
---
Tags: osx, rectangle, kill-text
---
|
thread-55895
|
https://emacs.stackexchange.com/questions/55895
|
How do I exit an archive in no-window mode?
|
2020-03-03T18:38:59.163
|
# Question
Title: How do I exit an archive in no-window mode?
When navigating the directory structure in no window mode, there is always `..` at the top of the current directory, so that one can leave it and go to the directory up ahead.
I am using emacs 26.3 and when I enter a zip archive, I see no way of leaving the archive other exiting emacs using `C-x C-c`.
How do I leave the archive properly, so that I end up back in the directory where the archive is stored?
# Answer
> 1 votes
`q` in `Zip-Archive` mode will run command `quit-window`. You can see information about enabled modes by invoking `describe-mode` (`C-h m`).
Your zip archive is a separate buffer along with dired one so usual commands to work with buffers can also help:
* `C-x b <RET>` (`switch-to-buffer`) will switch to previous buffer (dired)
* `C-x k <RET>` (`kill-buffer`) will kill current buffer (zip archive)
---
Tags: navigation, archive-mode
---
|
thread-55899
|
https://emacs.stackexchange.com/questions/55899
|
How to save a org buffer everytime the todo state changes?
|
2020-03-03T20:31:20.817
|
# Question
Title: How to save a org buffer everytime the todo state changes?
In both agenda mode or a regular org mode buffer, whenever I change the todo state, I want the buffer to be saved automatically.
# Answer
**Adding to `org-trigger-hook` works:**
```
(add-hook 'org-trigger-hook 'save-buffer)
```
Adding to `org-after-todo-state-change-hook` hook **does NOT work**:
I was troubled to see the hook above did not work until I saw the following post on reddit: https://www.reddit.com/r/orgmode/comments/9sxe3w/save\_file\_after\_toggling\_todo\_state/
> 3 votes
---
Tags: org-mode, hooks
---
|
thread-55897
|
https://emacs.stackexchange.com/questions/55897
|
How do I get Emacs to accept a # (hash) sign as a comment starter in a new mode?
|
2020-03-03T18:47:30.577
|
# Question
Title: How do I get Emacs to accept a # (hash) sign as a comment starter in a new mode?
I am attempting to develop an Emacs major mode for writing Tecplot macros. The Tecplot macro language has lots of peculiar constructs, such as a `#` sign for comments and `$!` for the beginning of a macro command. When I use the following code to define the syntax table, I get an invalid character error for the comments:
```
(defconst tecplot-macro-mode-syntax-table
(let ((table (make-syntax-table)))
;; ' is a string delimiter
(modify-syntax-entry ?' "\"" table)
;; " is a string delimiter too
(modify-syntax-entry ?\" "\"" table)
;; " is a string delimiter too
(modify-syntax-entry ?| "|" table)
;; / is punctuation, but # is a comment starter
(modify-syntax-entry ?# ". 1b" table)
table))
```
The error I get is:
```
**Lisp error: (error "Invalid syntax description letter: #")**
```
How do I get the `#` sign to be resolved as a comment? Am I going to have similar issues with the `$!`?
# Answer
> 1 votes
Stefan beat me with his answer. Nevertheless, I have got a basis for you where you can start with:
```
(defconst tecplot-macro-mode-syntax-table
(let ((table (make-syntax-table)))
;; ' is a string delimiter
(modify-syntax-entry ?' "\"" table)
;; " is a string delimiter too
(modify-syntax-entry ?\" "\"" table)
;; |...| delimits variable names
(modify-syntax-entry ?| "_" table)
;; $!... delimits macro calls
(modify-syntax-entry ?$ "_" table)
(modify-syntax-entry ?! "_" table)
;; / is punctuation, but # is a comment starter
(modify-syntax-entry ?# "<" table)
(modify-syntax-entry ?\n ">" table)
table))
(defvar tecplot-macro-mode-keywords
'(("$![[:alpha:]]+" . font-lock-function-name-face)
("|\\(?:[[:alpha:]]\\|\\s_\\)+|" . font-lock-variable-name-face))
"List of keywords for `tecplot-macro-mode'.")
(define-derived-mode tecplot-macro-mode prog-mode "Tecplot"
"Mode for editing Tecplot macros."
:syntax-table tecplot-macro-mode-syntax-table
(setq font-lock-defaults '(tecplot-macro-mode-keywords))
(font-lock-mode)
)
```
# Answer
> 1 votes
Use `?\#` instead of `?#`. This won't be needed for `!` nor `$` because these chars happen not be special for Elisp, whereas `#` is special (e.g. it is used for hexadecimal numbers like `#xFF`), but you *can* also use `?\!` and it won't hurt.
BTW, if `|...|` is a string, you can use `"\""` rather than `"|"` as its syntax (BTW, there's a copy&paste error in your comment about `|`).
The `1b` says that `#` is the first char of a two-chars comment starter (e.g. if a comment starter takes the form `#|` then you'd put a `2` into the syntax of `|`), but in your case it seems like you just want to use `"<"` for `?\#`.
---
Tags: comment, syntax-table
---
|
thread-55857
|
https://emacs.stackexchange.com/questions/55857
|
Magit - problem doing a second commit related to the GIT_EDITMSG buffer
|
2020-03-01T22:42:35.170
|
# Question
Title: Magit - problem doing a second commit related to the GIT_EDITMSG buffer
This looks similar (the same?) as How to prevent Magit from saving COMMIT\_EDITMSG? but I've also confirmed that the problem isn't magit itself, but interactions with settings or other packages.
I'm having the same issue as 46965 (though it just started recently) -- my second commit goes to the previous git commit and bypasses the options for commits.
I am definitely using `C-c C-c` to commit and I see the commit in the log.
I tried running a bare magit using the info in the debug section of the manual -- that instance worked as it's supposed to (goes to the options). So it sounds like either settings or other packages are causing the problem. I turned off all other magit packages (magit-section, magit-todos, vdiff-magit) but the problem is still there.
Has anyone else seen this behaviour and found out what the offending setting/package is?
My setup: Magit 20200228.1207, Git 2.25.1, Emacs 28.0.50, gnu/linux
# Answer
> 1 votes
@ddavis answered this question in a comment!
Changing setq server-kill-new\_buffers to t:
```
(setq server-kill-new-buffers t)
```
fixed this issue. This will kill buffers given to the server, when the user is done with it, unless the buffer already existed. If this would cause another problem then you can leave that variable as nil and add a regexp for this buffer to server-temp-file-reg-exp which will tell the server that this file is a temp file so that it can kill it once you finish.
Thanks @ddavis !
---
Tags: magit
---
|
thread-55903
|
https://emacs.stackexchange.com/questions/55903
|
Setf and pushnew do not work on slot "options" of org-export-backend defined by cl-defstruct
|
2020-03-03T23:19:34.750
|
# Question
Title: Setf and pushnew do not work on slot "options" of org-export-backend defined by cl-defstruct
Org-mode export backends are defined as instances of the cl structure `org-export-backend`:
```
(cl-defstruct (org-export-backend (:constructor org-export-create-backend)
(:copier nil))
name parent transcoders options filters blocks menu)
```
The documentation string of `cl-defstruct` says:
> This macro defines a new data type called NAME that stores data in SLOTs. It defines a `make-NAME` constructor, a `copy-NAME` copier, a `NAME-p` predicate, and slot accessors named `NAME-SLOT`. You can use the accessors to set the corresponding slots, via `setf`.
>
> Each SLOT may instead take the form (SNAME SDEFAULT SOPTIONS…), where SDEFAULT is the default value of that slot and SOPTIONS are keyword-value pairs for that slot. Currently, only one keyword is supported, `:read-only`. If this has a non-nil value, that slot cannot be set via `setf`.
The `options` slot of `org-export-backend` is not marked with the keyword `:read-only`.
Therefore setting backend options with `cl-pushnew` should work as in the next example Elisp snippet:
```
(require 'cl-lib)
(with-eval-after-load 'ox-ascii
(cl-pushnew
'(:ascii-upcase-title nil "ascii-upcase-title" 'org+-ascii-upcase-title)
(org-export-backend-options (org-export-get-backend 'ascii))))
```
But this does not work reliable. I had to remove it from an answer to a question about the ox-ascii export plugin.
If one calls `M-x` `load-library` `RET` `ox-ascii` `RET` after this setting, one gets the error
```
let*: Symbol’s function definition is void: \(setf\ org-export-backend-options\)
```
This error presents itself with the following message if one tries to export with `org-export-dispatch`:
```
Problems while trying to load export back-end ‘ascii’
```
What does cause this error? How can I prevent it?
# Answer
Macroexpansion of the body of `with-eval-after-load` happens eagerly, i.e. before `ox-ascii` is loaded. So at that time, the slot is not defined and the `setf/cl-pushnew` macroexpander doesn't know what to do and chooses a default setter which is not the one that `cl-defstruct` will define.
Better move that code to a separate file:
```
(require 'ox-ascii)
(cl-pushnew
'(:ascii-upcase-title nil "ascii-upcase-title" 'org+-ascii-upcase-title)
(org-export-backend-options (org-export-get-backend 'ascii))))
```
and then load it when `ox-ascii` gets loaded:
```
(with-eval-after-load 'ox-ascii (load <myfile>))
```
> 3 votes
---
Tags: org-export, cl
---
|
thread-37851
|
https://emacs.stackexchange.com/questions/37851
|
How do I insert a heading above the current one in org-mode?
|
2018-01-02T18:33:39.473
|
# Question
Title: How do I insert a heading above the current one in org-mode?
I'm currently running Spacemacs+evil and pressing `C-RET` calls `evil-org-org-insert-heading-respect-content-below`, which inserts a a heading **below** the current one.
I couldn't find a dual/mirror command that would create a heading **above** the current one, though. Is there one, or what's a good implementation that does this?
---
Note: I'm self-answering with my solution, which is **the first elisp I've ever written** and is very tied to Spacemacs+evil, but I would love it if others could chime in with snippets that don't depend on Spacemacs nor evil and are as such more useful to the general org-mode user. Thanks!
# Answer
Building on kbdluv's answer, here's a simpler generic version that doesn't require evil-mode:
```
(defun org-insert-heading-above ()
(interactive)
(move-beginning-of-line nil)
(org-insert-heading))
```
I've bound it to `C-o` (normally `open-line`) for org-mode files:
```
(add-hook 'org-mode-hook
(lambda ()
(define-key org-mode-map (kbd "C-o") 'org-insert-heading-above)))
```
> 3 votes
# Answer
M-x org-insert-heading (usually bound to M-ret) will insert a heading above the current heading, and with a prefix arg below the current heading.
> 2 votes
# Answer
This is the solution that *works for me*. It is unfortunately very coupled to evil-mode (and to Spacemacs, if you consider the keybindings.)
I define a function which does the same as pressing `0,iha`, then bind it to `,b`.
I also bind the original `evil-org-org-insert-heading-respect-content-below` to `,f` so that the `,b`/`,f` pair uses the "backwards/forwards" mnemonic.
```
(defun my-org/insert-heading-above ()
"Same as 0 , i h"
(interactive)
(evil-digit-argument-or-evil-org-beginning-of-line)
(org-insert-heading)
(evil-append 1))
(with-eval-after-load 'org
(spacemacs/set-leader-keys-for-major-mode 'org-mode "f" 'evil-org-org-insert-heading-respect-content-below)
(spacemacs/set-leader-keys-for-major-mode 'org-mode "b" 'my-org/insert-heading-above))
```
> 1 votes
# Answer
Thanks to @kdbluv @steve-simms . I'm using Spacemacs on macOS and utilize `⌘return` to insert new heading below and `⌃⌘return` to insert new heading above (respect content) in both normal mode and then switch to insert mode.
```
(defun my-org-insert-heading-below ()
"Insert heading below and switch to insert mode."
(interactive)
(org-insert-heading-respect-content)
(evil-insert-state 1))
(defun my-org-insert-heading-before ()
"Insert heading above current heading and switch to insert mode."
(interactive)
(cond
((org-on-heading-p) nil)
(t (org-backward-heading-same-level 0)))
(move-beginning-of-line nil)
(org-insert-heading)
(evil-insert-state 1))
(with-eval-after-load 'evil-maps
(define-key evil-normal-state-map (kbd "<s-return>") 'my-org-insert-heading-below)
(define-key evil-insert-state-map (kbd "<s-return>") 'my-org-insert-heading-below)
(define-key evil-normal-state-map (kbd "<C-s-return>") 'my-org-insert-heading-before)
(define-key evil-insert-state-map (kbd "<C-s-return>") 'my-org-insert-heading-before)
)
```
> 0 votes
---
Tags: org-mode
---
|
thread-55867
|
https://emacs.stackexchange.com/questions/55867
|
Org mode export to HTML not opening in browser in cygwin emacs-w32
|
2020-03-02T11:18:11.343
|
# Question
Title: Org mode export to HTML not opening in browser in cygwin emacs-w32
When I do `C-c C-e h o` the file opens in an Emacs buffer instead of my default browser which is odd because org-mode links do open in the browser as is the case when I preview a file from web-mode, so Emacs must know how to open the default windows program for html files.
I have tried to customize the `org-file-apps` variable as per an answer in this question. I put in the cygwin path of browser executable and org-mode now indeed opens the browser but the browser fails to open the file as Emacs gives it a cygwin path to the html file, and I don't know what magic I would have to insert to convert the file path to a windows one. In any case it should open the browser with default setting for this variable, which was default before I changed it.
# Answer
Whilst I feel a bit sheepish about answering my own question I have found a solution. If you put something like this in you `.emacs` then the exported file will be opened by the Windows default browser. The program `cygstart` translates the URL or file path into a Windows equivalent one and opens the default program associated with the file extension. In the snippet bellow I have applied the fix for HTML and PDF file, others can be added as required. I suspect the intention is that org mode should do this by default as that's what it does on my Ubuntu system, but after taking a quick look at the Org Mode code, it seems like it is not handling the Cygwin case correctly. Maybe I will submit a fix one day!
```
(defun my-org-mode-hook ()
(setq org-file-apps
(quote
((auto-mode . emacs)
("\\.x?html?\\'" . "cygstart %s")
("\\.pdf\\'" . "cygstart %s")))))
(add-hook 'org-mode-hook 'my-org-mode-hook)
```
> 0 votes
---
Tags: org-mode, cygwin, emacs-w32
---
|
thread-55890
|
https://emacs.stackexchange.com/questions/55890
|
Is it possible to repeat the last org-mode source block's headers
|
2020-03-03T15:38:34.923
|
# Question
Title: Is it possible to repeat the last org-mode source block's headers
Lately I have been writing a lot of literate sysadmining, writing down my thoughts as I explore systems by executing commands on them. This means that I end up writing the following boilerplate over and over again:
```
#+begin_src bash :dir /ssh:<some-remote-machine>:/
#+end_src
```
I usually just copy this snippet and bring it back from the kill ring whenever needed, but it grows tiresome if you mix this with other operations that populate the kill ring.
It would be handy if I could bring this back using some keybinding or snippet. The shell of a yasnippet doing this would look like:
```
#+begin_src ${1: `(some (code (finding-the-last-used-header-args)))`
#+end_src
```
But for my specific purposes perhaps having only the hostname being picked up would be better, like:
```
#+begin_src bash :dir /ssh:${1: `(code-finding-the-hostname)`:/
#+end_src
```
The result of invoking either one of these snippets in the same buffer as the first code example but below it would result in the exact same text being produced again.
I hope this explains what I'm looking for well enough.
# Answer
> 4 votes
You can set header arguments in Org mode properties (see (org) Using Header Arguments) to avoid repeating, for example, all code blocks in this org file will have `:dir /tmp`
```
#+PROPERTY: header-args :dir /tmp
#+BEGIN_SRC sh
pwd
#+END_SRC
#+RESULTS:
: /private/tmp
```
I also have the following command in my init file, it duplicates the last src block's header, it shows you can use Org Mode's API to access src block's header arguments
```
(defun chunyang-org-babel-copy-previous-src-block ()
"Copy previous src block excluding the content."
(interactive)
(let (result)
(save-excursion
(org-babel-previous-src-block)
(let ((element (org-element-at-point)))
(when (eq (car element) 'src-block)
(let* ((pl (cadr element))
(lang (plist-get pl :language))
(switches (plist-get pl :switches))
(parms (plist-get pl :parameters)))
(setq result
(format
(concat "#+begin_src %s\n"
"\n"
"#+end_src\n")
(mapconcat #'identity
(delq nil (list lang switches parms))
" ")))))))
(and result (insert result))
(previous-line 2)))
```
# Answer
> 0 votes
I want to begin by thanking you xuchunyang so much for your answer. In order to understand how the code worked I broke it down into some smaller functions.
```
(defun org-previous-source-block-headers ()
"Returns the previous source block's headers."
(save-excursion
(org-babel-previous-src-block)
(let ((element (org-element-at-point)))
(when (eq (car element) 'src-block)
(let* ((content (cadr element))
(lang (plist-get content :language))
(switches (plist-get content :switches))
(parms (plist-get content :parameters)))
(delq nil (list lang switches parms)))))))
(defun org-previous-source-block-headers-string ()
"Returns the previous source block's headers as a string."
(mapconcat #'identity
(org-previous-source-block-headers)
" "))
(defun org-previous-source-block-without-content ()
"Returns the previous source block, except its contents."
(format
(concat "#+begin_src %s\n"
"\n"
"#+end_src\n")
(org-previous-source-block-headers-string)))
(defun org-repeat-previous-source-block-without-content ()
"Inserts the previous source block, except the actual code in
the block, into the buffer."
(interactive)
(when-let (result (org-previous-source-block-without-content))
(insert result)
(previous-line 2)))
```
What drove this breakdown was me trying to create a yasnippet from it. I ended up with the following.
```
# -*- mode: snippet -*-
# name: Repeat last source block without content
# key: <r
# --
#+begin_src `(org-previous-source-block-headers-string)`
$1
#+end_src
```
This snippet does exactly what `chunyang-org-babel-copy-previous-src-block` does, but is invoked by typing `<r` and pressing `TAB` instead of some other keybinding.
---
Tags: org-mode, yasnippet
---
|
thread-55912
|
https://emacs.stackexchange.com/questions/55912
|
Temporarily show the documentation for a emacs lisp function
|
2020-03-04T12:51:26.583
|
# Question
Title: Temporarily show the documentation for a emacs lisp function
I want to bind a key which when pressed shows the documentation for an emacs lisp function, but as non-disruptive as possible. I want the contents of `describe-function` but jumping directly to the docs for the symbol I'm at if there is an exact match and shown in a temporary popup, perhaps at the bottom of the screen, that goes away if any key is pressed.
# Answer
> 1 votes
The user thblt@irc.freenode.net#emacs provided the following implementation of a function that shows the documentation in the echo area at the bottom of emacs:
```
(defun showdoc (f)
(interactive (list (thing-at-point 'symbol t)))
(message "%s: %s" f (documentation (intern f))))
```
I noticed that if the docstring was long, as for example with interactive, only the bottom part would be show; but it is often the top that is the most interesting. So I expanded on the function so that it would show the function signature at the top, and only show as many lines that fit in the echo area.
```
(defun elisp-showdoc (f)
(interactive (list (thing-at-point 'symbol t)))
(message
"%s"
(let* ((doc-list (split-string (documentation (intern f)) "\n"))
(number-lines (min (- (floor (* max-mini-window-height (frame-height))) 2)
(- (length doc-list) 2)))
(subset (concatenate 'list
(last doc-list)
'("")
(subseq doc-list 0 number-lines)))
(pruned-subset (if (string-equal (car (last subset)) "")
(butlast subset)
subset)))
(mapconcat #'identity pruned-subset "\n"))))
```
# Answer
> 4 votes
I use eldoc, this screenshot shows the first line of `concat`'s docstring:
```
(define-advice elisp-get-fnsym-args-string (:around (orig-fun sym &rest r) docstring)
"If SYM is a function, append its docstring."
(concat
(apply orig-fun sym r)
(let* ((doc (and (fboundp sym) (documentation sym 'raw)))
(oneline (and doc (substring doc 0 (string-match "\n" doc)))))
(and oneline
(stringp oneline)
(not (string= "" oneline))
(concat " | " (propertize oneline 'face 'italic))))))
```
---
> shown in a temporary popup
You can use tooltip (via the builtin `tooltip-show` or the third party package pos-tip), or overlay (homemade or `popup-tip` from the popup package, or child frame. I believe there also is a package for your purpose (it shows something like Microsoft Clippy alongside?), I can't remember.
---
Tags: help, documentation
---
|
thread-55924
|
https://emacs.stackexchange.com/questions/55924
|
Exclude Cancelled items from Org Mode Agenda
|
2020-03-04T21:52:18.183
|
# Question
Title: Exclude Cancelled items from Org Mode Agenda
is there a straightforward way to exclude an item starting with
```
* CANCELLED
```
from the agenda?
it seems like there is probably an easy way to do this in the docs by setting a variable in init.el but I haven't found it.
thanks
# Answer
> 4 votes
Make CANCELLED one of your TODO states and make sure that it is one of the DONE states. The agenda does not show DONE states by default. For example, add something like the following to the top of the file:
```
#+TODO: TODO DELEGATED WAITING | CANCELLED DONE
```
Press `C-c C-c` on the above line to make sure Org knows about it (or close the file and reopen it). A heading in a TODO state (those to the left of the vertical bar) is potentially shown in the agenda; if it is in a DONE state (those to the right of the vertical bar), it will not be.
This also gives you the ability to change the TODO state using standard methods (`C-c C-t` in the file, `t` in the agenda).
To do the equivalent setup using `org-todo-keywords`, add something like this to your init file:
```
(setq org-todo-keywords '("TODO" "DELEGATED" "WAITING" "|" "CANCELLED" "DONE"))
```
adding a stringified vertical bar at the appropriate place - see TODO keywords as workflow states in the Org mode manual.
There are two variables whose settings might affect the above: `org-agenda-skip-scheduled-if-done` and `org-agenda-skip-deadline-if-done` affect some aspects of whether an item is shown in the agenda: if these variables are non-nil, then a scheduled (resp. deadline) item will *not* be shown in the agenda if it is in a DONE state, but if they are nil, it *will* be shown but only on the relevant date. I recommend that you set them to non-nil for now and revisit them later if necessary.
You should definitely read the TODO chapter of the Org mode manual.
---
Tags: org-mode, org-agenda
---
|
thread-24215
|
https://emacs.stackexchange.com/questions/24215
|
Is it possible to create case-insensitive keywords in a generic-mode?
|
2016-06-27T13:37:38.047
|
# Question
Title: Is it possible to create case-insensitive keywords in a generic-mode?
I am very new to Emacs and I am discovering the functionality of "generic-mode" for the first time. I am trying to add a generic-mode to create basic syntax highlighting for an obscure programming language that I use. It's very simple:
```
;; BEGIN mtl-mode
(define-generic-mode
;; name of mode
'mtl-mode
;; comments
;; '("(*" . "\*)") Opening comment is (* closing is *) but not sure how to do it!
nil
;; keyword list
'("ACV" "CONTACT" "DISCHARGE" "FOR" "MODULE" "REPEAT" "TESTMACRO"
"TRANSF" "WITH" "BITS" "CONTINUE" "ELSE" "IF" "OPTO" "RES"
"TESTPINS" "TYPEOF" "ZENER" "BREAK" "DCI" "IND" "PATGEN"
"RETURN" "TESTMODULE" "UNTIL" "CAP" "DCV" "EXIT" "LED" "PIN"
"TRACK" "CASE" "DIODE" "FET" "LINK" "PULSE" "TESTBLOCK" "TRAN"
"WHILE" "PRINTF" "FFLUSH" "STDOUT"
)
;; font-lock list
'()
;; auto-mode list
'(".*mtl")
;; function list
nil
;; documentation
"Mode for editing Aeroflex ICT MTL files")
;; END mtl-mode
```
This works fine for a start, but the keywords are not actually case sensitive in MTL. Is there a way to specify that they should not be treated as such? Or do I have to add separate keyword cases to the list for each common possibility (e.g. "WHILE" "while")
# Answer
> 3 votes
Font-lock provides a variable, `font-lock-keywords-case-fold-search`, that controls whether keywords should be seen as case sensitive or not:
> Non-nil means the patterns in `font-lock-keywords` are case-insensitive. This is set via the function `font-lock-set-defaults`, based on the CASE-FOLD argument of `font-lock-defaults`.
Normally, when you add font-lock keywords the normal way (using `font-lock-defaults`), you can specify it there. Using `define-generic-mode` you don't have that option. Check if you can add a specific font-lock setup function in the "function list" to do this.
If you have some keywords that are case sensitive and some that are not, things get more complicated. In that case you would have to replace some font-lock keywords regexp:s with your own search functions, that bind `case-fold-search` and do the search using, for example, `search-forward-regexp`.
# Answer
> 1 votes
I tried setting the font lock option inside the function argument, without success. From what I can tell it works after the mode is active, but not before.
This is what I've done to make it work:
```
(define-generic-mode 'my-mode ...)
```
```
(defun case-insensitive-advice ()
(set (make-local-variable 'font-lock-keywords-case-fold-search) t))
(advice-add 'my-mode :after #'case-insensitive-advice)
```
```
(provide 'my-mode)
```
---
Tags: syntax-highlighting
---
|
thread-21559
|
https://emacs.stackexchange.com/questions/21559
|
Specify and use inferior shell only once
|
2016-04-10T19:35:23.597
|
# Question
Title: Specify and use inferior shell only once
I know you can customize settings or set environmental variables to get emacs to use other shells in shell-mode (, ). Is it possible to simply start a shell specifying which shell you want to use interactively?
Like: `M-x other-shell RET /path/to/csh RET`
Or set up something in your init file to let you use other shells fairly easily without changing the default?
# Answer
This appears to do the job:
```
(defun other-shell (explicit-shell-file-name)
(interactive "f")
(if (called-interactively-p)
(call-interactively #'shell)
(shell)))
```
This relies on `shell` using the variable `explicit-shell-file-name` as a first choice of the shell to be used.
It also relies on *not* using lexical scoping.
> 3 votes
# Answer
Building on Harald's answer. If you want to specify the shell by name (interactive "s" option) rather than path and use the default `shell-file-name` instead of the explicit path:
```
(defun other-shell (shell-file-name)
(interactive "s")
(if (called-interactively-p)
(call-interactively #'shell)
(shell)))
```
I found this to be more useful when using a shell like `xonsh` where I just want to use the one in the virtualenv that started emacs, rather than specify long explicit paths.
> 0 votes
---
Tags: shell
---
|
thread-52894
|
https://emacs.stackexchange.com/questions/52894
|
How to open text links (hypertext) firefox with mu4e?
|
2019-09-29T17:29:13.677
|
# Question
Title: How to open text links (hypertext) firefox with mu4e?
I have this function to open links in firefox with mu4e, which I found somewhere here.
```
;; open with firefox
(defun my-browse-url-firefox-new-tab (url &optional new-window)
"Open URL in a new tab in Firefox."
(interactive (browse-url-interactive-arg "URL: "))
(let ((cmd (shell-command-to-string
(concat "~/src/firefox/mozilla-xremote-client -a any 'openURL("
url ",new-tab)'"))))
(unless (string= "" cmd)
(message "Starting Firefox...")
(start-process (concat "firefox " url) nil "/usr/bin/firefox" url)
(message "Starting Firefox...done"))))
(define-key mu4e-view-mode-map (kbd "C-c C-o") #'my-browse-url-firefox-new-tab)
```
My problem is that it only works for "direct" links, not hypertext. If I have a link such as mylink, it displays `URL: http://mylink`, not `URL http://www.example.com`. Can anyone help?
# Answer
For email in text format, `g` will prompt you for the url you want to visit, which you select by number. (The numbers appear next to the link in the message).
For emails in html format, put your cursor on the url you want to visit and type `M-RET`. Please, find more info about Mu4e keybindings here.
You may also be interested by opening the whole email in the browser; by defining a custom action
> 2 votes
# Answer
Pressing `g` followed by a number should open the link in the default browser AFAIK. The problem is how to open links in HTML format.
One way to do this is to create a hash table of all links in the buffer containing the URL and a number assigned to it (similar to how `mu4e~view-make-urls-clickable` works) by searching href anchor properties. There's no general solution AFAICT, so here's one using the default setting:
```
(setq mu4e-html2text-command 'mu4e-shr2text)
(defun mu4e-make-hypertext-clickable ()
(let ((next-url
(lambda ()
(ignore-errors
(goto-char (next-single-property-change (point) 'shr-url))))))
(save-excursion
;; Do nothing if no anchors are found
(when (funcall next-url)
(setq mu4e~view-link-map ; buffer local
(make-hash-table :size 32 :weakness nil))
(let ((c 0))
(remove-overlays)
(goto-char (point-min))
(while (funcall next-url)
(let ((ov (make-overlay (point) (point)))
(num (cl-incf c))
(url (shr-url-at-point nil)))
(puthash num url mu4e~view-link-map)
(overlay-put ov 'before-string
(propertize (format "[%d]" num)
'face 'mu4e-url-number-face)))
(funcall next-url)))))))
(add-hook 'mu4e-view-mode-hook 'mu4e-make-hypertext-clickable)
```
I would also suggest reading this section of the manual.
> 0 votes
---
Tags: org-mode, mu4e
---
|
thread-55919
|
https://emacs.stackexchange.com/questions/55919
|
Copying Column View (Org-Mode)
|
2020-03-04T16:22:55.490
|
# Question
Title: Copying Column View (Org-Mode)
Is there a way to copy the table presented in "column view" as raw text?
# Answer
> 1 votes
As mentioned in my comment, you should look at the Capturing column view section of the Org manual for additional details, but doing
```
M-x org-insert-columns-dblock RET global RET
```
should give you a good beginning.
E.g. given this file:
```
TODO foo
foo
* TODO bar
:LOGBOOK:
CLOCK: [2020-03-05 Thu 07:44]
:END:
bar
```
if you position the cursor at the end of the file and do `M-x org-insert-columns-dblock RET global RET` you will get this:
```
* TODO foo
foo
* TODO bar
:LOGBOOK:
CLOCK: [2020-03-05 Thu 07:44]
:END:
bar
#+BEGIN: columnview :hlines 1 :id global
| ITEM | TODO | PRIORITY | TAGS |
|------+------+----------+------|
| foo | TODO | B | |
|------+------+----------+------|
| bar | TODO | B | |
#+END:
```
If you then change the file (e.g. add another heading), you can update the dynamic block with `M-x org-update-dblock` or just `C-c C-c` on the `#+BEGIN:` line of the block.
---
Tags: org-mode, column
---
|
thread-55934
|
https://emacs.stackexchange.com/questions/55934
|
Key binding to issue another key binding
|
2020-03-05T13:48:02.173
|
# Question
Title: Key binding to issue another key binding
Is there a way to configure emacs so that a key binding will just issue another one? In particular, I want to configure it so that `C-t` replicates (or even better replaces) `backspace`. I couldn't find a way to do it in my Window Manager (I am not even sure if it is at all possible in any Window Manger) so I have to do it in Emacs.
At the moment, I am just mapping `C-t` to `backward-delete-char` but this is not ideal, because many packages map `backspace` and I would have to go over all keymaps and replace `backspace` with `C-t`.
# Answer
A key sequence is just one possible form of a command. So you can just use the following form (if I understand your question right):
```
(global-set-key (kbd "C-t") (kbd "<backspace>"))
```
You can replace `backspace` with `C-t` by translating it in `input-decode-map`:
```
(define-key input-decode-map (kbd "C-t") (kbd "<backspace>"))
(define-key input-decode-map (kbd "<backspace>") [7])
```
The second form replaces `backspace` with the ASCII bell character. The harmless `keyboard-quit` command is bound to that character.
---
Note that there is already a duplicate of this question **but the following statement in that question is wrong**:
> I also tried this:
>
> ```
> (global-set-key (kbd "\C-d") (kbd "<DEL>"))
>
> ```
>
> But it obviously turns every C-d key into , so keybindings such C-c C-d stop working, making this not a suitable solution either.
See also the corresponding comment of VanLaser:
> You say "it obviously turns every C-d key into , so keybindings such as C-c C-d stop working" - are you sure about that? When you press C-c (or C-x, or C-h) another keymap becomes active, in which C-d should NOT be overwritten. As per this doc: https://gnu.org/software/emacs/manual/html\_node/elisp/Prefix-Keys.html
> 2 votes
---
Tags: key-bindings, keymap
---
|
thread-55059
|
https://emacs.stackexchange.com/questions/55059
|
Ligatures with the JetBrains Mono font
|
2020-01-22T14:50:16.587
|
# Question
Title: Ligatures with the JetBrains Mono font
After installing the JetBrains Mono Font and setting it as my default face. I am wandering how to enable Ligatures in Emacs.
I tried a solution based on this answer that show how to do this with Fira Code, with what I think are the required modifications I am speaking about:
---
**EDIT**: @Piquan's answer, suggested to me that I wasn't clear about what are the *required modifications* to the fira-code-mode, so here they are:
* Search and replace from fira-code to jetbrains-mono
* Change the code points from `#Xe100 . #Xe16f` to `#X10001 . #X1009c`
* Update the `jetbrains-ligature-mode--ligatures` constant to reflect the actual character map of the JetBrains Mono font as I see them (using FontForge).
* Since the `#X10001 . #X1009c` contains some diacritics I didn't wish to be part of the resulting `prettify-symbols-alist`, I put some `nil`s into the said constant, and introduced an `(if ...)` expression to the `jetbrains-ligature-mode--make-alist` function to ignore those `nil`s and just increment the code point.
* AFAIK, the reason the Fira Code Ligature was created for Emacs compatibility, is to be compatible with the upstream haskling-mode that used those code points. But since I modified the numbers to be compatible with the *JetBrains Mono* original font, this is not needed.
* I should be able to do without `jetbrains-ligature-mode--setup` function, but I figured out it shouldn't hurt to keep it (and indeed removing it as a troubleshooting step didn't help).
---
Thus the resulting code is:
```
(defun jetbrains-ligature-mode--make-alist (list)
"Generate prettify-symbols alist from LIST."
(let ((idx -1))
(mapcar
(lambda (s)
(setq idx (1+ idx))
(if s
(let* ((code (+ #X10001 idx))
(width (string-width s))
(prefix ())
(suffix '(?\s (Br . Br)))
(n 1))
(while (< n width)
(setq prefix (append prefix '(?\s (Br . Bl))))
(setq n (1+ n)))
(cons s (append prefix suffix (list (decode-char 'ucs code)))))))
list)))
(defconst jetbrains-ligature-mode--ligatures
'("-->" "//" "/**" "/*" "*/" "<!--" ":=" "->>" "<<-" "->" "<-"
"<=>" "==" "!=" "<=" ">=" "=:=" "!==" "&&" "||" "..." ".."
nil nil nil nil nil nil nil nil nil nil nil nil nil nil
"|||" "///" "&&&" "===" "++" "--" "=>" "|>" "<|" "||>" "<||"
"|||>" "<|||" ">>" "<<" nil nil "::=" "|]" "[|" "{|" "|}"
"[<" ">]" ":?>" ":?" nil "/=" "[||]" "!!" "?:" "?." "::"
"+++" "??" "###" "##" ":::" "####" ".?" "?=" "=!=" "<|>"
"<:" ":<" ":>" ">:" "<>" "***" ";;" "/==" ".=" ".-" "__"
"=/=" "<-<" "<<<" ">>>" "<=<" "<<=" "<==" "<==>" "==>" "=>>"
">=>" ">>=" ">>-" ">-" "<~>" "-<" "-<<" "=<<" "---" "<-|"
"<=|" "/\\" "\\/" "|=>" "|~>" "<~~" "<~" "~~" "~~>" "~>"
"<$>" "<$" "$>" "<+>" "<+" "+>" "<*>" "<*" "*>" "</>" "</" "/>"
"<->" "..<" "~=" "~-" "-~" "~@" "^=" "-|" "_|_" "|-" "||-"
"|=" "||=" "#{" "#[" "]#" "#(" "#?" "#_" "#_(" "#:" "#!" "#="
"&="))
(defvar jetbrains-ligature-mode--old-prettify-alist)
(defun jetbrains-ligature-mode--enable ()
"Enable JetBrains Mono ligatures in current buffer."
(setq-local jetbrains-ligature-mode--old-prettify-alist prettify-symbols-alist)
(setq-local prettify-symbols-alist (append (jetbrains-ligature-mode--make-alist jetbrains-ligature-mode--ligatures) jetbrains-ligature-mode--old-prettify-alist))
(prettify-symbols-mode t))
(defun jetbrains-ligature-mode--disable ()
"Disable JetBrains Mono ligatures in current buffer."
(setq-local prettify-symbols-alist jetbrains-ligature-mode--old-prettify-alist)
(prettify-symbols-mode -1))
(define-minor-mode jetbrains-ligature-mode
"JetBrains Mono ligatures minor mode"
:lighter " JetBrains Mono"
(setq-local prettify-symbols-unprettify-at-point 'right-edge)
(if jetbrains-ligature-mode
(jetbrains-ligature-mode--enable)
(jetbrains-ligature-mode--disable)))
(defun jetbrains-ligature-mode--setup ()
"Setup JetBrains Mono Symbols"
(set-fontset-font t '(#X10001 . #X1009c) "JetBrains Mono"))
(provide 'jetbrains-ligature-mode)
```
However the best I got so far is that the sequence is replaced with an empty space (although with the correct length).
What am I missing?
---
I am using Emacs 26.3 (from Kevin Kelley's PPA) on Kubuntu 18.04
# Answer
> 6 votes
You want to do this with composition rules, not with prettify-symbols. Try this instead:
```
(defconst jetbrains-ligature-mode--ligatures
'("-->" "//" "/**" "/*" "*/" "<!--" ":=" "->>" "<<-" "->" "<-"
"<=>" "==" "!=" "<=" ">=" "=:=" "!==" "&&" "||" "..." ".."
"|||" "///" "&&&" "===" "++" "--" "=>" "|>" "<|" "||>" "<||"
"|||>" "<|||" ">>" "<<" "::=" "|]" "[|" "{|" "|}"
"[<" ">]" ":?>" ":?" "/=" "[||]" "!!" "?:" "?." "::"
"+++" "??" "###" "##" ":::" "####" ".?" "?=" "=!=" "<|>"
"<:" ":<" ":>" ">:" "<>" "***" ";;" "/==" ".=" ".-" "__"
"=/=" "<-<" "<<<" ">>>" "<=<" "<<=" "<==" "<==>" "==>" "=>>"
">=>" ">>=" ">>-" ">-" "<~>" "-<" "-<<" "=<<" "---" "<-|"
"<=|" "/\\" "\\/" "|=>" "|~>" "<~~" "<~" "~~" "~~>" "~>"
"<$>" "<$" "$>" "<+>" "<+" "+>" "<*>" "<*" "*>" "</>" "</" "/>"
"<->" "..<" "~=" "~-" "-~" "~@" "^=" "-|" "_|_" "|-" "||-"
"|=" "||=" "#{" "#[" "]#" "#(" "#?" "#_" "#_(" "#:" "#!" "#="
"&="))
(sort jetbrains-ligature-mode--ligatures (lambda (x y) (> (length x) (length y))))
(dolist (pat jetbrains-ligature-mode--ligatures)
(set-char-table-range composition-function-table
(aref pat 0)
(nconc (char-table-range composition-function-table (aref pat 0))
(list (vector (regexp-quote pat)
0
'compose-gstring-for-graphic)))))
```
In order to improve the performance of redisplay, you could take all the ligature patterns that start with the same character, and use `regexp-opt` to produce one regular expression matching all of them, ie use
```
(regexp-opt '("###" "## "####" "#{" "#[" "#(" "#?" "#_" "#_(" "#:" "#!" "#="))
```
as the pattern for `#`.
# Answer
> 0 votes
Per the upstream Fira Code instructions, you have to install the Fira Code Symbol font to use the mechanism being used here. The Fira Code Symbol font is a separate font that has the Fira Code ligatures, but puts them as regular characters in the font so that Emacs can access them. (You may note that the original Fira Code example referred to `"Fira Code Symbol"` rather than `"Fira Code"` in the `set-fontset-font` call.) Without that font, this mechanism won't work.
Unfortunately, I don't know of an analogous symbol font for JetBrains Mono yet, so this solution wouldn't apply. Of course, JetBrains Mono is quite new, so somebody may make one soon!
If somebody does create one, you'll need to make sure that the constant base that you use (`#X10001` in your post), and the order of the elements of `jetbrains-ligature-mode--ligatures`, both match the (theoretical future) JetBrains Mono Symbol font.
---
Tags: fonts
---
|
thread-55927
|
https://emacs.stackexchange.com/questions/55927
|
Integrate Magit with ssh-ident
|
2020-03-04T23:38:21.130
|
# Question
Title: Integrate Magit with ssh-ident
Recently I was looking at utilities for handling ssh-agent at an even higher level, so that entering SSH keys passphrases becomes even more seamless than with the standard ssh-agent utility.
One such utility is ssh-ident, the one I chose as the best solution for my workflow. I have configured my system paths so that Git uses ssh-ident instead of regular ssh, which is what the utility requires in order to work.
However, whenever I have to enter an SSH key passphrase through Magit, I get stuck because Magit does not parse the prompt that this tool issues. I would like to know if it is possible to fix this issue (or, in general, of any solution to have ssh-ident work w/ Magit).
Thank you for your help!
# Answer
### Update:
Magit now supports prompting for the password in the way that ssh-ident asks for it by default, via the variable `magit-process-password-prompt-regexps`. In my case, I had to adjust it as follows:
```
;; Integrate with ssh-ident
(add-to-list 'magit-process-password-prompt-regexps
"^\\(Enter \\)?[Pp]assphrase for [^ ]*: ?$")
(add-to-list 'magit-process-password-prompt-regexps
"^Bad passphrase, try again for [^ ]*: ?$")
```
---
### Old:
I created the emacs-ssh-ident minor mode that adds a hook to Magit when it needs credentials and gets user input for ssh-ident.
> 3 votes
---
Tags: magit, ssh
---
|
thread-55940
|
https://emacs.stackexchange.com/questions/55940
|
How to regexp-search for a word surrounded by spaces
|
2020-03-05T18:23:45.493
|
# Question
Title: How to regexp-search for a word surrounded by spaces
I'm looking at this
> One use of `regexp-quote` is to combine an exact string match with context described as a regular expression. For example, this searches for the string that is the value of string, surrounded by whitespace:
>
> ```
> (re-search-forward (concat "\\s-" (regexp-quote string) "\\s-"))
>
> ```
and wondering how to adapt it to do simply go through the file and search for a word that is surrounded by one or more spaces, i.e., whitespace. I'd like to do it as a regex search in the minibuffer. Tried Search/Regex Forward from the menu, also `M-x :` to type it as a command in the minibuffer -- all to no avail. Once again, I'm lost in a "guess-and-test" loop.
# Answer
Not quite sure what you're looking for. This searches for a word surrounded by whitespace. User input for `read-string` is tested to be sure it is a word.
```
(defun foo (word)
(interactive
(let ((strg (read-string "Word: ")))
(while (not (string-match-p "\\`\\w+\\'" strg)) ; Not a word. Prompt again.
(setq strg (read-string "Word: ")))
(list strg)))
(re-search-forward (concat "\\s-" (regexp-quote word) "\\s-")))
```
But if you're just wanting to search for a word interactively (not necessarily surrounded by whitespace), you can use `word-search-forward` or `word-search-forward-lax`, or for incremental search, just `M-s w`.
> 2 votes
---
Tags: regular-expressions, search, words
---
|
thread-55922
|
https://emacs.stackexchange.com/questions/55922
|
How to prevent LaTeX verbatim environments to be subject to LaTeX-fill-region
|
2020-03-04T17:45:27.417
|
# Question
Title: How to prevent LaTeX verbatim environments to be subject to LaTeX-fill-region
With `LaTeX-verbatim-environments-local`, it is possible to declare environments that AUCTeX should consider as verbatim ones.
```
\documentclass{article}
\begin{document}
\begin{myverbatimenv}
First verbatim line.
Second verbatim line.
\end{myverbatimenv}
\end{document}
% Local Variables:
% LaTeX-verbatim-environments-local: ("myverbatimenv")
% End:
```
The problem is, such environments are subject to `LaTeX-fill-region` (`C-c C-q C-r`). Hence, if the whole buffer is selected (`C-x h)` and is filled (`C-c C-q C-r`), the verbatim environment becomes:
```
\begin{myverbatimenv}
First verbatim line. Second verbatim line.
\end{myverbatimenv}
```
whereas I would like:
```
\begin{myverbatimenv}
First verbatim line.
Second verbatim line.
\end{myverbatimenv}
```
How to prevent these LaTeX verbatim environments to be subject to `LaTeX-fill-region`?
# Answer
Add your self-defined verbatim environment to `LaTeX-indent-environment-list`.
Your modified example would look like this:
```
\documentclass{article}
\usepackage{verbatim}
\begin{document}
This text
just shows
that LaTeX-fill-region does something.
\begin{myverbatimenv}
First verbatim line.
Second verbatim line.
\end{myverbatimenv}
\end{document}
% Local Variables:
% LaTeX-verbatim-environments-local: ("myverbatimenv")
% eval: (setq-local LaTeX-indent-environment-list (cons '("myverbatimenv" current-indentation) (default-value 'LaTeX-indent-environment-list)))
% End:
```
Note the third paragraph in the doc string of `LaTeX-indent-environment-list`:
> `LaTeX-indent-environment-list` is a variable defined in ‘latex.el’. Its value is shown below.
>
> Documentation: Alist of environments with special indentation. The second element in each entry is the function to calculate the indentation level in columns.
>
> **Environments present in this list are not filled by filling functions, see `LaTeX-fill-region-as-paragraph`.**
> 3 votes
# Answer
In case you're using `fancyvrb.sty` to define your custom environment, you only need to hit `C-c C-n` and let AUCTeX parse your document. AUCTeX has a sophisticated style file for `fancyvrb.sty` which takes care of adding your environment to various internal variables. After that, you can do `C-c C-e myverTAB RET` to include it in your document. AUCTeX will support the key-value's provided by `fancyvrb.sty` for your environment as well. This is the file I tested:
```
\documentclass{article}
\usepackage{fancyvrb}
\DefineVerbatimEnvironment{myverbatimenv}{Verbatim}{%
fontsize=\normalsize
}
\begin{document}
\begin{myverbatimenv}[numbers=right]
First verbatim line.
Second verbatim line.
\end{myverbatimenv}
\end{document}
%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:
```
> 1 votes
---
Tags: auctex, fill-paragraph
---
|
thread-55942
|
https://emacs.stackexchange.com/questions/55942
|
Regexp for the inverse of a match
|
2020-03-05T20:13:16.570
|
# Question
Title: Regexp for the inverse of a match
Given a regexp A, how do I derive the inverse regexp B such that given any text exactly one of the two regexes will match it.
For example in the below example:
```
(rx (or (group ---regexpA---) ; a match
(group ---regexpB---))) ; every group of text that's not matched by above
```
It should be the case that the concatenation of the list of matches should be exactly the contents of the buffer.
```
(string= (buffer-string)
(let (string)
(while (re-search-forward regexp nil t)
(setq string (concat string
(or (match-string-no-properties 1)
(match-string-no-properties 2)))))
string))
```
# Answer
Sounds like this is maybe an X Y question. What is it that you're really trying to do?
Except for some simple regexps (e.g. character classes, `[...]`, where `[^...]` means *not*), a regexp *cannot* find a **non**-match. A regexp is not negative.
The way to get the effect of negative matching is to use Elisp to first match and then take the complement, that is, ignore or exclude whatever matches, using Lisp code to do what you want with the text that didn't match a regexp.
> 1 votes
---
Tags: regular-expressions
---
|
thread-17981
|
https://emacs.stackexchange.com/questions/17981
|
Any way to make git errors more prominent in Magit?
|
2015-11-10T13:15:11.477
|
# Question
Title: Any way to make git errors more prominent in Magit?
Whenever Git fails (e.g. if you try to rebase when your working tree has changes), Magit writes the following message:
> Git failed ... \[See buffer \*magit-process: ... for details\]
which is then immediately obscured with other stuff like
> Reverting (up to) 670 file-visiting buffer(s)...
In other words it is *extremely* non-obvious when and why something fails, especially if you don't watch it closely, e.g. commit and switch to a different desktop, for example.
Is there any way to make Magit bark hard when Git underneath it fails, e.g. pop some buffer?
# Answer
> 4 votes
**Edit**: The last error messages is now *also* shown in the status buffer. You'll know it when you see it. But it is only shown in the status buffer - if that buffer is not visible, then the message can only be seen in the echo area. So everything said below about how to make sure you get to see the message there, still applies.
Also note that the message is only shown in the status buffer until that is refreshed.
---
When a git process exits with a non-zero exit status, then magit tries to find an error message in git's output. So usually you should see e.g.:
> Could not read from remote repository. ... \[See buffer \*magit-process: use-package for details\]
`Git failed` is only used if git did not output anything resembling an error message.
---
But you are right, without any user configuration, these error messages are usually drowned in a see of messages about buffers being reverted. The last of these messages reads like this:
> ```
> Reverting 55 file-visiting buffer(s)...done
> This can be undone using `C-/' in the affected buffers
> Customize behavior using `M-x customize-option RET magit-revert-buffers RET'
>
> ```
My hope was that this is verbose enough to annoy users sufficiently to actually bother customizing the mentioned variable. When you do that, then you will get to read its doc-string, which explains that you should set the value to `silent` and (to some extend) why that isn't the default:
> ```
> ‘usage’ Like ‘t’ but include usage information in the summary.
> This is the default so that users come here and pick
> what is right for them.
>
> ‘silent’ Revert the buffers synchronously and be quiet about it.
> This is the recommended setting, because for the other
> values the revert messages might prevent you from
> seeing other, more important, messages in the echo
> area.
>
> ```
So change the value to `silent` and you should get to see the error messages in most cases. There might be other messages which shadow the git error messages in some cases, but that's expected to be rare.
---
The reason we are forcing users to read the doc-string and to change the value from the *actual* default to the *intended* default, is that there is a tiny risk of data loss, when buffers are reverted without the user being aware of it. So we *do* revert by default (because that's very useful), but we do it very verbosely and tell the user how to undo the reverts. (And also suggest that s/he configures the variable, which is the part you missed.)
Q: When could the automatic reverts lead to data-loss?
If the buffer has unsaved changes, then Emacs won't attempt to revert; so no risk here. If the buffer is saved and that caused the file in the working tree to contain uncommitted changes, then git refuses to perform any action which would lose these changes; so no risk here. There only is a risk, if you knowingly use buffers as a staging area (without knowing about the automatic reverts by magit). For example: Make changes, save, and commit. Notice that you should for some reason not have committed. Do a hard reset to `HEAD~`, *expecting the buffer not to be reverted*. What you should do instead (as in "take full advantage of Git and the nice wrapping provided by Magit") is a soft reset, but ...
Q: So if the risk of data loss is tiny, why are you doing all that?
... not every user might realize that, so we play it safe.
Q: But...?!
See https://github.com/magit/magit/issues/1809.
# Answer
> 2 votes
I believe I have an answer to this part of the question:
> Is there any way to make Magit bark hard when Git underneath it fails, e.g. pop some buffer?
This snippet makes the process buffer open after a git error:
```
(defun auto-display-magit-process-buffer (&rest args)
"Automatically display the process buffer when it is updated."
(let ((magit-display-buffer-noselect t))
(magit-process-buffer)))
(advice-add 'magit-process-set-mode-line-error-status :before
#'auto-display-magit-process-buffer)
```
I modfied a snippet I found on the Tips and Tricks section of the magit wiki: Automatically displaying the process buffer.
The original snippet opens the process buffer whenever it is written to, regardless of error or success. For example, when you push successfully.
I changed `magit-process-insert-section` to `magit-process-set-mode-line-error-status`.
This solved my specific problem: from time to time I push and that push takes a while and then fails. In the mean time I look somewhere else and miss the error.
---
Tags: magit
---
|
thread-55949
|
https://emacs.stackexchange.com/questions/55949
|
mutilpe add-hook merge to one?
|
2020-03-06T07:25:19.450
|
# Question
Title: mutilpe add-hook merge to one?
On my config i have too many `add-hook`,Is there any way to merge them and make them more beautiful.
```
(add-hook 'go-mode-hook #'my-go-project-setup)
(add-hook 'go-mode-hook #'lsp-deferred)
(add-hook 'go-mode-hook #'lsp-go-install-save-hooks)
(add-hook 'go-mode-hook #'rainbow-delimiters-mode)
(add-hook 'go-mode-hook #'galaxy/go-defun-setup)
```
maybe write a macro is best? then it will like this? how to write this macro or other best way?
```
(add-hook-x 'go-mode-hook #'lsp-deferred
#'lsp-go-instal-save-hooks
...)
```
# Answer
No need for a macro, all you need is a function doing a loop:
```
(defun add-hook-x (hook &rest functions)
(dolist (function functions)
(add-hook hook function)))
```
There isn't really a need for this either once you realize that you can bundle all these functions added to the hook into a single function:
```
(defun my-go-mode-setup ()
(my-go-project-setup)
(lsp-deferred)
(lsp-go-install-save-hooks)
(rainbow-delimiters-mode)
(galaxy/go-defun-setup))
(add-hook 'go-mode-hook #'my-go-mode-setup)
```
For the opposite case where you want to add a single function to many hooks you might find this question of mine useful: How do I "group" hooks?
> 5 votes
---
Tags: hooks
---
|
thread-55951
|
https://emacs.stackexchange.com/questions/55951
|
Confirm command by pressing same key that invoked it
|
2020-03-06T10:10:17.280
|
# Question
Title: Confirm command by pressing same key that invoked it
I have `<f5>` bound to `projectile-run-project`. When pressing `<f5>`, the minibuffer displays the command to run and you need to press `RET` to confirm it.
How can I add the behavior that when `<f5>` is pressed again, it acts as a `RET` to confirm and execute the command?
UPDATE: my working projectile config after the answer from @Tobias
```
(use-package projectile
:init (setq
projectile-project-search-path '("c:/repo") ;; todo make variable and declare it in paths
projectile-enable-caching t
projectile-completion-system 'helm
projectile-indexing-method 'native)
(add-hook 'ibuffer-hook
(lambda ()
(ibuffer-projectile-set-filter-groups)
(unless (eq ibuffer-sorting-mode 'alphabetic)
(ibuffer-do-sort-by-alphabetic))))
;; projectile-globally-ignored-file-suffixes
;; (append '("S" "elf" "o") projectile-globally-ignored-file-suffixes))
:bind-keymap
("C-c p" . projectile-command-map)
:bind
("<f5>" . projectile-run-project)
:config (projectile-mode +1))
(defun my-read-shell-command-key-wrapper (oldfun &rest args)
"Wrapper for `projectile-run-project' that temporarily adds <f5> to the keymap."
(let ((minibuffer-local-shell-command-map (copy-sequence minibuffer-local-shell-command-map)))
(define-key minibuffer-local-shell-command-map (kbd "<f5>") (kbd "RET"))
(apply oldfun args)))
(advice-add 'projectile-run-project :around #'my-read-shell-command-key-wrapper)
```
# Answer
The working horse of `projectile-run-project` is `projectile--run-project-cmd` which uses indirectly `read-shell-command`.
I don't have `projectile` but I demonstrate here how you can implement the binding of `f5` with a simple example that works for me in Emacs 26.3. You can just replace `example-shell-command` in the `advice-add` with `projectile-run-project`. Naturally, in your usecase you do not need the definition of `example-shell-command` anymore.
```
(defun my-read-shell-command-key-wrapper (oldfun &rest args)
"Wrapper for `projectile-run-project' that temporarily adds <f5> to the keymap."
(let ((minibuffer-local-shell-command-map (copy-sequence minibuffer-local-shell-command-map)))
(define-key minibuffer-local-shell-command-map (kbd "<f5>") (kbd "RET"))
(apply oldfun args)))
(defun example-shell-command ()
"Example: Read and call shell command."
(interactive)
(shell-command (read-shell-command "Shell command:")))
(advice-add 'example-shell-command :around #'my-read-shell-command-key-wrapper)
```
> 2 votes
---
Tags: key-bindings
---
|
thread-55921
|
https://emacs.stackexchange.com/questions/55921
|
org-indent-mode prevents first-line paragraph indents
|
2020-03-04T17:37:47.957
|
# Question
Title: org-indent-mode prevents first-line paragraph indents
I'm a writer (non-programmer) using `org-mode` mainly for prose notes/planning and writing.
I'm trying to enable first-line paragraph indents for text under Org headings. I discovered `paragraph-indent-mode`, and after enabling it to no effect, I finally realized that it doesn't work, and Org's normal ability to first-line indent also doesn't work, when `org-indent-mode` is enabled. With the latter enabled, `M-i` indents the whole paragraph.
Are the two features incompatible? Ideally I would have my text body indented under the headline as per normal `org-indent-mode`, and then `M-i` would allow me to further indent the first line of a paragraph from the new margin (if I wanted to).
E.g.,
```
* org heading
a paragraph nicely indented and aligned to the heading text (thx org-indent, you're really great, i'd hate to have to lose you just to enable first-line paragraph indents!). sentence sentence blah blah waffle waffle
a new first-line indented prose paragraph starting here.
and back to non-indented new paragraph still possible if i wanted to.
```
The idea is just to have the two types of paragraph breaks available.
I also have `variable-pitch-mode` and `org-bullets-mode` enabled.
edit: * M-i is bound to tab-to-tab-stop.
* i'm running emacs 26.1 and org latest from melpa (9.3)
* if i first run org-fill-paragraph, then the indentation works, but i don't at all like the idea of using that for my writing.
* (i also have indent-tools installed (but disabled by default in org buffers). if i run indent-tools-indent, i also get whole paragraph indenting.)
# Answer
What you're trying to do is not possible with `org-indent-mode` turned on. Maybe you can trick the mode by inserting some invisible character before inserting the space/tab:
```
(defun org-indent-paragraph ()
(interactive)
(forward-line 0)
(if (looking-at "^¶")
(while (looking-at "^¶\\|[ \t]")
(delete-char 1))
(insert (propertize "¶" 'font-lock-face 'org-hide))
(insert "\t")))
(add-to-list 'org-export-filter-plain-text-functions
(lambda (text _backend _info)
(replace-regexp-in-string "¶" "" text)))
```
> 1 votes
---
Tags: org-mode, indentation, paragraphs
---
|
thread-28055
|
https://emacs.stackexchange.com/questions/28055
|
Inherit SCHEDULED and priority properties
|
2016-10-23T21:52:07.683
|
# Question
Title: Inherit SCHEDULED and priority properties
What is the reasoning behind the design of not inheriting the SCHEDULED and priority properties?
Any notable use cases to support this behavior?
On the contrary, actually inheriting SCHEDULED (or DEADLINE for that matter) and priority properties makes perfect sense to me.
For instance, if an entry is SCHEDULED and thus is appearing in the week agenda, adding a sub-item to it will automatically bring that item to agenda replacing the parent. This will prevent the parent from falling out of attention. In the current design you may loose a DEADLINE task forever by adding a sub-task to it without scheduling it.
# Answer
> 1 votes
Not sure if this is still relevant in 2020, but I needed something similar and so I modified `org-get-entry` to allow for inheriting special properties (by passing `'t` to `INHERIT`). Leaving this here in case someone needs it
```
(defun org-entry-get-special-with-inheritance (property &optional literal-nil)
"Same as org's `org-entry-get-with-inheritance' but for special properties"
(move-marker org-entry-property-inherited-from nil)
(org-with-wide-buffer
(let (value)
(catch 'exit
(while t
(let ((v (org-entry-properties nil property)))
(cond
(v
(setq value (cdr (assoc-string property v)))
(org-back-to-heading-or-point-min t)
(move-marker org-entry-property-inherited-from (point))
(throw 'exit nil))
((org-up-heading-or-point-min))
(t
(let ((global (org--property-global-or-keyword-value property literal-nil)))
(cond ((not global))
(value (setq value (concat global " " value)))
(t (setq value global))))
(throw 'exit nil))))))
(if literal-nil value (org-not-nil value)))))
(defun org-entry-get (pom property &optional inherit literal-nil)
"Same as org's `org-get-entry' but allows inheriting special properties"
(org-with-point-at pom
(let ((special (member-ignore-case property (cons "CATEGORY" org-special-properties)))
(inherit (and inherit
(or (not (eq inherit 'selective)) (org-property-inherit-p property)))))
(cond
((and special (not inherit))
(cdr (assoc-string property (org-entry-properties nil property))))
((and special inherit)
(org-entry-get-special-with-inheritance property literal-nil))
((and (not special) inherit)
(org-entry-get-with-inheritance property literal-nil))
(t
(let* ((local (org--property-local-values property literal-nil))
(value (and local (mapconcat #'identity (delq nil local) " "))))
(if literal-nil value (org-not-nil value))))))))
```
---
Tags: org-mode, org-agenda, todo
---
|
thread-55955
|
https://emacs.stackexchange.com/questions/55955
|
Nonexistent newline on display after using outorg
|
2020-03-06T15:24:15.663
|
# Question
Title: Nonexistent newline on display after using outorg
I'm using outorg to convert an elisp file to an org file and then back to an elisp file via `(outorg-convert-to-org)` and `(outorg-convert-back-to-code)`. When I do this conversion I notice that it looks like there is an extra newline between headlines and source blocks. On the image below the left is my original elisp file and the right is after the conversions. It seems as if the conversion added an extra newline between the comment and the code. However, when saving the contents of the buffers before and after conversion and testing for this via `(string= original-buffer-contents after-conversion-contents)` I get `t`. So the buffer contents are the same.
Upon further investigation, I can't move the cursor over the "extra newline". It always skips it. I suspect that there is no actual newline added to the buffer contents and this is some sort of visual (bug?) thing.
What's happening here? And how can I prevent this "extra newline" from displaying?
UPDATE: This is what is displayed when I use `describe-char` just before the (nonexistent?) newline. The character is described as a newline.
Another thing I found interesting is what happens when I try to delete it (e.g. by putting my curser before the `(defvar` and pressing backspace). If the extra newline existed, pressing backspace twice should leave the commented line on the line above `(defvar` line. However when I press backspace twice (the right window in the picture below) the two lines are joined on the same line indicating the extra new line is not really there.
The left window is the result of pressing backspace one time on the original buffer.
# Answer
You enabled whitespace visualization (Whitespace mode), you can disable the mode using `M-x whitespace-mode`. If you use the mode, you can change the option `whitespace-style` to choose which kind of whitespace to visualize.
> 0 votes
---
Tags: characters
---
|
thread-55959
|
https://emacs.stackexchange.com/questions/55959
|
How do I set evil mode to use the normal state by default in Customize mode?
|
2020-03-06T21:38:29.540
|
# Question
Title: How do I set evil mode to use the normal state by default in Customize mode?
When I open the Easy Customization in Emacs, I want to be in `normal` mode instead of `emacs` mode. Is that possible?
# Answer
> 1 votes
Insert the following line in your Emacs config:
```
(evil-set-initial-state 'Custom-mode 'normal)
```
**NOTE**: The capitalization of `'Custom-mode` matters here!
---
Tags: evil, customize
---
|
thread-55964
|
https://emacs.stackexchange.com/questions/55964
|
How to get emacs to keep cursor in the middle of buffer during search?
|
2020-03-06T23:03:15.413
|
# Question
Title: How to get emacs to keep cursor in the middle of buffer during search?
(I am using Aquamacs 3.5 which is based on GNU Emacs 25.3.50.1, in case this matters.)
While searching (`isearch-forward`) in a buffer it often happens that I need to see some lines before/after the matched string. It happens regularly (as shown in the screenshot below) that the matched string appears at the bottom of the buffer. In that case I was searching for `[h!]` and there is not even one line showing below the matched line.
I tried to customise the variable `list-matching-lines-default-context-lines` without success. In the screenshot above `list-matching-lines-default-context-lines` was set to 5. I suspect that `isearch` does not pay attention to that variable.
```
list-matching-lines-default-context-lines is a variable defined in ‘replace.el’.
Its value is 5
Original value was 0
Documentation:
Default number of context lines included around ‘list-matching-lines’ matches.
A negative number means to include that many lines before the match.
A positive number means to include that many lines both before and after.
```
Is there a variable I can set to get the desired behaviour?
# Answer
You can just use `C-l` at any time during Isearch, to center the current search hit vertically in the window.
> 1 votes
---
Tags: isearch, scrolling
---
|
thread-55316
|
https://emacs.stackexchange.com/questions/55316
|
Setup find-file-at-point to treat tilde as project root
|
2020-02-05T08:20:19.943
|
# Question
Title: Setup find-file-at-point to treat tilde as project root
A JavaScript project is setup with webpack path resolver like this:
```
resolve: {
alias: {
'~': path.resolve(cwd, 'src')
}
},
```
This has the effect that a line in `c:/projects/myproject/src/models/User.js`
```
import '~/config/global';
```
will point to `c:/projects/myproject/src/config/global.js`.
Can I setup `find-file-at-point` (or any other interactive function) so that when in `User.js` the point is at the file path `~/config/global.js` and I invoke `f-f-a-p` (or other magic), the `global.js` file is opened?
I.e., can I replace the meaning of `~` on a per-project or global basis?
This is Windows 10 if it makes a difference.
# Answer
> 1 votes
This custom function finds the file as described by looking for the `src` directory of the file currently being visited and assumes that the directory one above is the `cwd`.
As a consequence it only works if used while visiting a file somewhere inside the `src` directory else it will not find the `cwd`.
```
(defun my-find-file-at-point-with-tilde ()
"Find the file at point changing tilde to project root."
(interactive)
(let* ((current-filename buffer-file-name)
;; Get cwd from filename.
(cwd (car (split-string current-filename "/src/")))
;; Get filename at point.
(filename-at-point (thing-at-point 'filename))
;; Replace ~ with src
(filename-stripped (replace-regexp-in-string "~" "src" filename-at-point))
;; Get the filename with cwd and the stripped filename.
(filename (expand-file-name filename-stripped cwd)))
(if (file-exists-p filename)
(find-file filename)
(user-error "File %s does not exist" filename))))
```
Evaluate the function or add it to your init file and then call it with `M-x my-find-file-at-point-with-tilde RET` while point is at `~/config/global.js`.
> *Remark:<br>It would be probably better to use something else than the tilde as this is usually reserved for the home directory and might confuse others.*
# Answer
> 1 votes
Use https://github.com/technomancy/find-file-in-project (ffip).
What `~` means does not matter. ffip will try to find file in project root using the file name under cursor.
Example, https://emacs.stackexchange.com/a/50567/202
---
Tags: find-file, javascript, project
---
|
thread-9982
|
https://emacs.stackexchange.com/questions/9982
|
How do use Emacs to look up a function in Python?
|
2015-03-13T06:55:52.007
|
# Question
Title: How do use Emacs to look up a function in Python?
What is the easiest way to configure Emacs to be able to look up where a function is defined? I want to highlight it in Emacs and press a key combo to look up where the source of the function is.
Can you also find out where a specific function is being used?
This is easily done in PyCharm, but can it also be easily done in Emacs?
# Answer
> 18 votes
Did you try Elpy? It binds `elpy-goto-definition` to the key `M-.`.
If you have a recent Emacs, I think you can also jump back with `xref-pop-marker-stack` (`M-,`). Elpy has some other nice features as well.
To install it, follow the instructions in the link.
# Answer
> 12 votes
I use Jedi mode for Python and I'm very happy with it. Not only does it do accurate look ups for function calls, it resolves functions to the correct definition even in complicated situations (like inheritance). Comes with auto complete to boot. http://tkf.github.io/emacs-jedi/latest/
# Answer
> 10 votes
The feature of PyCharm that you mention was one of my favourites, and one of the first things I looked for in trying to replace PyCharm completely with Emacs (which I am happy to say I have been able to do).
As mentioned in another answer the `elpy` package has this feature (in addition to many other useful IDE features). However, if you use `elpy-goto-definition` to look up the symbol at point, you will find sooner or later that in some cases where PyCharm would succeed in finding what you are looking for, `elpy` will not. As the docs say:
> the backends can not always identify what kind of symbol is at point. Especially after a few indirections, they have basically no hope of guessing right, so they don’t
In this case, invoking `elpy-goto-definition` will do nothing and show a little error message in the echo area. When this happens, of course you still want to find what you are looking for, and `elpy` doesn't leave you hanging. In this kind of situation I always use `C-c C-s` (`elpy-rgrep-symbol`) to `rgrep` for the symbol at point in whatever project I am in. At least for me, the thing I am looking for more or less always shows up in the `rgrep` results. Actually, I think this is similar to what PyCharm does too: if you try to look up the definition of something and PyCharm is not sure where it is defined, it will have you choose from a list. I actually prefer `elpy`'s implementation, because rather than a transient list that disappears when you go to the first option, `elpy-rgrep-symbol` will leave the list of possibilities open in another buffer so that you can jump back and forth between them if necessary.
Since my workflow is almost always to first call `elpy-goto-definition` and if it fails, call `elpy-rgrep-symbol`, I decided to hack together a simple function that just calls `elpy-rgrep-symbol` automatically if `elpy-goto-definition` fails. That function is below:
```
(defun goto-def-or-rgrep ()
"Go to definition of thing at point or do an rgrep in project if that fails"
(interactive)
(condition-case nil (elpy-goto-definition)
(error (elpy-rgrep-symbol (thing-at-point 'symbol)))))
```
Then I bind this to `M-.` (the default binding for `elpy-goto-definition`).
```
(define-key elpy-mode-map (kbd "M-.") 'goto-def-or-rgrep)
```
This way I can use one of my favorite PyCharm features in my favorite editor. I know this is kind of an old question and you may have already solved this problem or moved on, but I hope you or someone else finds this useful!
# Answer
> 3 votes
python-mode.el provides a command `py-find-definition` \- see in menu Help.
# Answer
> 2 votes
`M-.` works in anaconda-mode (which I switched to after having problems with elpy).
Note that you need proper python environment, in my case I do the following:
* `mkvirtualenv someenv`
* `python setup.py develop` for all modules develop or use (or prefer to reach source instead of installed version)
* `M-x venv-workon RET someenv` to enable paths in Emacs.
Then I configure `anaconda-mode` to be active whenever I edit python and voila, `M-.` works
# Answer
> 1 votes
Good question, that isn't available out of the box and is a handy feature of full blown IDEs. I do that with `cscope`, with a nice helm interface: http://wikemacs.org/wiki/Python#cscope It can answers questions like "where is this symbol defined ? Where is it used ?".
ps: in evil-mode we can go to the definition of a symbol in the same file with `gd`.
# Answer
> 1 votes
`M-.` which is bound to `elpy-goto-definition` will do the trick. Use `M-*` will let you jump back to the previous location int he buffer. This allows you to quickly check something and go back to the previous location.
I also use `C-c C-o` often (`elpy-occur-definitions`). This will open a window with all class and function is the current buffer. From that buffer, pressing `Enter` will land you on the definition in the source code.
# Answer
> 1 votes
Today there is a wonderful development called LSP. Python is supported.
> Client for Language Server Protocol (v3.14). lsp-mode aims to provide IDE-like experience by providing optional integration with the most popular Emacs packages like company, flycheck and projectile.
Emacs client/library for the Language Server Protocol
# Answer
> 0 votes
Jedi is an awesome autocompletion/static analysis library for Python.I used it a lot back to when I was using vim.
Just like the golang autocompletion engine(i.e. gocode) works both for vim and emacs, the same Jedi engine works both for vim and emacs.
# Answer
> 0 votes
For jedi we can use `jedi:goto-definition` to jump to definition.
---
Tags: python, development
---
|
thread-36628
|
https://emacs.stackexchange.com/questions/36628
|
How to graphically represent Meta characters
|
2017-11-05T12:55:40.017
|
# Question
Title: How to graphically represent Meta characters
Given that the variable `x` contains the numeric representation of the key "Control-Z", say
```
(setq x ?\C-z),
```
one may graphically represent its contents by issuing the command
```
(char-to-string x),
```
producing the usual representation of "Control-Z", namely "^Z". I would like to acheive a similar effect in case `x` contained the numeric representation of "Meta-Z", namely
```
(setq x ?\M-z).
```
However my system represents "Meta-Z" as the number 134217850, and `(char-to-string x)` now causes the error `(wrong-type-argument characterp 134217850)`. I am aware that the graphical representation of "Meta-Z" is not as standard as for "Control-Z", since the latter is part of the ASCII code while the former isn't, but anything legible, such as "M-Z" would be better than the big number 134217850.
My question is thus: which standard elisp function should I use in order to transform numerical representations of Meta characters into a legible string?
# Answer
Properly speaking, `?\C-z` is the *read syntax* of the character. Internally, the Lisp object is an integer. Nonetheless, characters in strings may have different character codes \[2\]. In other words, a similar read syntax does not necessarily produce the same Lisp object.
You can see in the following example that the character codes are different: `134217818` and `218`.
```
ELISP> ?\M-Z
134217818
ELISP> "\M-Z"
"\332"
ELISP> ?\332
218
```
Characters inserted in text must be in the range of 0 to 4194303. Extra characters, typed using modifier keys, are used to represent keyboard inputs. \[1\]
In summary, you cannot use a string (*read syntax*) to represent a meta character. For a conversion function, look at \[3\].
```
(single-key-description ?\M-z)
```
### References
> 0 votes
---
Tags: key-bindings, help, keystrokes
---
|
thread-55983
|
https://emacs.stackexchange.com/questions/55983
|
Is there any way to write html code inside org table that properly be exported as html?
|
2020-03-08T01:12:57.933
|
# Question
Title: Is there any way to write html code inside org table that properly be exported as html?
I want to put one line html code inside org table. I wrote following text(see Input below) in org-mode and exported it to html and opened in my browser(see Output below). But the output is not what I expected.
**Input(sample.org):**
```
| No | html code | desc |
| 1 | #+HTML: <p>hoge</p> | hoge |
```
**Output(sample.html):**
My expected output is below.
**Expected output(sample.html):**
Is there any way to do this?
# Answer
I cite from https://orgmode.org/manual/Quoting-HTML-tags.html:
> The HTML export back-end transforms `<` and `>` to `<` and `>`. To include raw HTML code in the Org file so the HTML export back-end can insert that HTML code in the output, use this inline syntax: `@@html:...@@`. For example:
>
> `@@html:<b>@@bold text@@html:</b>@@`
In the following example I use `<i>` instead of `<b>` to separate the formatting from the formatting of the table heading.
```
| my | table |
|----+--------------------------------------|
| | @@html:<i>@@italic text@@html:</i>@@ |
```
Rendered result:
> 5 votes
---
Tags: org-mode, org-export
---
|
thread-55962
|
https://emacs.stackexchange.com/questions/55962
|
Highlight syntax of function names and their arguments in custom mode
|
2020-03-06T22:49:44.803
|
# Question
Title: Highlight syntax of function names and their arguments in custom mode
I'm trying to create a major mode that handles the following syntax:
```
function someName(value1, value2)
# some contents
end function
```
I'm using the following to highlight the keywords `function`, and `end function`.
```
(define-derived-mode my-mode prog-mode "My Mode"
"Major mode for editing my mode code."
(setq-local font-lock-defaults
'(my-mode-font-lock))
```
How can I target the function name (`someName`) and its arguments with font lock (`value1`, `value2`)?
# Answer
In my "my-mode-font-lock" function, this is what I ended up using:
```
; This regexp matches "function someName(", and sets a font face to "someName"
("^[[:space:]]*?sub\\(?:[[:space:]]*\\)?\\([[:word:]]+\\)?\\(?:[^( \t\n]\\)?"
(1 font-lock-function-name-face)
; This starts at the end of the previous regexp
; It matches everything up to "," or ")" - whichever comes first
; The ".*" is there to allow extra information, such as "someName(value1 as String)"
("\\([[:word:]]+\\).*?\\(?:,\\|)\\)"
(save-excursion
(goto-char (match-end 0))
(backward-char)
(ignore-errors
(forward-sexp))
(point))
; Once a match was found, it tries the find another, beginning at the end of the last result
(goto-char (match-end 0))
(1 font-lock-variable-name-face)))
```
> 0 votes
---
Tags: major-mode, font-lock, syntax-highlighting
---
|
thread-55977
|
https://emacs.stackexchange.com/questions/55977
|
Make/unmake a variable globally buffer-local depending on another variable
|
2020-03-07T18:51:17.760
|
# Question
Title: Make/unmake a variable globally buffer-local depending on another variable
I have a package with the variable `my-package--my-var` that needs to be buffer-local when `my-package-buffer-only` is `t` but global if `my-package-buffer-only` is `nil`. This is what I have so far:
```
(defcustom my-package-buffer-only nil
:type 'boolean
:set (lambda (sym val)
(when val
(make-variable-buffer-local 'my-package--my-var))
(set-default sym val)))
(defvar my-package--my-var nil)
```
The problem is that I can't find a way to make the variable global again if `my-package-buffer-only` is set to `nil`.
# Answer
> 0 votes
Thanks to the answer from Tobias I realized that I can do what I want by using a function instead of a variable. `my-package--my-var` returns/sets the local value if `my-package-buffer-only` is set and the global value otherwise.
```
(defcustom my-package-buffer-only nil
:type 'boolean)
(defvar-local my-package--my-var-v nil)
(defun my-package--my-var (&optional val)
"Return `my-package--my-var-v' or set it if VAL is non-nil.
Use the local value if `my-package-buffer-only' is set and the global value
otherwise."
(if val
(if my-package-buffer-only
(setq my-package--my-var-v val)
(setq-default my-package--my-var-v val))
(if my-package-buffer-only
my-package--my-var-v
(default-value 'my-package--my-var-v))))
```
# Answer
> 0 votes
Note, I have a strange feeling about your wish making a local variable `var` global:
1. You can always access the global value of `var` with `(default-value 'var)`.
2. You can set the global value of a local variable with `(setq-default var val)`.
3. Maybe, you should have a global version `var` **and** a local version `var-local` of your variable. AFAIK that is how most modes deal with variables that can have a global (default) value and a local value.
Nevertheless, the following lisp snippet defines two functions related to your wish. The predicate `lispTZA-variable-made-buffer-local-p` tells you whether `make-variable-buffer-local` was applied to a variable and `lispTZA-make-variable-global` gives a symbol a fresh start as global variable.
```
(defun lispTZA-variable-made-buffer-local-p (var)
"Return t if VAR is local_if_set.
This is the case if `make-variable-buffer-local' was applied to VAR."
(with-temp-buffer
(local-variable-if-set-p var)))
(defun lispTZA-make-variable-global (var)
"Give VAR a fresh start forgetting about localness."
(let ((name (symbol-name var))
(val (default-value var))
(plist (symbol-plist var))
(fun (symbol-function var))
(special (special-variable-p var))) ;; Hm, should always be t. Maybe worth an assert?
(unintern name obarray)
(setq var (intern name)) ;; Here we have a fresh start.
(when special
(eval `(defvar ,var)))
(set var val)
(setf (symbol-plist var) plist)
(fset var fun)))
```
---
Tags: variables, buffer-local
---
|
thread-55822
|
https://emacs.stackexchange.com/questions/55822
|
using tramp over aws ssm proxycommand
|
2020-02-27T16:00:41.737
|
# Question
Title: using tramp over aws ssm proxycommand
I'm trying to get tramp to use my ProxyCommand from my ~/.ssh/config (pasted below), specifically for AWS SSM. Should I expect this ProxyCommand to work, maybe something is wrong with my environment or how I'm invoking tramp? Or would tramp need changes to its source to support AWS SSM?
I try `C-x C-f /ssh:i-8746484eadb75:/var/log` and it asks me if I want to create the directory or file y/n - never seems to even try connecting to the remote host or looking at my ~/.ssh/config and ProxyCommand.
Any pointers or direction would be most welcome, TIA!
```
Host i-* mi-*
ProxyCommand sh -c "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p'"
User ec2-user
```
I'm using emacs 26.3 (9.0) on osx catalina 10.15.3.
# Answer
Using the temporary test AWS account, I have been able to access that file system via Tramp. Necessary configs are
1. If you use another AWS profile but `default`, you shall tell it to Emacs. Add to your `~/.emacs`
```
(setenv "AWS_PROFILE" "my_profile")
```
2. Add your private key file to `~/.ssh/config`
```
Host i-* mi-*
ProxyCommand sh -c "aws ssm start-session --target %h --document-name AWStartSSHSession --parameters 'portNumber=%p'"
User ec2-user
StrictHostKeyChecking no
IdentityFile ~/.ssh/id_rsa_aws
```
> 3 votes
---
Tags: tramp, ssh
---
|
thread-36988
|
https://emacs.stackexchange.com/questions/36988
|
configure chooses the "wrong" libraries
|
2017-11-20T14:20:09.883
|
# Question
Title: configure chooses the "wrong" libraries
I'm trying to build Emacs 26 from source but `make` fails
```
./temacs --batch --load loadup bootstrap
./temacs: error while loading shared libraries: libjpeg.so.9: cannot open shared object file: No such file or directory
```
If I search for `libjpeg.so` I have
```
$ locate libjpeg.so
/home/boffi/Downloads/processing-3.3.5/java/lib/amd64/libjpeg.so
/home/boffi/lib/miniconda3/lib/libjpeg.so
/home/boffi/lib/miniconda3/lib/libjpeg.so.9
/home/boffi/lib/miniconda3/lib/libjpeg.so.9.2.0
/home/boffi/lib/miniconda3/pkgs/jpeg-9b-habf39ab_1/lib/libjpeg.so
/home/boffi/lib/miniconda3/pkgs/jpeg-9b-habf39ab_1/lib/libjpeg.so.9
/home/boffi/lib/miniconda3/pkgs/jpeg-9b-habf39ab_1/lib/libjpeg.so.9.2.0
/usr/lib/x86_64-linux-gnu/libjpeg.so
/usr/lib/x86_64-linux-gnu/libjpeg.so.62
/usr/lib/x86_64-linux-gnu/libjpeg.so.62.2.0
```
and it seems to me that Emacs is not looking at the system libraries...
Grepping the output of configure I have another suspicious line
```
$ ./configure | grep miniconda
Does Emacs use a png library? yes - L/home/boffi/lib/miniconda3/lib -lpng16
```
My question is, how can I screen the libraries installed by the Anaconda Python Distribution for its own use, so that `./configure` does not mess with them?
Or, on the other hand, how can I have `temacs` and later Emacs find the library they expect to load?
# Answer
Emacs uses the "libpng-config" tool to locate PNG include files and libraries. So yes, if you have multiple versions installed you need to adjust PATH so that the one you want to be used, is. For other libraries, it's normally "pkg-config" that is consulted, for which there is the PKG\_CONFIG\_PATH environment variable. If Anaconda provides a pkg-config, it probably prefers Anaconda packages, so again adjusting PATH is probably the right solution.
> 2 votes
# Answer
### TL;DR `export PATH=/usr/bin:/bin`
I had a look at `config.log` to see where `configure` mentioned the paths used by the Anaconda distribution and I found 3 references to `miniconda3` — 2 were related to the PNG libraries and one to the `PATH` variable... of course the `bin` directory of the Anaconda distribution has to be prepended to `PATH`, hasn't it?
To be sure that was not a problem with my `PATH` I issued the command
```
$ PATH=/usr/bin:/bin ./configure 2>/dev/null | grep -qs miniconda || make
...
make[1]: Leaving directory '/home/boffi/src/emacs-26.0.90'
$
```
I have now a way to shade private Anaconda libraries from the scrutiny of `configure`, I have an instance of Emacs 26 too and eventually I have the doubt that `configure` had been too smart in deducing too much from my `PATH`.
---
ps I'm not going to approve my answer because it seems to me just a workaround, I'm convinced that a better solution is possible.
> 3 votes
# Answer
The above answers fixed the problem but in my case I couldn't have `/usr/bin` before my conda path. This is because I'm using a cluster and I need specific tools with versions that I install in my conda. Putting `/usr/bin` in front prioritize those installed by admin before my own installs. Of cource I can then prepend another folder that contains symlinks pointing to the right versions (essentially everything inside `conda/bin` except for `libpng-config`) but that's lame and a lot of work.
What I did was simply install Emacs inside conda, install ligpng15, and it solved it.
## update as of 2020/03/09:
Alternatively, I also tried to locate the missing library and add it to $LD\_LIBRARY\_PATH.
```
~$ locate libjpeg
# showing the location of libjpeg. In my case it's inside my anaconda
# /home/user/app/anaconda2/lib/libjpeg.so.9
~$ export LD_LIBRARY_PATH=/home/user/app/anaconda2/lib:$LD_LIBRARY_PATH
~$ emacs
# launches fine
```
> 0 votes
---
Tags: build
---
|
thread-55993
|
https://emacs.stackexchange.com/questions/55993
|
Diary appoinment variables is void:
|
2020-03-08T11:22:55.030
|
# Question
Title: Diary appoinment variables is void:
Reference to 31.10.6 Diary Appointments
> If you have a diary entry for an appointment, and that diary entry begins with a recognizable time of day, Emacs can warn you in advance that an appointment is pending. Emacs alerts you to the appointment by displaying a message in your chosen format, as specified by the variable *appt-display-format*. If the value of *appt-audible* is non-nil, the warning includes an audible reminder. In addition, if *appt-display-mode-line* is non-nil, Emacs displays the number of minutes to the appointment on the mode line.
it mentioned the variables of `appt-display-format`, `appt-audible` and `appt-display-mode-line`,
Unfortunately, I cannot find the variables with prefix of `appt`
eval `(appt-audible)` but report :
Symbol’s function definition is void: appt-audible
Why I cannot not find the variables of appointments?
# Answer
The library `appt.el` contains the variables/functions sought. Consider using something like `(require 'appt)` before attempting to locate (with functions such as `describe-...` or `find-...`) and/or before attempting to use the variables/functions.
**Q**: How did I find the answer to this question?
**A**: I grepped the `lisp` folder (of the Emacs source code) for the prefix `appt-`, and/or, grepped for a random variable described in the Emacs manual (to which a link was provided in the question by the O.P. above); e.g., `appt-display-format`.
> 2 votes
---
Tags: diary
---
|
thread-36111
|
https://emacs.stackexchange.com/questions/36111
|
Invalid duration format org-agenda
|
2017-10-12T14:06:22.997
|
# Question
Title: Invalid duration format org-agenda
I probably hit the wrong keys at some point but now when I'm calling an org-agenda command (i.e. C-a a), I'm receiving an error message: Invalid duration format: "shell", with an empty window. I re-installed org-mode with no success.
org-mode 9.1.2
emacs 25.3
Ubuntu 17.04
# Answer
The word "shell" was inadvertently inserted into a PROPERTIES drawer in one of the entry of an org agenda file. Removing it solved the issue.
> 2 votes
# Answer
I got a similar error `Invalid duration format: "-"` when I was opened my agenda. Let me complete @Denis answer by explaining how this malformed input can be "inadvertently" inserted. In my case, the reason behind is I have mistakenly input "-" in the effort buffer activated on the agenda (`e` in the agenda). At the time, I've received the same error `Invalid duration format: "-"` but `-` has still been written in my agenda file. It was more painful to find "-" than "shell" since it appears everywhere in an agenda file. I will report this behaviour.
Sidenote: `Org-mode 9.1.9`.
**EDIT**:
The issue is fixed.
> 0 votes
# Answer
To help identify the element which is causing trouble, run the org-agenda command but restricting to particular files and particular subtrees
> 0 votes
# Answer
I also did what the OP has done. I also received the error message: Invalid duration format "taTesting" I also re-installed EMACS, org-agenda, etc to restore my emacs configuration
Two hours of toil passed --and the problem didn't go away--
What solved the problem was: `M-x dired` and navigated to the folder containing my .org files
`M-x grep-find` , entered taTesting
BANG! It found a grep match.
I go to that location and remove the :Effort: property containing that offensive value, and saved that file.
org-agenda behaved properly from then on.
> 0 votes
---
Tags: org-mode, org-agenda
---
|
thread-55998
|
https://emacs.stackexchange.com/questions/55998
|
How can I get list of all things supported by thing-at-point?
|
2020-03-08T18:41:54.663
|
# Question
Title: How can I get list of all things supported by thing-at-point?
I want a complete list of *things* that works with `thing-at-point`. The documentation states:
```
Possibilities include `symbol`, `list`, `sexp`, `defun`,
`filename`, `url`, `email`, `word`, `sentence`, `whitespace`,
`line`, and `page`.
See the file `thingatpt.el` for documentation on how to define a
valid THING.
```
Because users can dynamically define new *things*, I'm assuming this list needs to be dynamically computed. Things are defined by adding the appropriate properties to a symbol. Is it possible to get a list of all symbols that has a given property?
# Answer
> 5 votes
Yes, sure - use `mapatoms`:
```
(defun find-symbols-having-properties (properties)
(let (ret)
(mapatoms (lambda (s)
(when (cl-loop for prop in properties
thereis (get s prop))
(push s ret))))
ret))
```
Now, to get all the "things", we need to do
```
(find-symbols-having-properties
'(beginning-op end-op bounds-of-thing-at-point thing-at-point forward-op))
==> (email url line git-revision list number buffer defun filename uuid sexp)
```
**PS**. You might not necessarily find *all* defined things, but the code should put you on the right path...
# Answer
> 4 votes
It's not enough to test for properties `beginning-op`, `end-op`, `bounds-of-thing-at-point`, and `thing-at-point`. A thing can instead be defined by property **`forward-op`** or by a **`forward-`** *THING* function. (And some uses of things require the existence of a `forward-op` or a `forward-` *THING* function.)
Library **`thing-cmds.el`** (code) defines these functions:
* **`thgcmd-defined-thing-p`**: Return non-`nil` if `THING` (type) is defined as a thing-at-point type. `THING` is a symbol.
* **`thgcmd-things-alist`**:
> `thgcmd-things-alist` is a compiled Lisp function in thing-cmds.el.
>
> `(thgcmd-things-alist &optional REQUIRE-FWD-P)`
>
> List of most thing types currently defined.
>
> Each is a string that names a type of text entity for which there is a either a corresponding `forward-` thing operation, or corresponding `beginning-of-` thing and `end-of-` thing operations. The list includes the names of the symbols that satisfy `thgcmd-defined-thing-p`, but with these excluded: `thing`, `buffer`, `point`.
>
> Non-nil arg `REQUIRE-FWD-P` means exclude `THING`s that do not have an associated `forward-THING` function.
This is the definition of `thgcmd-defined-thing-p`, which sounds like what you're looking for:
```
(defun thgcmd-defined-thing-p (thing)
"Return non-nil if THING (type) is defined as a thing-at-point type.
THING is a symbol."
(let ((forward-op (or (get thing 'forward-op)
(intern-soft (format "forward-%s" thing))))
(beginning-op (get thing 'beginning-op))
(end-op (get thing 'end-op))
(bounds-fn (get thing 'bounds-of-thing-at-point))
(thing-fn (get thing 'thing-at-point)))
(or (functionp forward-op)
(and (functionp beginning-op) (functionp end-op))
(functionp bounds-fn)
(functionp thing-fn))))
```
---
There is also user option **`thing-types`**:
> **`thing-types`** is a variable defined in `thing-cmds.el`.
>
> Its value is
>
> `("sexp" "button" "char" "char-same-line" "color" "comment"
> "decimal-number" "defun" "email" "filename" "hex-number" "line" "list"
> "list-contents" "non-nil-symbol-name" "number" "overlay" "page"
> "paragraph" "region-or-word" "sentence" "string" "string-contents"
> "symbol" "symbol-name" "unquoted-list" "url" "whitespace"
> "whitespace-&-newlines" "word")`
>
> Documentation:
>
> List of thing types.
>
> Each is a string that names a type of text entity for which there is a either a corresponding `forward-`thing operation, or corresponding `beginning-of-`thing and `end-of-`thing operations.
>
> The default value includes the names of most symbols that satisfy `thgcmd-defined-thing-p` at the time the `defcustom` is evaluated. These types are excluded: `thing`, `buffer`, `point`.
>
> **`M-@`** cycles through this list, in order.
>
> You can customize this variable.
The actual default value depends on your setup. This is the sexp that is evaluated at `defcustom` time to produce the default value:
```
(let ((types ()))
(mapatoms
(lambda (tt)
(when (thgcmd-defined-thing-p tt) (push (symbol-name tt) types))))
(setq types (sort types #'string-lessp))
;; Remove types that do not make sense.
(dolist (typ '("sexp" "thing" "buffer" "point"))
(setq types (delete typ types)))
(setq types (cons "sexp" types))) ; Put `sexp' first.
```
The option is used in command `cycle-select-something`, and it could also be useful in other contexts:
> **`cycle-select-something`** is an interactive compiled Lisp function in `thing-cmds.el`.
>
> It is bound to **`M-@`**.
>
> `(cycle-select-something)`
>
> Select something at or near point. Successively select different things.
>
> The default thing type is the first element of option **`thing-types`**.
>
> In Transient Mark mode, you can follow this with **`C-M-SPC`** to select successive things of the same type, but to do that you must first use `C-x C-x`: `M-@ C-x C-x C-M-SPC`.
>
> If option **`thgcmd-use-nearest-thing-flag`** and non-`nil` then use a thing that is *near*, not necessarily at, point.
---
Tags: symbols, thing-at-point
---
|
thread-55672
|
https://emacs.stackexchange.com/questions/55672
|
Org mode how to continue list on previous heading after subheading
|
2020-02-21T08:59:13.750
|
# Question
Title: Org mode how to continue list on previous heading after subheading
Please see in the image how I expect to put down the information in an org file. Sub-heading 1 has some list items which are collapsed, after which I would like to continue the list at the previous level.
I see how this can be hard to parse as I want it, since the underlying file is just plain text and org-indent-mode is trying to lay it out, but is there a way to capture lists as shown in the image? Can I earmark a particular list item to belong to a higher level heading?
After the state shown in the picture, if I expand and collapse sub-heading 1, 'Third thing' will become a list item under it.
# Answer
The feature that you’re looking for is only available for ordered lists.
> Ordered list items start with a numeral followed by either a period or a right parenthesis10, such as ‘1.’ or ‘1)’11 If you want a list to start with a different value—e.g., 20—start the text of the item with ‘\[@20\]’12. Those constructs can be used in any item of the list in order to enforce a particular numbering. ~ org-mode manual - plain lists.
For example,
```
* Heading 1 @ level 0
1. list item 1 @ level 1
2. list item 2 @ level 1
** Sub-heading 1 @ level 1
3. [@3] list item 3 @ level 1
```
However, if you do not want to use an ordered list then my recommendation is to convert each `headline` into a `plain list` instead.
For example,
```
- *Heading 1* @ level 0
+ list item 1 @ level 1
+ list item 2 @ level 1
- *Sub-heading 1* @ level 2
+ list item 3 @ level 1
```
> 1 votes
---
Tags: org-mode
---
|
thread-21949
|
https://emacs.stackexchange.com/questions/21949
|
How to initialize org agenda on Emacs startup?
|
2016-04-29T20:31:20.103
|
# Question
Title: How to initialize org agenda on Emacs startup?
I have a quite extensive `org-agenda-files`, so the first time I load an agenda view after starting the Emacs process, I have to wait ~20sec. I'm using Emacs in daemon mode (via systemd user service).
How can I have Emacs initialize the org-agenda on daemon startup, so that once I'm in Emacs, I don't have to wait when displaying an agenda for the first time?
# Answer
> 4 votes
Add this to your `.emacs`:
```
(add-hook 'after-init-hook 'org-agenda-list)
```
# Answer
> 0 votes
To make this work with `emacsclient` (and with a regular session also) you can use a `focus-in-hook` instead of the `after-init-hook` in Emacs User his answer. To make the agenda show your agenda items also, you should set your `agenda-file/directory` before setting the hook.
```
(setq org-agenda-files (quote ("agenda-directory")))
```
# Answer
> -1 votes
This has been covered before: https://stackoverflow.com/questions/2010539/how-can-i-show-the-org-mode-agenda-on-emacs-start-up
The top answer on that occasion was the answer posted by Emacs User.
---
Tags: org-mode, org-agenda
---
|
thread-56005
|
https://emacs.stackexchange.com/questions/56005
|
scale text in eww with proportional fonts enabled
|
2020-03-09T02:15:24.043
|
# Question
Title: scale text in eww with proportional fonts enabled
when i use eww, which is v often, coz i love reading the web by just text in a format i choose,
i can scale the text (with `C-x +/-`) until i enable "proportional fonts" with `F`. it changes my display text to be the same as my settings for `variable-pitch-mode`, but when enabled the text doesn't scale (although some other objects do).
scaling works fine in other buffers that have `variable-pitch-mode` enabled.
# Answer
> 2 votes
in my case, scaling didn't work because my variable-pitch configuration specified the `:height` in the format `140`. i switched it to the format `1.3`. and now it works.
(thanks Basil for the pointers. `emacs -Q` will come in handy again i'm sure.)
---
Tags: fonts, eww, scaling, variable-pitch, zooming
---
|
thread-56018
|
https://emacs.stackexchange.com/questions/56018
|
Using multiple tty emacsclient with "C-x 5" other frame commands
|
2020-03-09T14:04:47.797
|
# Question
Title: Using multiple tty emacsclient with "C-x 5" other frame commands
I'm using emacs in daemon mode on a server and connecting over ssh in a terminal console (tty) window (i.e. no GUI support).
I'm invoking emacsclient using in the tty window (window here refers to OS application window, not emacs window) using: `emacsclient -nw`
Everything so far works as expected.
I can spawn a second tty window and run a second `emacsclient -nw` on the same server and it will operate like a second frame which is useful if you have a multi-monitor setup.
However I can't get the the following to work:
1. I have focus on one terminal window and call, for example, `C-x 5 d`.
2. What happens is I get a new `dired` buffer in the **same** tty window as I entered the command.
3. I was hoping that the `C-x 5` would mean that `dired` was opened in the **other** frame, i.e. the other tty window.
My question is how can I harness the `C-x 5` commands when using two different tty windows containing two different emacsclient instances on the same server?
```
$ emacs --version
GNU Emacs 26.3
```
Terminal emulator = wsltty
# Answer
Are you sure that you don't have multiple frames in the same "tty window"? Does this doc help explain how to move among multiple frames when Emacs is in a text terminal?
> On a text terminal, Emacs can display only one Emacs frame at a time. However, you can still create multiple Emacs frames, and switch between them. Switching frames on these terminals is much like switching between different window configurations.
I don't think there is a way to have `C-x 5 <whatever>` use a completely different emacsclient session.
> 1 votes
---
Tags: frames, emacsclient, terminal-emacs, emacs-daemon
---
|
thread-56017
|
https://emacs.stackexchange.com/questions/56017
|
Diary specific date but displayed in every year
|
2020-03-09T14:02:03.777
|
# Question
Title: Diary specific date but displayed in every year
Reference to 31.10.1 The Diary File
It provides example as
```
April 15, 2020 Income tax due.
```
`M-x calendar` to the date of Apr 15, 2020 and strike `d`, it prompts a buffer as
```
2020-04-15 Wednesday
=====================
ISO date: Day 3 of week 16 of 2020
Last Quarter Moon 7:01am (CST)
Sunrise 5:23am
Sunset 6:30pm
2020 Income tax due.
```
It seems to work properly, but if I check the date of Apr 15, 2021
```
2021-04-15 Thurday
=====================
ISO date: Day 4 of week 15 of 2021
Sunrise 5:24am
Sunset 6:29pm
2020 Income tax due.
```
The "Income tax due" appeared again and it actually displayed every year on the date Apr 15.
What's the problem?
Org mode version 9.4 in Emacs 26.3 with Ubuntu 19.10
# Answer
EDIT (added 2021-05-04): either the question was changed (which I cannot see from the edit history) or I misunderstood the question: instead of the entry being tied to a single year, but incorrectly appearing in *every* year, I think I read it as that it *should* appear every year. Apologies for the misreading.
As mentioned in the comment, I cannot reproduce the behavior that the OP observes, but the the fact that the `2020` appears as part of the message makes me think that the diary is getting confused because of some artifact (perhaps a non-printing character) in the diary file. Make sure that the entry is:
```
April 15, 2020 Income tax due.
```
---
If you want the entry to appear in your calendar *every* year, then you just omit the year part from the diary entry.
`C-x v diary-file` tells you:
```
...
The file’s entries are lines beginning with any of the forms
specified by the variable ‘diary-date-forms’, which by default
uses the forms of ‘diary-american-date-forms’:
MONTH/DAY
MONTH/DAY/YEAR
MONTHNAME DAY
MONTHNAME DAY, YEAR
DAYNAME
...
```
So just do
> April 15 Tax day
> 3 votes
---
Tags: time-date, diary
---
|
thread-18017
|
https://emacs.stackexchange.com/questions/18017
|
Why exec-path doesn't contain /usr/local/bin while /etc/paths already contains it?
|
2015-11-12T02:17:07.410
|
# Question
Title: Why exec-path doesn't contain /usr/local/bin while /etc/paths already contains it?
Emacs 24.5.1 on OS X 10.11.1.
This is the content of `/etc/paths`:
```
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
```
This is the value of `exec-path`:
```
("/usr/bin"
"/bin"
"/usr/sbin"
"/sbin" "/Applications/Emacs.app/Contents/MacOS/bin-x86_64-10_9"
"/Applications/Emacs.app/Contents/MacOS/libexec-x86_64-10_9"
"/Applications/Emacs.app/Contents/MacOS/libexec"
"/Applications/Emacs.app/Contents/MacOS/bin")
```
Why doesn't it contain `/usr/local/bin`?
# Answer
OS X only evaluates `/etc/paths` and `/etc/paths.d/` for shell sessions, through an invocation of `path_helper` in the global shell profile.
GUI applications have a different launch path (through launchd as far as I know), which includes a different environment and a different environment configuration. Specifically, GUI applications do not inherit `$PATH` from a shell session, and thus do not get `$PATH` entries from the aforementioned files.
You can work around this behaviour with exec-path-from-shell, which sets `exec-path` based on the `$PATH` value of a shell session. This package is more or less a standard equipment for Emacs users on OS X.
> 5 votes
# Answer
For future searchers: I used this to solve the problem:
https://github.com/arouanet/path-helper
It is a small elisp module that mimics the behavior of the `/usr/libexec/path_helper` utility available on MacOS.
I added these lines to my .emacs
```
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; set path correctly on MacOS, based on /etc/paths
(if (memq window-system '(ns mac))
(path-helper-setenv "PATH"))
```
For more information you may want to examine this link on emacswiki.
> 1 votes
# Answer
> Emacs initializes ‘exec-path’ when it starts up, based on the value of the environment variable ‘PATH’.
`C-h``i``g` `(elisp) Subprocess Creation` `RET`
> -1 votes
---
Tags: osx, exec-path
---
|
thread-56031
|
https://emacs.stackexchange.com/questions/56031
|
Why is emacs so bad at rendering long strings of text and what can be done to make it good?
|
2020-03-09T20:29:33.940
|
# Question
Title: Why is emacs so bad at rendering long strings of text and what can be done to make it good?
Whenever a long string is to be rendered in an emacs buffer, which usually happens in the shell, emacs hangs and freezes, or takes too long to render the text compared to the terminal. What can be done to improve the performance of rendering text in emacs buffers?
# Answer
> 2 votes
As Drew says, your question is a bit vague. However, Emacs does have a long-known problem with long lines in files. Many of the internal operations that Emacs does make the assumption that lines are generally short. This is usually a safe assumption, of course.
As for exactly what is slow, the main problem is usually syntax highlighting. Most syntax highlighting is done with lots of repeated regular expression searches, which generally need to know the line boundaries to work. Turning off font-lock mode for that buffer frequently makes a huge difference.
I doubt the actual text rendering is a big part of the cost; simply rendering glyphs to the screen is generally pretty fast. Deciding which glyphs to render can take more time in some circumstances, but that's mostly related to the script the file is using. Anything that requires shaping will naturally be slower, for example. It still shouldn't be very significant.
If disabling font-lock mode doesn't help enough to satisfy you, I recommend profiling emacs with perf or similar tools. This will let you measure what's actually slow, rather than speculating. Then you may be able to make other adjustments to your configuration that will help.
---
Tags: performance
---
|
thread-56036
|
https://emacs.stackexchange.com/questions/56036
|
Portable way of setting the windows urgent hint?
|
2020-03-10T00:24:33.677
|
# Question
Title: Portable way of setting the windows urgent hint?
I've seen links to X11 flag setting that sets the current windows urgent hint.
Is there a portable way to do this in Emacs? Or does it need to be handled per-platform?
# Answer
> 1 votes
This is a snippet from @arne-babenhauserheide's site for making the frame urgent in X11, while it works it's not portable.
```
(defun my-frame-urgent-hint-set--for-x11 (frame arg &optional source)
"Set the x11-urgency hint for the frame to arg:
- If arg is nil, unset the urgency.
- If arg is any other value, set the urgency.
If you unset the urgency, you still have to visit the frame to make the urgency setting disappear."
(let* ((wm-prop "WM_HINTS") ;; Constants.
(wm-flag-urgent #x100)
(wm-hints (append (x-window-property wm-prop frame wm-prop source nil t) nil))
(flags (car wm-hints)))
(setcar wm-hints
(if arg
(logior flags wm-flag-urgent)
(logand flags (lognot wm-flag-urgent))))
(x-change-window-property wm-prop wm-hints frame wm-prop 32 t)))
(defun my-frame-urgent-hint-set (&optional arg)
"Mark the current Emacs frame as requiring urgent attention.
With a prefix argument which does not equal a boolean value of nil, remove the urgency flag
(which might or might not change display, depending on the window manager)."
(interactive "P")
(let*
(
(frame (selected-frame))
(win-system (window-system frame)))
(cond
((eq win-system 'x)
(my-frame-urgent-hint-set--for-x11 frame (not arg)))
;; TODO, other platforms.
(t
(message "Urgent hint for window system %S unsupported" win-system)))))
```
---
Tags: window, frames
---
|
thread-56029
|
https://emacs.stackexchange.com/questions/56029
|
When creating an org-agenda-custom-commands command, how can I make the (agenda) portion only display certain tags?
|
2020-03-09T19:21:52.343
|
# Question
Title: When creating an org-agenda-custom-commands command, how can I make the (agenda) portion only display certain tags?
I add custom `org-agenda` commands to the `org-agenda-custom-commands` like so
```
(setq w-view
`("W" "Work"
(
(agenda ""
(
(org-agenda-span 'day)
(org-deadline-warning-days 365)
))
(tags-todo "work"
((org-agenda-overriding-header "All Work")
(org-agenda-files '("~/Dropbox/org/inbox.org"))
(org-agenda-sorting-strategy '(deadline-up priority-down tag-up))
))
(tags-todo "work"
((org-agenda-overriding-header "Work Projects")
(org-agenda-files '("~/Dropbox/org/projects.org"))
(org-agenda-sorting-strategy '(deadline-up priority-down tag-up))
))
nil
)
)
)
(add-to-list 'org-agenda-custom-commands `,w-view)
```
I understand that items can start with "agenda," "tags-todo," or "tags," and possibly other things, though I'm not clear on what exactly as the documentation doesn't say.
I do know that an `agenda` item shows my `TODO` items that have deadlines or are scheduled, in order and with their timestamps. I also know that I can create custom headers, i.e. like I do for "All Work" or "Work Projects." I know that I can determine what `TODO` items are displayed under those custom headers because I start those sections with `tags-todo`.
What I don't understand is how I can make a custom section that starts with `agenda` only show `TODO` items of a certain tag.
I've tried the following:
```
(agenda ""
((tags-todo "work")
(org-agenda-span 'day)
(org-deadline-warning-days 365)
))
```
Which didn't throw any errors but also shows all `TODO` items regardless of tags, i.e., didn't change anything.
**When making a custom org-agenda-custom-commands view, and using the "agenda" custom header identifier, how can I make that custom agenda view only display certain tags?**
I'm not sure what to call the "agenda" or "tags-todo" or "tags" custom header identifier, help in the vocabulary sense so I can edit and clarify this question would be appreciated.
# Answer
> 6 votes
This can be done using built in tools using `org-agenda-skip-function` (I've used this answer on Stack Overflow in the past).
If you don't mind external packages, org-super-agenda makes this easy:
```
(add-to-list 'org-agenda-custom-commands
'("w" "Work agenda" agenda ""
((org-super-agenda-groups
'((:discard (:not (:tag ("work"))))
))
)
))
```
This will remove any item that doesn't match the selector `(:tag ("work"))`, that is will show only `:work:` items. This is also significantly faster than using `org-agenda-skip-function`.
You can give multiple tags and combine them using `:and` and `:or`. For example,
```
(:or
(:not (:tag ("work")))
(:and
(:tag ("home"))
(:tag ("urgent"))))
```
will match work items, but also `:urgent:` items at home. For even more advanced matching, check out org-ql, which is very powerful and fast
---
Tags: org-mode, org-agenda, org-ql
---
|
thread-55907
|
https://emacs.stackexchange.com/questions/55907
|
Emacs 24.3: warning "Unable to activate package"
|
2020-03-04T00:43:21.143
|
# Question
Title: Emacs 24.3: warning "Unable to activate package"
Upon startup of my emacs 24.3, I'm getting the errors:
```
Warning (emacs): Unable to activate package `with-editor'.
Required package `emacs-24.4' is unavailable
```
I have a dim recollection that when I first started this job, I sometimes used another machine that had 24.4, and with-editor may have been some package used by the coworker (since left) who had a more advanced emacs version in their home directory and who had suggested I copy some of their configuration.
However, if I grep my `.emacs`, `.emacs.d` recursively, or my `.emacsinit`, I don't see with-editor.
Running `emacs -Q` doesn't have the error.
What is causing it, and to the extent stackoverflow lets me ask, what techniques could I be using to troubleshoot this myself?
# Answer
The command `grep with-editor ~/.emacs.d/*/*/*` found a directory called `elpa` with a subdirectory `with-editor-2.8.1`. Many other files under `elpa` outside of that directory had references to `with-editor`. Simply deleting all of `elpa` did away with this error, allowing emacs to actually start.
The command `find ~/.emacs.d -name '*with-editor*'` would also have found the `with-editor` package, but wouldn't have let me see immediately that lots of other things under `elpa` depended on it.
> 1 votes
---
Tags: package, error-handling, warning
---
|
thread-3895
|
https://emacs.stackexchange.com/questions/3895
|
Changing the compilation mode current directory automatically?
|
2014-11-26T09:31:01.913
|
# Question
Title: Changing the compilation mode current directory automatically?
Currently, my compilation command is as follow:
```
cd ~/somedir && ./somescript.sh
```
This prevents emacs from finding the file in which an error happens (and opening it).
Of course I can run `M-x cd` manually but is there a way to tell the buffer to change its current directory programmatically?
# Answer
> 11 votes
Finally, I abandoned relying on the current directory as it was too intrusive and other things like ido where ending being affected...
Instead, I use added my build directory to `compilation-search-path`
```
(add-to-list 'compilation-search-path "/path/to/build")
```
Found on this question: How to adjust the path that Emacs' compile-goto-error gets from the compilation buffer?
The question also explains that the directory matcher can change the directory automatically if some particular strings are emitted:
```
Entering directory `...'
...
Leaving directory `...'
```
This is also customizable apparently.
# Answer
> 7 votes
You can simply make a Dired buffer of the directory where you want to invoke compile command, to serve as an anchor. When you want to compile, switch to the Dired buffer and run compile command. `compile` will run its command at this directory of the Dired buffer. The advantage of this is that you don't have to `M-x cd` or traverse directories when you want to compile.
If you use `projectile`, it has a command named `projectile-compile` that automatically runs compile command at project root recognized by `projectile`.
# Answer
> 6 votes
This alternate command should do the trick:
```
(defun compile-in-dir (dir command)
(interactive "DCompile in directory: \nsCommand: ")
(let ((default-directory dir))
(compile command)))
```
Alternatively, after you have run the compilation using the regular `compile` command, you can eval `(setq default-directory "~/somedir")` in the `*compilation*` buffer. That should make the error navigation work, but it might stop `recompile` and friends from doing the right thing.
# Answer
> 0 votes
If you have a rule for creating the source search path, you can add it as advice to the function that compile uses for finding paths. For example, the default directory for building with bazel is ~/.cache/bazel. So I want to find all those and strip out that part of the file. I added an "advice" to the `compilation-find-file` function so that it will rename the file before calling the function. That elisp is:
```
;; Rewrite the names of bazel error filenames.
(defun rename-bazel (orig-fun marker filename &rest args)
(let ((new-filename (or (and (string-match "^\\(.*\\)/.cache/bazel/.*/__main__/\\(.*\\)" filename)
(concat (match-string 1 filename) "/" (match-string 2 filename)))
filename)))
(apply orig-fun marker new-filename args)))
(advice-add 'compilation-find-file :around #'rename-bazel)
```
Now when I click on errors in the compilation buffer, it goes to the right place.
---
Tags: compilation-mode
---
|
thread-56028
|
https://emacs.stackexchange.com/questions/56028
|
Rename multiple files from a predefined directory to another directory
|
2020-03-09T18:49:46.223
|
# Question
Title: Rename multiple files from a predefined directory to another directory
I want to have a function, which moves a file or optionally multiple marked files from one directory to a different directory in some parent folder. I managed to design a script which does the main things:
```
(defun multiple-rename (candidate)
(loop for cand in (helm-marked-candidates)
do
(spacemacs/rename-file cand)))
(defun move-from-downloads ()
"helm interface to copy files from downloads"
(interactive)
(helm :sources `(
((name . "My org files")
(candidates . ,(f-entries "~/Dropbox/Documents"))
(action . (("Rename" . multiple-rename))))
)))
```
The feature which is not present yet, which I would like to have is having some specified parent folder path for a target directory of renaming.
In other words, spacemacs/rename-file takes the file to rename as an argument and if it is not getting an a second argument which is here the case put up the prompt to select a filename where the files should be moved, the path in this prompt is however the path of the current buffer. Instead I would like to have the default path, which pops up in the prompt for renaming to be something different, e.g. `home/mydefaultrenamepath`. Would be happy to hear some solution, it doesn't need to use spacemacs/rename file, only the flow of having helm candidates to select and then standard directory to move files into (which should be able to be altered).
# Answer
Here's a command that shows files from `your-initial-directory`, and moves/renames the marked/selected files to `your-target-directory`. Tested with `./emacs-helm.sh`.
```
(defvar your-initial-directory "~/Downloads/")
(defvar your-target-directory "~/Documents/")
(defun multiple-rename (_)
(let ((files (helm-marked-candidates)))
(helm-dired-action your-target-directory
:files files
:action 'rename)))
(defclass helm-user-rename (helm-source-ffiles)
((action :initform '(("Rename files" . multiple-rename)))))
(defun helm-rename ()
(interactive)
(require 'tramp)
(helm :sources (helm-make-source "Rename files" 'helm-user-rename)
:input your-initial-directory))
```
1. `M-x helm-rename`
2. `C-SPC` to mark the files you want to rename
3. `RET`
> 0 votes
# Answer
`M-x find-lisp-find-dired` to find files in a directory matching user given regular expression. Please note this command supports unicode on Windows out of box.
Select all files and `M-x dired-do-rename`.
Surely you can use above command in your own code.
> 0 votes
---
Tags: spacemacs, helm
---
|
thread-55969
|
https://emacs.stackexchange.com/questions/55969
|
Tamil characters show as garbage in shell buffer but ok in files
|
2020-03-07T06:53:39.200
|
# Question
Title: Tamil characters show as garbage in shell buffer but ok in files
When printing non-latin characters like the ones from my mother tongue Tamil in shell, it appears weird(left side window in the image). When I open the file with Tamil characters they are rendered correctly(right side window in the image). I have set the shell locale to utf-8 but the problem still persists.
```
vanangamudi@kaikuttai:~/home/projects/code/oneoff-experiments/tamil-etymdict-visualizer$ python3 -i generate-dot.py
100% 53753/53753 [00:00<00:00, 163166.71it/s]
Traceback (most recent call last):
File "generate-dot.py", line 32, in <module>
write_dot(G, 'graph.dot')
File "/home/vanangamudi/.local/lib/python3.6/site-packages/networkx/drawing/nx_agraph.py", line 192, in write_dot
A = to_agraph(G)
File "/home/vanangamudi/.local/lib/python3.6/site-packages/networkx/drawing/nx_agraph.py", line 151, in to_agraph
A.add_node(n)
File "/home/vanangamudi/.local/lib/python3.6/site-packages/pygraphviz/agraph.py", line 309, in add_node
node = Node(self, nh=nh)
File "/home/vanangamudi/.local/lib/python3.6/site-packages/pygraphviz/agraph.py", line 1611, in __new__
n = super(Node, self).__new__(self, gv.agnameof(nh), graph.encoding)
TypeError: decoding to str: need a bytes-like object, NoneType found
>>> G.nodes
NodeView(('நà¯à®°à¯à®à¯à®à¯à®´à®¿|நà¯à®°à¯à®à¯à®à¯à®´à®¿|பà¯', '(n', 'நà¯à®°à¯', 'பà¯à®´à¯', 'தà¯à®³à¯à®¤à¯à®¤à®²à¯', 'à®à¯à®±à¯à®¤à®²à¯', 'fowl', 'à®à¯à®´à®¿', 'வனà¯à®©à®¤à¯à®²à®¿à®à¯|வனà¯à®©à®¤à¯à®²à®¿à®à¯|பà¯', '|பà¯', 'à®à®³à®µà®¾à®à®®à¯|à®à®³à®µà®¾à®à®®à¯|பà¯', 'à®à¯', 'à®à¯', 'வி', 'à®à¯à®à¯à®¤à¯à®¤à¯à®£à®¿|à®à¯à®à¯à®¤à¯à®¤à¯à®£à®¿|பà¯', 'à®à¯à®©à¯à®±à®¾à®µà®¿', 'à®à®²à¯à®à¯|à®à®²à¯à®à¯
```
Adding locale information as pointed out by @Rusi,
```
vanangamudi@kaikuttai:~$ locale
LANG=en_IN
LANGUAGE=en_IN:en
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8
vanangamudi@kaikuttai:~$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IL
en_IL.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
POSIX
ta_IN
ta_IN.utf8
ta_LK
ta_LK.utf8
vanangamudi@kaikuttai:~$
```
# Answer
# Diagnosis
Clearly at this point we have only insufficient data. Anyways... here's my tentative diagnosis
* `LANG` is set `en_IN` (no utf8) in `/etc/default/locale`; `LANGUAGE` too is set there to `en_IN:en`
* `LC_ALL` is set *somewhere else* to `en_US.utf8`
* In short, your system is in a tug-o-war between IN-dia and US-a, between utf8 and legacy encoding and emacs is getting confused.
# Suggested Treatment
Assuming the above somewhat true, you need to
* Add the utf8 to `LANG` setting
* Find and remove wherever `LC_ALL` is being set
* verify working by calling `locale`. All should be same. `LC_ALL` **should show as unset**
* Try emacs without any attempted locale related customizations. I would guess that shell-inside-emacs has more things that could go wrong than simply reading/writing Tamil files. And python-unicode even more so. So for testing purposes I'd start with the reading/writing Tamil files. For python-unicode, first try in a shell outside emacs.
# Finding LANG/LC\_\* settings
This can be a non-trivial treasure hunt. Some likely culprits
* /etc/default/locale (debian/ubuntu)
* /etc/environment (older debian/ubuntu)
* /etc/profile
* In your $HOME
+ .pam\_environment
+ .profile
+ .bash\_profile
+ .bashrc
* etc...
Unfortunately this list cannot be exhaustive And at this point is getting quite far removed from emacs.
---
Also please report
```
M-: (process-coding-system (get-process "???"))
```
where ??? Is `shell` or `Shell` or `*shell*` ... I'm not exactly sure which will work
And, if necessary, use `set-process-coding-system`. ( manual )
> 1 votes
---
Tags: character-encoding, utf-8
---
|
thread-55906
|
https://emacs.stackexchange.com/questions/55906
|
Emacs 24.3 and 26.3 scrollbars refuses to move up if not moved up immediately, on various OS's and X-servers
|
2020-03-04T00:40:52.797
|
# Question
Title: Emacs 24.3 and 26.3 scrollbars refuses to move up if not moved up immediately, on various OS's and X-servers
The problem manifests on:
* Emacs 26.3 on Fedora Release 31, using Xming on Windows 7 as X server, whether in -Q mode or not
* Emacs 24.3 on RHEL7, using MobaXterm 12.2 4204, whether in -Q mode or not
The scrollbar I'm seeing is a medium-dark rectangle (the scrollbar "elevator") with rounded left-hand corners and square right-hand corners (which may have been a wide-scrollbar setting on 26.3; on 24.3 it's as pictured below) in a light-gray vertical area (the scrollbar "track"). When I mouse over the rectangle it switches to dark gray.
When I click it, it turns blue. After about 1/2 second, if not moved, it narrows about 2 pixels on both sides\]\**, and refuses to move. Moving the mouse will sometimes get one scroll of the window contents, and sometimes not.
If I click it and move it slightly in that 1/2 second, it will move, and continue to be movable even if I hold still for a while. But I have to move it substantially (at least half its height, it seems, in a 2000 line file) or it will then freeze at the 1/2 second mark.
Here's my current `.emacs` file:
```
(defun switch-to-next-buffer-frank ()
(interactive)
(switch-to-buffer (other-buffer)))
(defun switch-to-prev-window ()
(interactive)
(other-window -1))
(defun scroll-one-line-up (&optional arg)
"Scroll the selected window up (forward in the text) one line (or N lines)."
(interactive "p")
(scroll-up (or arg 1)))
(defun scroll-one-line-down (&optional arg)
"Scroll the selected window down (backward in the text) one line (or N)."
(interactive "p")
(scroll-down (or arg 1)))
(global-set-key [(control ?z)] 'scroll-one-line-up)
(global-set-key [(meta ?z)] 'scroll-one-line-down)
(global-set-key [(meta ?g)] 'goto-line)
(global-set-key [(control ?x)(k)] 'kill-this-buffer)
(global-set-key [(control meta ?l)] 'switch-to-next-buffer)
(global-set-key [(control shift meta ?l)] 'switch-to-prev-buffer)
(global-set-key [(control tab)] 'other-window)
(global-set-key [(control shift iso-lefttab)] 'switch-to-prev-window)
(modify-syntax-entry ?_ "w")
(setq scroll-bar-mode 'left)
(setq scroll-bar-adjust-thumb-portion nil)
(setq gutter-buffers-tab-visible-p nil)
(setq inhibit-startup-screen t)
(setq mouse-yank-at-point t)
(setq inhibit-startup-buffer-menu t)
(tool-bar-mode -1)
(delete-selection-mode 1)
;(setq inhibit-splash-screen t)
;(setq inhibit-startup-message t)
;(setq initial-scratch-message nil)
;(delete-selection-mode 1)
;
;(defun ask-user-about-supersession-threat (fn)
; "blatantly ignore files that changed on disk"
; )
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(ansi-color-faces-vector
[default default default italic underline success warning error])
'(ansi-color-names-vector
["#3F3F3F" "#CC9393" "#7F9F7F" "#F0DFAF" "#8CD0D3" "#DC8CC3" "#93E0E3" "#DCDCCC"])
'(background-color "#000000")
'(background-mode dark)
'(company-quickhelp-color-background "#4F4F4F")
'(company-quickhelp-color-foreground "#DCDCCC")
'(cursor-color "#ffffff")
'(custom-enabled-themes (quote (manoj-dark)))
'(custom-safe-themes
(quote
("54f2d1fcc9bcadedd50398697618f7c34aceb9966a6cbaa99829eb64c0c1f3ca" "4138944fbed88c047c9973f68908b36b4153646a045648a22083bd622d1e636d" "8885761700542f5d0ea63436874bf3f9e279211707d4b1ca9ed6f53522f21934" "59e82a683db7129c0142b4b5a35dbbeaf8e01a4b81588f8c163bd255b76f4d21" default)))
'(fci-rule-color "#383838")
'(font-use-system-font t)
'(foreground-color "#00ff00")
'(gutter-buffers-tab-visible-p nil t)
'(indent-tabs-mode nil)
'(nrepl-message-colors
(quote
("#CC9393" "#DFAF8F" "#F0DFAF" "#7F9F7F" "#BFEBBF" "#93E0E3" "#94BFF3" "#DC8CC3")))
'(pdf-view-midnight-colors (quote ("#DCDCCC" . "#383838")))
'(query-user-mail-address nil)
'(tool-bar-mode nil)
'(user-mail-address "fsheeran@gmail.com")
'(vc-annotate-background "#2B2B2B")
'(vc-annotate-color-map
(quote
((20 . "#BC8383")
(40 . "#CC9393")
(60 . "#DFAF8F")
(80 . "#D0BF8F")
(100 . "#E0CF9F")
(120 . "#F0DFAF")
(140 . "#5F7F5F")
(160 . "#7F9F7F")
(180 . "#8FB28F")
(200 . "#9FC59F")
(220 . "#AFD8AF")
(240 . "#BFEBBF")
(260 . "#93E0E3")
(280 . "#6CA0A3")
(300 . "#7CB8BB")
(320 . "#8CD0D3")
(340 . "#94BFF3")
(360 . "#DC8CC3"))))
'(vc-annotate-very-old-color "#DC8CC3"))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(default ((t (:foreground "#00ff00" :background "#000000" :size "10pt" :family "DejaVu Sans Mono" :foundry "PfEd" :slant normal :weight normal :height 144 :width normal))))
'(font-lock-builtin-face ((t (:foreground "#00ccff"))))
'(font-lock-comment-delimiter-face ((t (:foreground "#ffff00" :slant normal))))
'(font-lock-comment-face ((t (:foreground "#ffff00" :slant normal))))
'(font-lock-constant-face ((t (:foreground "#00ff99" :weight normal))))
'(font-lock-function-name-face ((t (:foreground "#00ff00" :weight normal :height 1.0))))
'(font-lock-preprocessor-face ((t (:foreground "#ff4040"))))
'(font-lock-string-face ((t (:foreground "#00ffee"))))
'(font-lock-type-face ((t (:foreground "#33ccff"))))
'(font-lock-variable-name-face ((t (:foreground "#66ff00"))))
'(italic ((t nil)))
'(mode-line ((t (:background "#445555" :foreground "#ffffff" :box (:line-width 2 :color "#445555") :height 1.0))))
'(mode-line-buffer-id ((t (:background "#445555" :foreground "#55ff55" :weight normal :height 1.0))))
'(mode-line-emphasis ((t (:weight normal))))
'(mode-line-highlight ((t (:box (:line-width 2 :color "#445555")))))
'(mode-line-inactive ((t (:background "#445555" :foreground "#ffffff" :box (:line-width 2 :color "#445555") :weight normal :height 1.0))))
'(scroll-bar ((t (:background "#334444" :foreground "#ddffff")))))
```
Here's a screenshot: of emacs -Q 24.3/RHEL7/MobaXterm:
Then here is the same window after I've held the top scrollbar about 1 second without moving after clicking down:
# Answer
> 0 votes
**Short Answer:** Create file `~/.config/gtk-3.0/settings.ini` as seen at the bottom of this answer.
**Long Answer:** Starting up `emacs` under the `strace` utility, capturing the output:
```
tcsh> strace emacs MyFile.cpp >& emacs.strace &
```
Emacs apparently can be built with different kinds of scrollbars, one being gtk. If I search `emacs.strace` for `gtk` I find a bunch, so I assume my emacs package was built with gtk and that's what I'm probably looking at. Furthermore, the `gtk` references typically mention 3.0, so I assume gtk version 3.0:
```
> grep -i gtk emacs.strace
open("/opt/rh/devtoolset-6/root/usr/lib64/tls/libgtk-3.so.0", O_RDONLY|O_CLOEXEC) = -1
ENOENT (No such file or directory)
open("/opt/rh/devtoolset-6/root/usr/lib64/libgtk-3.so.0", O_RDONLY|O_CLOEXEC) = -1
ENOENT (No such file or directory)
open("/opt/rh/devtoolset-6/root/usr/lib/libgtk-3.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT
(No such file or directory)
open("/lib64/libgtk-3.so.0", O_RDONLY|O_CLOEXEC) = 3
access("/usr/share/gtk-3.0/settings.ini", F_OK) = -1 ENOENT (No such file or directory)
access("/etc/gtk-3.0/settings.ini", F_OK) = -1 ENOENT (No such file or directory)
access("/etc/xdg/gtk-3.0/settings.ini", F_OK) = -1 ENOENT (No such file or directory)
:
:
:
```
Given that, I read the documentation for Gtk 3.0 scrollbars. There's a little mention of a "fine-tune" mode.
I create a special `~/.config/gtk-3.0/gtk.css` file that should highlight this fine-tune mode:
```
.scrollbar.vertical slider,
scrollbar.vertical slider {
background: #777777;
border-radius:0px; /* Make the slider rectangular instead of a oval or roundrect. */
margin:1px; /* Fix the margin size at 1 pixel whether we're active or note. */
}
.scrollbar.vertical slider:active,
scrollbar.vertical slider:active {
background: #555555;
}
.scrollbar.vertical.fine-tune slider:active,
scrollbar.vertical.fine-tune slider:active {
background: red;
}
```
That should turn the scrollbar slider red if/when the fine-tune mode kicks in, and indeed: as soon as it turns red, it cannot be moved any more.
So searching for Gtk fine-tune, I find that there are hundreds of complaints about this mode since about 2014, and not a single voice in favor. But we still have it, oh well. Luckily, it can be disabled by the following `~/.config/gtk-3.0/settings.ini` file:
```
[Settings]
gtk-long-press-time=99999
```
The time seems to be measured in units of 2ms, such that a value of 1000 gives about 2 seconds.
# Answer
> 1 votes
Aha, I figured it out. It's a new feature (or "feature", depending on your outlook) of Gtk 3. I haven't found any mention of it in the documentation yet, but here's an article from a Gtk developer: https://blog.gtk.org/2017/10/11/a-scrolling-primer/
I'll quote the relevant portion:
> There’s more to scrolling in GTK+ that you may not know about. One feature that we introduced long ago is a ‘zoom’ or ‘fine adjustment’ mode, which slows the scrolling down to allow pixel-precise positioning.
>
> To trigger this mode you can either use a long press or shift-click in the slider. As you can see in the video, once you move the pointer below or above the scrollbar, it will keep scrolling at the same relaxed speed until you let go.
Scrolling by moving the slider triggers mouse events which Emacs turns into calls to `scroll-bar-toolkit-scroll`. By tracing this function to see what arguments it's called with, I can see the units it's in:
```
======================================================================
1 -> (scroll-bar-toolkit-scroll (mouse-1 (#<window 348 on *Help*> vertical-scroll-bar (5179898 . 9754353) 0 handle)))
1 <- scroll-bar-toolkit-scroll: 12576
======================================================================
1 -> (scroll-bar-toolkit-scroll (mouse-1 (#<window 348 on *Help*> vertical-scroll-bar (5179899 . 9754353) 0 handle)))
1 <- scroll-bar-toolkit-scroll: 12576
======================================================================
1 -> (scroll-bar-toolkit-scroll (mouse-1 (#<window 348 on *Help*> vertical-scroll-bar (0 . 0) 0 end-scroll)))
1 <- scroll-bar-toolkit-scroll: t
```
You can see that Gtk is scrolling the document from 5179898/9754353 of the way through document to 5179899/9754353 of the way through the document. This would indeed be pixel-accurate scrolling if the document really was 9754353 pixels tall, but it's not. I'm not sure where that number came from; it doesn't appear to be the number of characters either. Instead, because the units are so odd, the scrolling is very slow, just one line every few seconds. That explains why you sometimes got it to scroll, but other times you didn't.
At any rate, when I don't long click I get this:
```
======================================================================
1 -> (scroll-bar-toolkit-scroll (mouse-1 (#<window 348 on *Help*> vertical-scroll-bar (5202322 . 9754353) 0 handle)))
1 <- scroll-bar-toolkit-scroll: 12576
======================================================================
1 -> (scroll-bar-toolkit-scroll (mouse-1 (#<window 348 on *Help*> vertical-scroll-bar (5224745 . 9754353) 0 handle)))
1 <- scroll-bar-toolkit-scroll: 12576
======================================================================
1 -> (scroll-bar-toolkit-scroll (mouse-1 (#<window 348 on *Help*> vertical-scroll-bar (0 . 0) 0 end-scroll)))
1 <- scroll-bar-toolkit-scroll: t
```
Which results in the usual pace of scrolling.
Update:
It looks like the size of the scrollbars that emacs creates are fixed, and that they always go from one to ten million. See gtkutil.h line 30:
```
/* Minimum and maximum values used for GTK scroll bars */
#define XG_SB_MIN 1
#define XG_SB_MAX 10000000
#define XG_SB_RANGE (XG_SB_MAX-XG_SB_MIN)
#define YG_SB_MIN 1
#define YG_SB_MAX 10000000
#define YG_SB_RANGE (YG_SB_MAX-YG_SB_MIN)
```
It may be adjusted slightly from there to account for things like the size of the thumb or the height of the window or something, but that seems to explain the large values. The alternative used by most programs is to measure the height of the document in pixels, and use that.
---
Tags: emacs26, gtk3, scroll-bars, emacs24
---
|
thread-53082
|
https://emacs.stackexchange.com/questions/53082
|
How to write regex to change the go keywords color?
|
2019-10-10T15:25:41.967
|
# Question
Title: How to write regex to change the go keywords color?
I want to change the color which in `package import go defer` in go-mode ,need a regex..these code only change the `pacakge` word color
```
(defface my-font-lock-gokeyword-face
`((t (:foreground "#ab4642"))) ;; change to desired color
"Face for go keyword.")
(font-lock-add-keywords 'go-mode
;; change to desired operator regex
'(("package" 0 'my-font-lock-gokeyword-face)))
```
# Answer
> 0 votes
If you change "package" to "^package.\*" I think it will match every line that starts with package to the end of the line. I don't know enough about go to know if that is always the right thing to do here.
# Answer
> 0 votes
If I understand correct, just add the other keywords to the list. Something like:
```
(font-lock-add-keywords 'go-mode
;; change to desired operator regex
'(("package" 0 'my-font-lock-gokeyword-face)
("go" 0 'my-font-lock-gokeyword-face)
("defer" 0 'my-font-lock-gokeyword-face)
("package" 0 'my-font-lock-gokeyword-face)))
```
I understood you want the same color for all four keywords, then this is fine. Otherwise you can change the faces to whatever color you want for the keywords.
---
Tags: regular-expressions, font-lock
---
|
thread-56050
|
https://emacs.stackexchange.com/questions/56050
|
Problem with use-package and matlab-mode - cannot load
|
2020-03-10T12:52:49.970
|
# Question
Title: Problem with use-package and matlab-mode - cannot load
I am trying to use the matlab-mode package with use-package.
in my `init.el`:
```
(use-package matlab-mode
:ensure t
:config
(add-to-list
'auto-mode-alist
'("\\.m\\'" . matlab-mode))
(setq matlab-indent-function t)
(setq matlab-shell-command "matlab"))
```
This seems to work - the package is downloaded and installed if necessary, the mode is automatically enabled in `.m` files, but everytime I launch Emacs I get the warning `Error (use-package): Cannot load matlab-mode`. Can anybody tell me why this happens?
# Answer
The package name is `matlab-mode` but the `provide`d feature is `matlab`. Have a look at the very end of that source code file.
According to `use-package` Manual you have to get that right.
So your `use-package` declaration should look like this:
```
(use-package matlab
:ensure matlab-mode
:config
(add-to-list
'auto-mode-alist
'("\\.m\\'" . matlab-mode))
(setq matlab-indent-function t)
(setq matlab-shell-command "matlab"))
```
> 1 votes
---
Tags: use-package, matlab
---
|
thread-56054
|
https://emacs.stackexchange.com/questions/56054
|
eval and quotes
|
2020-03-10T16:03:09.797
|
# Question
Title: eval and quotes
I am trying to execute the code here, which I copy below
```
(defun buffer-local-set-key (key func)
(interactive "KSet key on this buffer: \naCommand: ")
(let ((name (format "%s-magic" (buffer-name))))
(eval
`(define-minor-mode ,(intern name)
"Automagically built minor mode to define buffer-local keys."))
(let* ((mapname (format "%s-map" name))
(map (intern mapname)))
(unless (boundp (intern mapname))
(set map (make-sparse-keymap)))
(eval
`(define-key ,map ,key func)))
(funcall (intern name) t)))
```
However, when executing it like this
```
(buffer-local-set-key "C-x k" #'previous-buffer)
```
I am getting an error `eval: Symbol’s value as variable is void: func`. I suspect it is at the line `(eval `(define-key ,map ,key func)))`
I understand what the code is doing, but I am not sure why `eval` is being used here instead of the function being called directly, i.e. `(define-key map key func)`. However, when I tried doing that instead I got the error
`Wrong type argument: keymapp, buf-magic-map`
Can someone explain to me why `eval` might be needed here? And how to fix the error above?
I have `lexical-binding` set to true in case that was relevant.
# Answer
There are several things wrong with the code:
* You need `#',` (or just `',`) in front of `func`. Inside a backquote expression, just `func` would result in the literal symbol `func`, not its value as a variable. Use comma (`,` to evaluate it. But then quote that evaluated result.
* You need to use `kbd`, or else you are trying to bind the key sequence `C-x SPC k`.
* You need to lose the `t` arg when calling the minor-mode function. The minor mode is enabled when no arg is passed. See the Emacs manual, node Minor Modes:
"If the mode command is called via Lisp, the minor mode is unconditionally **turned on if the argument is omitted** or `nil`."
```
(defun buffer-local-set-key (key func)
(interactive "KSet key on this buffer: \naCommand: ")
(let ((name (format "%s-magic" (buffer-name))))
(eval `(define-minor-mode ,(intern name)
"Automagically built minor mode to define buffer-local keys."))
(let* ((mapname (format "%s-map" name))
(map (intern mapname)))
(unless (boundp (intern mapname))
(set map (make-sparse-keymap)))
;; Use `,' before FUNC, then quote the result of the evaluation.
(eval `(define-key ,map ,key #',func)))
;; Lose the `t' arg from (funcall (intern name) t))).
(funcall (intern name))))
;; Use `kbd'
(buffer-local-set-key (kbd "C-x k") 'previous-buffer)
```
The reason you need to use `eval` is that the result of the backquote expression is a *list*, that is, it's the resulting code in list form. You then need to evaluate that code (i.e., that list).
**UPDATE after your comment question of why use backquote at all for the second occurrence**
Yes, the second occurrence doesn't need `eval` and backquote. But you then need to use `symbol-value` to get the value of variable `map`.
```
(defun buffer-local-set-key (key func)
(interactive "KSet key on this buffer: \naCommand: ")
(let ((name (format "%s-magic" (buffer-name))))
(eval `(define-minor-mode ,(intern name)
"Automagically built minor mode to define buffer-local keys."))
(let* ((mapname (format "%s-map" name))
(map (intern mapname)))
(unless (boundp (intern mapname))
(set map (make-sparse-keymap)))
;; Use `,' before FUNC, then quote the result of the evaluation.
(define-key (symbol-value map) key func)) ; <== Use `symbol-value'
;; Lose the `t' arg from (funcall (intern name) t))).
(funcall (intern name))))
```
> 3 votes
---
Tags: key-bindings, minor-mode, quote, eval, backquote
---
|
thread-56051
|
https://emacs.stackexchange.com/questions/56051
|
How to have all sections unnumbered in org-mode with inheriting property?
|
2020-03-10T14:44:44.517
|
# Question
Title: How to have all sections unnumbered in org-mode with inheriting property?
I would want to have all sections unnumbered. Instead to add the property
```
* Section Name
:PROPERTIES:
:UNNUMBERED: t
:END:
```
to each subtree (which works well). I thought to use inheriting property in the top of the file as specified in the documentation :
```
#+PROPERTY: UNNUMBERED t
```
but this approach doesn't work. What I am missing?
# Answer
You can do what you want with
```
#+OPTIONS: num:nil
```
As for the `#+PROPERTY:` setting, I can reproduce the problem: I thought at first that turning `org-use-property-inheritance` on would do the job, but I cannot get inheritance to work in this context (with a `#+PROPERTY:` setting). It *does* work in the context of a top-level headline having the property and lower-level headlines inheriting it:
```
#+PROPERTY: UNNUMBERED t
* Section name foo
:PROPERTIES:
:UNNUMBERED: t
:END:
** Section name baz
** Section name hunoz
* Section name bar
```
The first section and its subsections are unnumbered; the second section is numbered.
Whether inheritance should work with `#+PROPERTIES:` seems to me to be a reasonable question (or even a bug report) for the Org mode mailing list.
> 4 votes
---
Tags: org-mode
---
|
thread-56048
|
https://emacs.stackexchange.com/questions/56048
|
Report time at whole hours by prompting mini-buffer
|
2020-03-10T11:59:04.537
|
# Question
Title: Report time at whole hours by prompting mini-buffer
Reference to 31.10.6 Appointments of Emacs Manual
It provides a handy solution to report hour and remind appointments:
> For example, suppose the diary file contains these lines:
> =M-x appt-add= adds entries to the appointment list without affecting your diary file. You delete entries from the appointment list with =M-x appt-delete=.
Then if set the minutes to warning as 0 minutes to remind whole hours, it becomes a alarm to report whole hour to prompt a mini-buffer.
For example, `M-x appt-add` a whole hour "9:00pm" and set the warning as 0 minute. When it comes to 9:00pm, a mini-buffer would be prompt to report the current time.
At this moment, appointment transforms itself as an alarm to report whole hours.
Unfortunately, the appointment is one-off and it's cumbersome to set alarms manually every day.
How could have an alarm to report whole hours using appointments or any alternative solutions?
# Answer
You can do that using timers. Define a function to print out the time in the echo area:
```
(defun announce-time ()
(message (format "The time is %s" (format-time-string "%H:%M" (current-time)))))
```
and set up a timer to run it at some initial time and every hour thereafter:
```
(run-at-time "00:00" 3600 #'announce-time)
```
You can cancel the timer if you don't want it any longer with `M-x list-timers RET` and pressing `c` on this timer.
> 1 votes
---
Tags: minibuffer
---
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.