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-60649
https://emacs.stackexchange.com/questions/60649
Show compilation errors in "#+RESULTS" code blocks
2020-09-14T14:05:05.723
# Question Title: Show compilation errors in "#+RESULTS" code blocks # The problem I'm currently writing notes on C++ classes. Sometimes I annotate what I shouldn't do (because they cause compilation errors) so it would be really helpful if I could automatically insert compilation errors in the `#+RESULTS` section of source code blocks. Consider the following example: I would like the following code block to produce ``` #+begin_src cpp class A { static int n = 0; }; int main() { return 0; } #+end_src ``` this `#+RESULTS` code block ``` #+RESULTS: #+begin_example /tmp/babel-NYqDkg/C-src-HslBxN.cpp:11:14: error: ISO C++ forbids in-class initialization of non-const static member ‘A::n’ 11 | static int n = 0; | ^ #+end_example ``` # Additional context In `sh` source code blocks, I can accomplish a similar behavior by using the following header arguments ``` #+begin_src sh :prologue "exec 2>&1" :epilogue ":" ls "this path doesn't exist" #+end_src #+RESULTS: #+begin_example ls: cannot access "this path doesn't exist": No such file or directory #+end_example ``` # Answer > 3 votes Yes, you can do so by using the `:post()` header argument. I will present two solutions. The first one is simpler but has two disadvantages. I would consider the second solution the way to go. # First solution Consider the following Org Mode file. We can call the `dash` code block after the `c++` code block is executed by executing `org-babel-execute-src-block`, which is executed by pressing `C-c C-c` when the element at point is a source code block. ``` * Compilation errors in C++ #+NAME: compile-source-cpp #+begin_src dash :epilogue ":" :prologue "exec 2>&1" g++ main.cpp && echo "Success" #+end_src #+begin_src cpp yes :main yes :tangle main.cpp :post compile-source-cpp() int 12 = "a"; #+end_src #+RESULTS: #+begin_example main.cpp: In function ‘int main()’: main.cpp:2:5: error: expected unqualified-id before numeric constant 2 | int 12 = "a"; | ^~ #+end_example ``` There are two disadvantages of this solution: 1. The C++ source file would be executed twice: The first one because of `C-c C-c` is pressed and the second one because `g++` is executed in the `dash` code block but at least the `#+RESULTS` of the corresponding block would show the compilation errors. 2. Before pressing `C-c C-c`, you will need to ensure that `org-babel-tangle` is executed beforehand on the C++ code block so that the source file is created and `g++` can then compile it. # Second solution This solution gets rid of the two disadvantages of the first solution. ``` #+PROPERTY: header-args:cpp :tangle main.cpp :eval no * Utilities #+begin_src elisp (defun org-babel-tangle-previous-src () "Tangles the backward nearest source code block." (interactive) (save-excursion (goto-char (search-backward-regexp "^[[:space:]]*#\\+begin_src\\>")) (let ((current-prefix-arg '(4))) (call-interactively 'org-babel-tangle)))) #+end_src #+NAME: org-babel-tangle-previous-src #+begin_src elisp (org-babel-tangle-previous-src) #+end_src #+NAME: compile-source-cpp #+begin_src dash :prologue "exec 2>&1" :epilogue ":" g++ main.cpp && echo "Success" #+end_src * Compilation errors in C++ #+begin_src cpp int main #+end_src #+CALL: org-babel-tangle-previous-src() :post compile-source-cpp() #+RESULTS: #+begin_example main.cpp: In function ‘int main()’: main.cpp:3:1: error: expected initializer before ‘return’ 3 | return 0; | ^~~~~~ #+end_example #+begin_src cpp int number = "12 + 13"; #+end_src #+CALL: org-babel-tangle-previous-src() :post compile-source-cpp() #+RESULTS: #+begin_example main.cpp: In function ‘int main()’: main.cpp:2:14: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive] 2 | int number = "12 + 13"; | ^~~~~~~~~ | | | const char* #+end_example ``` Pressing `C-c C-c` in the `#+CALL` statements will tangle the nearest source code block and then will execute `g++` on the tangled file. # Answer > 1 votes If you look at ob-C.el function `org-babel-C-execute`, you'll see that it compiles and links a program to `tmp-bin-file`, then runs it and captures its output to `results`. So you need a different source-file type eg `cpp-wrong` that you would execute using shell that invokes g++ and captures its stderr as you hinted above. Maybe copy ob-C.el and try to modify it according ot the above blueprint? --- Tags: org-mode, org-babel ---
thread-12787
https://emacs.stackexchange.com/questions/12787
Two Python modes
2015-05-29T12:38:38.490
# Question Title: Two Python modes I have been trying to configure Emacs to use the proper Python mode. To this end I have read a few tutorials. Most importantly this one. The tutorial uses the `python-mode` package. However, when I install it through the package manager (`M-x package-install RET python-mode RET`) I can not use the shortcuts that are available for that package. I opened up a Python file to test some shortcuts such as `C-c |`, which should evaluate the selected expression. However, to my surprise these did not work so I decided to find out other tutorials on the topic. However, in my mode-line I do see `Python`, so there is some `python-mode` enabled. On the emacs wiki I found the following snippet to add to my `init.el` file: ``` (autoload 'python-mode "python-mode" "Python Mode." t) (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode)) (add-to-list 'interpreter-mode-alist '("python" . python-mode)) ``` When I add this the `python-mode` actually works and the aforementioned shortcuts work as well. I do not understand properly what this does more than manually executing `M-x python-mode` in a python file buffer. When I removed every trace of `python-mode` in my .emacs folder and opened up a python file I noticed that I still have a `python-mode`. So my guess is that there are two `python-mode`s? I think I want the `python-mode` from https://launchpad.net/python-mode. It seems that it is present in the package repository, but I am unsure how to remove the other Python mode. Could somebody elaborate please? # Answer Well yes there are two python modes: the one which ships with emacs is `python.el` and the other one is `python-mode.el` which is indeed this one: https://launchpad.net/python-mode Your tutorial has been referencing the later one. Your `python-mode` setup snippet does the following: ``` ;; by default, the function 'python-mode is associated with ;; the package python.el. The following changes that to python-mode.el: (autoload 'python-mode "python-mode" "Python Mode." t) ;; open py files with python-mode (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode)) ;; sets python interpreter mode to be python-mode (add-to-list 'interpreter-mode-alist '("python" . python-mode)) ``` > 12 votes # Answer As a maintainer of python-mode.el and in addition to answer by @Adobe: python-mode.el does not unload commands from python.el - both are available. Due to name of python-mode-map --which is used by both and can't be changed without breaking a lot of things-- keybindings and menu are delivered from the last one loaded. `C-c |` calls `py-execute-region` and works nicely here. Maybe python.el was loaded afterwards and the binding gone. Calling the command via M-x might be an option than. In case of trouble, please consider a bug-report at https://bugs.launchpad.net/python-mode > 8 votes # Answer Despite some people using this package, and despite the fact that it seems to be the first Python supporting library for Emacs, I recommended to the author to rename the feature of this library, maybe to something like 'py-mode'. As it stand, as soon as you download the python-mode.el file and it sits inside your ~/.emacs.d/elpa directory it will be used by Emacs over the python.el that is now packaged with Emacs. The confusion comes from the clash of these 2 files: * The python.el file that is packaged with Emacs provide the feature 'python-mode and the major mode command 'python-mode. * The python-mode.el file you can get from MELPA provides the same 'python-mode feature and major mode. I wish this situation would not be allowed by package managers and since python.el is now distributed with Emacs I think the authors of python-mode should rename, at the minimum, their feature and probably their file. > 1 votes --- Tags: python ---
thread-60200
https://emacs.stackexchange.com/questions/60200
Magit remove local branches that were merged into another branch
2020-08-18T04:01:33.323
# Question Title: Magit remove local branches that were merged into another branch Explaining the problem more in-depth than the titular definition: Often I merge branches into master and want to prune based on that. `M-p` works fantastic for removing the remote branches (eg `origin/mergedbranch`) but not the local branch (eg `mergedbranch`) that referenced it before. I'm left with branches like the in the screenshot below. There seem to be a lot of cli git commands such as this SO answer, but I was wondering if there was a magit equivalent. # Answer The refs buffer has options to filter to merged branches. Quoting `C-h``i``g` `(magit)References Buffer`: > ‘y’ (‘magit-show-refs’) > This command lists branches and tags in a dedicated buffer. However if this command is invoked again from this buffer or if it is invoked with a prefix argument, then it acts as a transient prefix command Therefore you can access that transient menu with `y``y`<sup>1</sup> Within the transient menu you can refine the view with `-``M` setting the value to the merge target (E.g `develop` or `main`). Then type `y` to execute the command, comparing against `HEAD`. The refs list you are left with should only contain merged branches. Now highlight all the branches you would like to delete, then press `k` to delete the selection.<sup>2</sup> Remember that you can set and save default transient values with `C-x``s` and `C-x``C-s` respectively. --- <sup>1</sup> or `C-u``M-x` `magit-show-refs`, or in Evil it's `y``r``y``r`. <sup>2</sup> or `M-x` `magit-delete-thing`, or in Evil it's `x`. > 10 votes # Answer There's no such command, but it wouldn't be hard to create one if you know a little emacs lisp and look at other `magit-branch-*` commands and the SO answers you mentioned. If you do, then please submit a pull-request. > 1 votes --- Tags: magit, git ---
thread-63455
https://emacs.stackexchange.com/questions/63455
Repeating characters in `python-mode.el` shell interaction
2021-02-18T08:15:22.560
# Question Title: Repeating characters in `python-mode.el` shell interaction I experience strange behaviour when using `python-mode`. When sending characters to the shell using `C-c C-e`, the first string works well. After that, the characters start repeating, in a manner that is best understood by looking at the screenshot below. Now what is also strange is that this behaviour is also present in the minibar. If I start emacs with `emacs -q` this doesn't happen. I'm looking to find what mode or setting is causing this, but I'm not knowledgeable enough to guess where to look. The minor modes that are switched on are these: ``` Async-Bytecomp-Package Auto-Composition Auto-Compression Auto-Encryption Blink-Cursor Company-Quickhelp Company-Quickhelp-Local Counsel Counsel-Projectile Delete-Selection Display-Line-Numbers Doom-Modeline Eldoc Electric-Indent File-Name-Shadow Font-Lock Global-Eldoc Global-Font-Lock Global-Git-Commit Global-Magit-File Ido-Everywhere Ivy Line-Number Magit-Auto-Revert Mouse-Wheel Org-Roam Override-Global Projectile Pyvenv Pyvenv-Tracking Recentf Shell-Dirtrack Tooltip Transient-Mark Which-Key Window-Numbering ``` The relevant configuration I guess in my `init.el` ``` (use-package python-mode :ensure t :custom (python-shell-interpreter "ipython3") ``` If I use `python` for interpreter, this doesn't happen, which leads me to believe there is something wrong with the regexes used for determining the prompt. However, why does the minibar show this as well? Perhaps something else with the code that drives the inferior mode? I would be grateful and will accept some pointers from someone that understands a bit better how this works, a plausible cause and explanation for this behaviour. # Answer Two observations related to your configuration: a) You started with the external package `python-mode` which may not be what you want. Instead, try using the internal package `python` this way: ``` (use-package python :ensure nil ;; built-in package ;; the rest of your configuration) ``` b) To have ipython correctly working, you need to add these lines below to your config: ``` (setq python-shell-interpreter "ipython3" python-shell-interpreter-args "-i --simple-prompt") ``` This setting is needed beginning with version 5 of ipython, as suggested here. > 1 votes --- Tags: python, shell, inferior-buffer ---
thread-63481
https://emacs.stackexchange.com/questions/63481
How to fill in a formula into adjacent cells in org-mode spreadsheet?
2021-02-20T11:05:58.920
# Question Title: How to fill in a formula into adjacent cells in org-mode spreadsheet? For example, in the following table ``` |------------+------------+-----+-----+-----+-----+-----+-----+-----+-----| | Pobability | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | | Odds | =B1/(1-B1) | | | | | | | | | | Logit | =ln(B2) | | | | | | | | | |------------+------------+-----+-----+-----+-----+-----+-----+-----+-----| ``` I'd like to automatically fill * C2 with `=C1/(1-C1)`, D2 with `=D1/(1-D1)`, etc. * C3 with `=ln(C2)`, D3 with `=ln(D2)`, etc. # Answer > 2 votes The Org mode spreadsheet is not like Excel: you don't create formulas in one cell and then propagate them to other cells (well, you *can* \- do `C-h i g (org)Field and range formulas`, but propagating them is basically a matter of cutting and pasting). You can instead use a `#+TBLFM` after the table to do all that: ``` |------------+------------+------------+-------------+-------------+-----+------------+------------+-----------+-----------| | Pobability | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | | Odds | 0.11111111 | 0.25 | 0.42857143 | 0.66666667 | 1. | 1.5 | 2.3333333 | 4. | 9. | | Logit | -2.1972246 | -1.3862944 | -0.84729786 | -0.40546510 | 0. | 0.40546511 | 0.84729785 | 1.3862944 | 2.1972246 | |------------+------------+------------+-------------+-------------+-----+------------+------------+-----------+-----------| #+TBLFM: @2$2..@2$> = @1/(1-@1) :: @3$2..@3$> = ln(@2) ``` Do `C-h i g (org) References RET` for the details of how to refer to cells. --- Tags: org-mode, org-table, calc, spreadsheet ---
thread-63485
https://emacs.stackexchange.com/questions/63485
Delete single window frame after app quits
2021-02-20T12:29:54.877
# Question Title: Delete single window frame after app quits Some of the apps (w3m, elfeed, mu4e, to name a few) when quit leave unused frame so the other buffer shows up in their place. Over time these redundant frames pile up, so we have to delete them. I look for a way to automate it, by deleting these frames if there is only one window inside with an app that just quit. I want to use it for buffers used by `w3m`, `mu4e`, `elfeed`, `erc`. If we just close the frame, the app will still be lurking around. The next time I will need it and call the command it may create another instance instead of reusing existing one. That's why it would be better to delete the frame on app quit rather than keeping it alive without active window. It would be perfect to configure it selectively using `display-buffer-alist` if that's possible. # Answer Could you not simply delete the frame, `C-x 5 0` rather than the window `C-x 0`? > 1 votes --- Tags: window, frames ---
thread-62653
https://emacs.stackexchange.com/questions/62653
Defining variables in org mode using tables
2021-01-07T20:02:42.883
# Question Title: Defining variables in org mode using tables I often want to define a whole bunch of variables at the top of an org file. In some cases I think it would be really nice to define all the variables in a table. So far, the best solution I've come up with is this: ``` #+NAME: variables | Variable | Value | Description | |----------+------------+-------------| | user1 | alice | Manager | | user2 | bob | Developer | #+NAME: lookup #+begin_src emacs-lisp :var data=variables var="a var name" (nth 1 (assoc var data)) #+end_src #+begin_src sh :var user=lookup(var="user1") echo $user #+end_src #+RESULTS: : alice ``` That works, but the syntax `:var user=lookup(var="user1")` is verbose, and it gets tiresome to call `lookup` in *every* `:var` header argument. I'm wondering if there is a way to register each variable and value in the table as though they were defined like this: ``` #+NAME: user1 : alice #+NAME: user2 : bob ``` That way, you could write source blocks with simple and familiar `:var` header arguments, like: ``` #+begin_src sh :var user=user1 echo $user #+end_src #+RESULTS: : alice ``` So I guess my question is: is there a way to "register" the variables/values in the `variables` table in such a way that would let me use them like `:var user=user1`? Or even just an alternative way to do something similar that you find works for you? **EDIT**: I perused the org source code a bit; I don't see any super easy way to do this. Maybe the best idea would be to introduce a new header argument, like `#+begin_src :tblvar user=user1`, which resolves variables defined in a table. # Answer I don't find this any easier than what you have already shown, but here are some different approaches that use advanced features (https://orgmode.org/manual/Advanced-features.html) of naming fields in tables. You have to put the $ in the first column to name these constants. Getting these into your variable is a little verbose, but explicit at least. The `org-table-get-remote-range` function returns a string of the value in parentheses, so I use read to turn it into lisp, then a car in the front to get the element from the list. ``` #+NAME: variables | | Value | Description | |---+-------------+-------------| | $ | user1=alice | Manager | |---+-------------+-------------| | $ | user2=bob | Developer | #+begin_src sh :var user=(car (read (org-table-get-remote-range "variables" "$user2"))) echo $user #+end_src #+RESULTS: : bob ``` If having extra functions is on the table, you might do something like this: ``` #+BEGIN_SRC emacs-lisp (defmacro ot (name field) `(car (read (org-table-get-remote-range ,(symbol-name name) , (symbol-name field))))) #+END_SRC ``` so that it is a little shorter: ``` #+begin_src sh :var user=(ot variables $user2)) echo $user #+end_src #+RESULTS: : bob ``` The final version, which may not be a good idea is to load the variables in the table to a local variable space in the buffer. To do this, you have to get the variables by going to the table, analyzing it and then using setq-local to add them to the local space. ``` #+BEGIN_SRC emacs-lisp (defun org-goto-named-table (name) (let ((pos (catch 'pos (cl-loop for table in (org-element-map (org-element-parse-buffer) 'table 'identity) do (when (string= name (org-element-property :name table)) (throw 'pos (org-element-property :contents-begin table))))))) (when pos (goto-char pos)))) (defun org-load-local-table-variables (name) (save-excursion (org-goto-named-table name) (org-table-analyze) (cl-loop for (name . value) in org-table-local-parameters do (eval `(setq-local ,(intern name) value))) org-table-local-parameters)) #+END_SRC ``` Then you need a src block to run the function that loads them: ``` #+BEGIN_SRC emacs-lisp (org-load-local-table-variables "variables") #+END_SRC #+RESULTS: : ((user2 . bob) (user1 . alice)) ``` And finally, you can use \`, notation to use those var-names in your src-blocks. I leave it to you to decide if these variables should be prefixed, e.g instead of user2, maybe variables-user2. ``` #+begin_src sh :var user=`,user2 echo $user #+end_src #+RESULTS: : bob ``` You might also consider variations on this theme where instead of using setq-local, you use the returned results of the org-load-local-table-variables and do look up by alist, etc... > 4 votes # Answer I use `#+constants: variable=value` for this and then `(org-table-get-constant "variable")` to get the value for src blocks etc. The advantage is that constants can be used directly in tables with `$variable`. > 1 votes --- Tags: org-mode, org-babel ---
thread-63480
https://emacs.stackexchange.com/questions/63480
How to compute ln in Org-Mode spreadsheet
2021-02-20T10:35:22.007
# Question Title: How to compute ln in Org-Mode spreadsheet Is there a formula to compute the natural logarithm of a number in Org-Mode spreadsheet? For example, to compute ln(1), Excel or Calc formula is `=ln(1)`, what would it be in Org-Mode? The result should be 0 as ln(1)=0. # Answer > 1 votes You can either use the calc syntax or the elisp syntax. ``` | x | calc syntax | elisp syntax | |---+-------------+--------------| | 1 | 0 | 0.0000 | | 2 | 0.6931 | 0.6931 | #+TBLFM: $2=log($1);n4::$3='(log $1);N%.4f ``` Notice that the output format of the calc syntax depends on the ~/.emacs.d/calc.el parameters. ``` (plist-put org-calc-default-modes 'calc-language 'latex) (plist-put org-calc-default-modes 'calc-symbolic-mode t) | x | calc syntax | elisp syntax | | |---+-------------+--------------+---| | 1 | 0 | 0.0000 | | | 2 | \ln{2} | 0.6931 | | #+TBLFM: $2=log($1);n4::$3='(log $1);N%.4f ``` # Answer > 0 votes Well, actually `=ln(1)` works in `org-table`, I just tested it. I didn't know because I didn't find it in the documentation... --- Tags: org-mode, org-table, calc, spreadsheet ---
thread-17380
https://emacs.stackexchange.com/questions/17380
Automization of preview-latex
2015-10-14T17:41:06.750
# Question Title: Automization of preview-latex The preview-latex package behaves in the following manner: it shows you an image of a formula / section header / etc. When the cursor gets "into" the image it is automatically replaced by the latex code. Once you're done, the user is supposed to hit C-c C-p C-p to update the preview. What I would like: instead of a manual process (hitting C-c C-p C-p), I would prefer that whenever I finish editing a formula, the images should be updated automatically. Is that possible? Warning: I'm a novice emacs user. FWIW, I'm using Aquamacs 3.2 GNU Emacs 24.4.51.2 , but I'm pretty sure this applies to standard emacs as well. # Answer > 2 votes This package, org-fragtog, seems to be a perfect solution. Although it's designed for org-mode, it works in LaTeX-mode as well. Simply install that package and enable `org-fragtog-mode` in your buffer. Then, after doing a `preview-at-point`, as your cursor goes in and out an equation, it automatically disables and enables rendering. Animation from org-fragtog github page: # Answer > 1 votes Here is my start of solution, it can be improved, see below. Add the following code to your init file and restart Emacs: ``` (defun mg-LaTeX-preview-formulae () (and (eq major-mode 'latex-mode) (not (texmathp)) (preview-section))) (add-hook 'LaTeX-mode-hook (lambda () (setq mg-LaTeX-preview-formulae-timer (run-with-idle-timer 1 nil 'mg-LaTeX-preview-formulae)))) ``` With this code, after 1 second of idle time (I mean: **every time** you do nothing for 1 second, but you can change the time in the last line of the above code) it's run the preview of the current section (trying to be as conservative as possible). Emacs can't really know which is the last equation you edited if you exit from it. You could use `preview-at-point` to preview the current equation you are in, but this is probably uncomfortable while you're writing it. As it is implemented above, I think this feature is really annoying while you write (but increasing the idle time can help), so you can run `M-:` `(cancel-timer mg-LaTeX-preview-formulae-timer)` `RET` in order to eliminate this for the current Emacs session, and remove the above code for the future sessions. The problem is: how do you think you can tell Emacs you want to see the preview? --- Tags: latex, preview-latex ---
thread-63488
https://emacs.stackexchange.com/questions/63488
How do I pass a variable definition as a parameter to a command in the minibuffer?
2021-02-20T14:10:18.350
# Question Title: How do I pass a variable definition as a parameter to a command in the minibuffer? I am an emacs novice. I am familiarizing myself with making basic changes to the `init.el` file. Currently, when I want to load `init.el`, I first `C-h v user-init-file RET`, this opens a `*Help*` screen which gives me its definition, and therefore the location of the file. I then highlight and `M-w` its value, then `C-x f` to a file requester, then delete the default, then `C-y` the copied file address then `RET`. This looks incredibly convoluted. What I want to know is, can I cut out all of that and instead simply `C-x f` to a file requester and then pass the `user-init-file` definition straight to it, with whatever the emacs notation is for expanding variables (which I don't know)? The help files I have read discuss only examining and setting variables, not using them in the minibuffer. In short, is there a notation for using variable definitions in a minibuffer command? # Answer > 3 votes One way is to type `M-:` which will prompt you for an expression to evaluate, and then in the mini-buffer type `(find-file user-init-file) RET`. You can press `TAB` while typing that to complete both the function and variable name. While that init file is open, you might consider bookmarking it (`C-x r m` or `Edit->Bookmarks->Set bookmark`). Then later, you can just jump to it with (`C-x r b` or `Edit->Bookmarks->Jump to bookmark`). I am not aware of an easy way to insert the value of a variable in the minibuffer with vanilla Emacs. # Answer > 2 votes As a technically correct answer to your question, you can programmatically insert arbitrary text into the minibuffer if you set the variable `enable-recursive-minibuffers` to a true value in your init file: ``` (setq enable-recursive-minibuffers t) ``` With this option enabled, you could start the find-file operation with `C-x` `C-f`, then insert the value of a variable by calling the `eval-expression` command with `M-:` and providing `(insert user-init-file)` to it. This will append the value of the variable to the original contents of the minibuffer. There's no need to delete the original contents; when Emacs sees two slashes, it treats the second slash as starting a brand new absolute file path. (This behavior would also let you shorten your original process of yanking the path from the Help buffer.) With more work it would be possible to add a new key binding when finding a file, for a command which prompts for a variable and then inserts the value of that variable. But really, I feel that the bookmark approach is the way to go, since that's what I do. My Emacs init file bookmark is named simply `e`, so to visit the file, I type `C-x` `r` `b` `e` `RET`. It's a not insignificant number of keystrokes, but to me it's appropriate considering how often I visit the file. Another alternative would be to write a very short command that just visits your init file: ``` (defun visit-init-file () (interactive) (find-file user-init-file)) ``` You could bind this command to a convenient key: ``` (global-set-key (kbd "C-c i") 'visit-init-file) ``` --- Tags: minibuffer, variables ---
thread-63495
https://emacs.stackexchange.com/questions/63495
How to configure lsp-cmake lsp server in vanilla emacs
2021-02-20T19:11:41.310
# Question Title: How to configure lsp-cmake lsp server in vanilla emacs I want to setup lsp-cmake lsp server in my vanilla emacs. I just installed lsp server using `pip install cmake-language-server`. I don't know how to configure in my emacs init.el to use the lsp server. The couldn't find any documentation as well for emacs. How can I configure lsp-cmake in my init file for emacs # Answer > 2 votes You can try something like the following. ``` (use-package lsp-mode :ensure t) (use-package cmake-mode :ensure t :mode ("CMakeLists\\.txt\\'" "\\.cmake\\'") :hook (cmake-mode . lsp-deferred)) (use-package cmake-font-lock :ensure t :after cmake-mode :config (cmake-font-lock-activate)) ``` The `lsp-mode` package provides additional features like integration with `which-key`, showing `diagnostics` and `breadcrumbs`, which you may want to explore if they are important for you with `cmake-mode`. --- Tags: init-file, lsp-mode, lsp ---
thread-63466
https://emacs.stackexchange.com/questions/63466
Multiple timestamps for various states in TODO lists
2021-02-19T12:47:51.903
# Question Title: Multiple timestamps for various states in TODO lists I'm finding `TODO` lists in org-mode incredibly useful. For example, say I have a task to send an email, I define the following sequence in my `init.el` file: ``` ;; Sequence in TODO list (setq org-todo-keywords '((sequence "EMAIL" "SENT" "|" "RESPONSE" "CANCELLED"))) ``` Once the email is sent, I switch it from `EMAIL` to `SENT` and then to `RESPONSE` when I get an email back. Great! And I can timestamp the `RESPONSE` like so: ``` ;; Timestamp on completed tasks (setq org-log-done 'time) ``` Now, I'd like to extend this further, so that I get a timestamp for `SENT`, which I can do by shifting `"|"` to the left of `SENT`. But when I toggle to `RESPONSE`, I don't get a new timestamp because the task is already closed. Is there a way to get timestamps that persist for multiple states of a `TODO` list item (i.e., for both `SENT` and then `RESPONSE`)? # Answer Instead of just rely on the done/not done state, you can specify for each task if you should record a timestamp on entering/leaving it. The relevant bit from `C-h v org-todo-keywords` is > Each keyword may also specify if a timestamp or a note should be recorded when entering or leaving the state, by adding additional characters in the parenthesis after the keyword. This looks like this: "WAIT(w@/!)". "@" means to add a note (with time), "!" means to record only the time of the state change. With X and Y being either "@" or "!", "X/Y" means use X when entering the state, and use Y when leaving the state if and only if the *target* state does not define X. You may omit any of the fast-selection key or X or /Y, so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid. So ``` (setq org-todo-keywords '((sequence "EMAIL" "SENT(!)" "|" "RESPONSE(!)" "CANCELLED"))) ``` Will record a timestamp when the state becomes `SENT` or `RESPONSE` > 3 votes --- Tags: org-mode, todo ---
thread-63505
https://emacs.stackexchange.com/questions/63505
How to open org-mode table as a pandas dataframe (with column names)?
2021-02-21T10:39:54.493
# Question Title: How to open org-mode table as a pandas dataframe (with column names)? I can't find how to open an `org-mode` table as a `pandas` dataframe. Here is my example: ``` #+NAME:tbl | a | b | |---|---| | 1 | 2 | #+BEGIN_SRC python :var tbl=electro :results replace output :session test :exports both import pandas as pd df = pd.DataFrame(tbl) print(df) #+END_SRC ``` Here I get the dataframe, but the columns are `1 2` # Answer I am sorry, I found (probably) a solution (my actual example): ``` #+NAME:electro | TIME | low | high | heatpump | water | accurain | repy1 | repy2 | repy3 | repy4 | |-------------------------+-------+------+----------+-------+----------+-------+-------+-------+-------| | 2016-10-15 08:41:00.000 | 24830 | 3242 | 7308 | 2294 | NaN | | | | | | 2016-10-23 10:38:53.000 | 24963 | 3254 | 7362 | 2317 | | | | | | | 2016-10-30 19:36:38.000 | 25107 | 3265 | 7417 | 2342 | | | | | | | #+BEGIN_SRC python :var tbl=electro :hlines no :colnames no :results replace output :session test :exports both import pandas as pd df = pd.DataFrame(tbl[1:], columns=tbl[0]) # and now more tricks... df = df.replace('', np.nan) df = df.replace('NaN', np.nan) print(df) df.to_hdf("test.h5",key="key1",mode='w') #+END_SRC ``` The solution was to add `:colnames no` to prevent babel from removing the header. > 1 votes --- Tags: org-mode, python ---
thread-63507
https://emacs.stackexchange.com/questions/63507
How to run commands locally even when on tramp?
2021-02-21T13:17:47.843
# Question Title: How to run commands locally even when on tramp? I have some commands that do "utility" stuff that have nothing to do with the current buffer. I need these to always run locally, and not remotely when visiting a tramp buffer. How can I do this? Here is the function in question: ``` (if load-file-name (setq night/fzf-cmd (concat (file-name-directory load-file-name) "/fzf_in2.dash"))) (defun night/helper-counsel-fzf-entries (str) (let ((entries night/counsel--fzf-entries)) (setq ivy--old-re (ivy--regex-fuzzy str)) (let ((night/counsel--stdin (mapconcat (lambda (x) x) entries "\n"))) (f-write-text night/counsel--stdin 'utf-8 "/tmp/nightFzf.txt") (counsel--async-command (list night/fzf-cmd "-f" str) ))) nil) ``` # Answer > 3 votes The point is `default-directory`. If it is local, your command runs locally. So do something like ``` (let ((default-directory "/")) (do your stuff)) ``` --- Tags: tramp, shell-command ---
thread-63430
https://emacs.stackexchange.com/questions/63430
Restore emacs' default undo/redo behavior in spacemacs
2021-02-16T13:22:35.727
# Question Title: Restore emacs' default undo/redo behavior in spacemacs I've recently moved to spacemacs and it seems that they've adopted a different undo package (undo-tree) which I don't like since it does not push the undo actions back onto the history stack. I would like to restore the default behavior but I can't seem to figure out how to do this. `C-/` is bound to `undo-tree-undo` in spacemacs. I've tried to unbind this and use emacs' `undo` instead, but that does't seem to work. I've added the following in my `user-config.el`: ``` (global-unset-key (kbd "C-/")) (global-set-key (kbd "C-/") 'undo) ``` But the key remains bound to the undo-tree method. I've also tried bind it to a new key, but the same seems to happen. It's as if spacemacs redirects call to for `undo` to `undo-tree-undo`. Is there anyway to fix this? Thank you. *EDIT* I've also tried adding `undo-tree` to the `dotspacemacs-excluded-packages` but it doesn't seem to get rid of it. # Answer > 3 votes Well, turns out the solution is easier then I imagined. Just add the following to your `user-config.el` file: ``` (global-undo-tree-mode 0) ``` --- Tags: spacemacs, undo, undo-tree-mode ---
thread-63503
https://emacs.stackexchange.com/questions/63503
Custom search for text under cursor
2021-02-21T06:05:28.597
# Question Title: Custom search for text under cursor I would like to write a custom elisp function that searches for a few variants of unicode text **under a cursor** and highlights their occurrences in the currently open file. For e.g. if my text is `helloम्` (it ends with bytes `U2350+U2381`) the function should search a modified version of the text `helloं` (i.e. `hello+U2306`) The unicode bytes are always at the end of the word. I started with a simple elisp function that would print a message if a text that matches my criteria is found and saving the modified string to be searched into a variable: ``` (defun c-search () "If word under cursor ends with U2350+U2381, search for word+U2306" (interactive) (if (string-match-p "म्" (thing-at-point 'word)) (setq z (replace-regexp-in-string "म्$" "ं" (thing-at-point 'word))) (message "Should search %s" z))) ``` Nothing gets printed when I evaluate this function. However, the following function that searches and replaces the string works fine: ``` (defun rrx () (interactive) (setq z (replace-regexp-in-string "म्$" "ं" (thing-at-point 'word))) (message z)) ``` How can I fix function `c-search` to perform a search for the string saved in variable `z`? # Answer > 1 votes > I would like to write a custom elisp function that searches for a few variants of unicode text under a cursor and highlights their occurrences in the currently open file. I took this as the task and wrote a function that *highlights* the variant of the symbol at point. It doesn't search for it, nor replace it. This way you can move freely while the matches are highlighted. Here's the function, ``` (defun c-search () "If word under cursor ends with U2350+U2381, highlight all occurrences of word+U2306" (interactive) (save-excursion (let ((bos (re-search-backward "\\_<")) (eos (re-search-forward "\\_>"))) (goto-char bos) (when (re-search-forward ".*म्" eos) (highlight-regexp (replace-regexp-in-string "म्$" "ं" (match-string-no-properties 0))))))) ``` Notice it searches within the *symbol* (delimited by `\_<` and `\_>`) at point instead of the *word* (delimited by `\b`) at point, because (at least in Emacs Lisp mode) words are splitted at the character `म्`, so if you search until the end of the word, or if you use `(thing-at-point 'word)`, the search stops short of `म्`. `hi-lock` saves the regexps it highlights in the variable `hi-lock-interactive-patterns`. The latest regexp it has highlighted is the car of the car of that variable, which means you can access it with `(caar hi-lock-interactive-patterns)` if you need it. For example, you can unhighlight the latest highlight with this function: ``` (defun unhighlight-latest-regexp () (interactive) (unhighlight-regexp (caar hi-lock-interactive-patterns))) ``` --- Tags: search, highlighting, unicode ---
thread-63508
https://emacs.stackexchange.com/questions/63508
Does icicles works with emacs28? Debugger entered--Lisp error: (wrong-number-of-arguments (3 . 3) 2)
2021-02-21T13:23:58.207
# Question Title: Does icicles works with emacs28? Debugger entered--Lisp error: (wrong-number-of-arguments (3 . 3) 2) I am using `GNU Emacs 28.0.50` and trying to enable `icicles` within. The error I am having: For: ``` (add-to-list 'load-path "~/.emacs.d/lisp/icicles") (require 'icicles) ``` error: ``` Debugger entered--Lisp error: (wrong-number-of-arguments (3 . 3) 2) make-obsolete(icicle-scatter icicle-scatter-re) eval-buffer(#<buffer *load*-323141> nil "/home/alper/.emacs.d/lisp/icicles/icicles-fn.el" nil t) ; Reading at buffer position 247290 load-with-code-conversion("/home/alper/.emacs.d/lisp/icicles/icicles-fn.el" "/home/alper/.emacs.d/lisp/icicles/icicles-fn.el" nil t) require(icicles-fn) eval-buffer(#<buffer *load*-374269> nil "/home/alper/.emacs.d/lisp/icicles/icicles.el" nil t) ; Reading at buffer position 84578 load-with-code-conversion("/home/alper/.emacs.d/lisp/icicles/icicles.el" "/home/alper/.emacs.d/lisp/icicles/icicles.el" nil t) require(icicles) eval-buffer(#<buffer *load*> nil "/home/alper/.emacs" nil t) ; Reading at buffer position 86650 load-with-code-conversion("/home/alper/.emacs" "/home/alper/.emacs" t t) load("~/.emacs" noerror nomessage) startup--load-user-init-file(#f(compiled-function () #<bytecode 0x14c922c058d04726>) #f(compiled-function () #<bytecode -0x1f3c692ddc0f4d75>) t) command-line() normal-top-level() ``` \[Q\] What may be the reason for this error and how can I fix it? # Answer > 3 votes It looks like you don't have the latest Icicles source files. The file in question now has this code: ``` (if (< emacs-major-version 23) (make-obsolete 'icicle-scatter 'icicle-scatter-re) ; 2018-01-14 (make-obsolete 'icicle-scatter 'icicle-scatter-re "2018-01-14")) ``` So you should not see that problem. The problem you're seeing is from Emacs 28 deciding that the 3rd arg should no longer be optional. Starting with Emacs 23 the 3rd arg is possible, and starting with Emacs 28 it's mandatory. Hence the need for the conditional code now. Please download the latest Icicles files from Emacs Wiki. --- Tags: icicles, obsolete ---
thread-5387
https://emacs.stackexchange.com/questions/5387
Show org-mode hyperlink as plain text
2014-12-14T23:03:10.847
# Question Title: Show org-mode hyperlink as plain text Although it is convenient how org-mode shows hyperlinks, there are times when I want to see the underlying plain text, e.g. `[[./file.org][Title]]`. How can I do this? I know about `org-insert-link`, but it is not what I want: > C-c C-l runs the command org-insert-link, which is an interactive compiled Lisp function in \`org.el'. > > ... > > If there is already a link at point, this command will allow you to edit link and description parts. # Answer I just found a nice function in the org source code: `M-x org-toggle-link-display`. Here is the source code, just for fun: ``` (defun org-toggle-link-display () "Toggle the literal or descriptive display of links." (interactive) (if org-descriptive-links (progn (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock) (setq org-descriptive-links nil)) (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock) (setq org-descriptive-links t)))) ``` > 46 votes # Answer A useful way to do this is ``` M-x font-lock-mode ``` which toggles font locking. When font locking is off, the hyperlink is visible in its undecorated form `[[./file.org][Title]]`. This can be a useful approach for seeing other pieces of mark-up in the buffer. > 21 votes # Answer I've been using this function. It will toggle between `fundamental-mode` and the original mode (`org-mode` in this case). It's a bit weird, but I like it: ``` (defun illiterate () (interactive) (let ((coding-system-for-read 'utf-8)) (if (eq major-mode 'fundamental-mode) (revert-buffer nil t) (let ((pt (1+ (length (encode-coding-string (buffer-substring-no-properties (point-min) (point)) 'utf-8)))) (file-name (buffer-file-name))) (kill-buffer (current-buffer)) (find-file-literally file-name) (goto-char pt))))) ``` > 3 votes # Answer A low-tech way is to move point to the beginning of the link text and type C-d (i.e., invoke `org-delete-char`). That removes the first "\[" character, so that you no longer have a properly formatted hyperlink, and you can see the remainder of it as raw text. Then when you're done, just invoke `undo` to restore it to what you had previously. > 2 votes # Answer Org mode achieves the link effect using the following code: ``` (if org-descriptive-links (add-to-invisibility-spec '(org-link))) ``` This adds `org-link` to the variable `buffer-invisibility-spec` which means that text which has its invisible property set to `org-link` will be hidden. Using `M-x visible-mode RET` you can reset `buffer-invisibility-spec` temporary to `nil`, which means the hidden text will be shown from there on. Using `M-x visible-mode RET` again you can reset `buffer-invisibility-spec` to its previous value, which will hide the relevant text parts again. > 2 votes # Answer (Extending Andrew Swann above) Following may be a superset of what you want, but here goes: I typically want to see all the markup (for everything, not just for links), occasionally switching back to the default/pretty display (mostly as a form of Org syntax validation). Hence I mostly set my display to 1. turn off font-lock mode in my Org buffers, with effects as described by Swann above. 2. *wrap* aka *continue* my lines (which in Emacsish is the opposite of *truncating* lines) to show all of each line. But I am also still an Org noob, so I put the following comment at the top (TOF) of most of my Org files, ensuring that the 1st line in the comment is the 1st line of the file (thus becoming a local file variables list) ``` # -*- truncate-lines: nil; eval: (font-lock-mode -1); -*- # 1. unset->wrap long lines in display, set->don't show continuation lines # 2. unset->show undecorated text (e.g., don't prettify hyperlinks), set->display pretty ``` Eventually I'll either put this in my init file, or just adapt to the default Way of Org. But for now, it both 1. configures the display behavior I want by default. 2. reminds me what to do to get back to the default Org display. I don't yet want to put this in my init.el, because that makes it harder for me to remember how to toggle these display aspects. Note also that 1. `truncate-lines` is a normal variable, so one can just set it=`nil` as above. But ... 2. `font-lock-mode` is a minor mode, so that requires the `eval` above to turn off, per The Fine Manual). 3. You can also put the local-variables list at EOF with different syntax (RTFM again), but I'm more likely to see it at TOF. > 0 votes --- Tags: org-mode ---
thread-62987
https://emacs.stackexchange.com/questions/62987
Cannot set correct size for variable pitch font in Doom Emacs
2021-01-25T01:50:35.563
# Question Title: Cannot set correct size for variable pitch font in Doom Emacs I am trying to use a variable-pitch font for Org-mode: ``` (add-hook! 'org-mode-hook #'mixed-pitch-mode) ``` I am specifying a variable pitch font that is normally renders much smaller than the fixed pitch one: ``` (setq doom-font (font-spec :family "Fira Code" :style "Retina" :size 14) doom-variable-pitch-font (font-spec :family "ETBembo") doom-big-font (font-spec :family "Fira Code" :style "Retina" :size 24)) ``` However, no matter what I do I cannot change the size of the default text face in Org mode. I can change size for title, org-levels, etc. but not the default text font. I've tried this: ``` (setq doom-font (font-spec :family "Fira Code" :style "Retina" :size 14) doom-variable-pitch-font (font-spec :family "ETBembo" :height 1.3) doom-big-font (font-spec :family "Fira Code" :style "Retina" :size 24)) ``` and this: ``` (setq doom-font (font-spec :family "Fira Code" :style "Retina" :size 14) doom-variable-pitch-font (font-spec :family "ETBembo" :size 18) doom-big-font (font-spec :family "Fira Code" :style "Retina" :size 24)) ``` and even this: ``` (after! org (custom-set-faces! '(org-default :weight normal :slant normal :height 2.9))) ``` and it still fails. Can somebody help me? screenshot: # Answer I found the answer. Doing this does the trick: ``` (use-package! mixed-pitch :hook (org-mode . mixed-pitch-mode) :config (setq mixed-pitch-set-heigth t) (set-face-attribute 'variable-pitch nil :height 1.3)) ``` I have set the height for my normal font to 1.0: ``` (setq doom-font (font-spec :family "Fira Code" :style "Retina" :size 14 :height 1.0) doom-variable-pitch-font (font-spec :family "ETBembo" :style "RomanOSF" :height 1.3) doom-big-font (font-spec :family "Fira Code" :style "Retina" :size 24)) ``` Reference: I found this from this link. > 2 votes --- Tags: org-mode, fonts, doom ---
thread-63515
https://emacs.stackexchange.com/questions/63515
How can I set and retain font size of the solarized-theme?
2021-02-21T19:12:16.287
# Question Title: How can I set and retain font size of the solarized-theme? I like the solarized (light) theme in emacs but i have a 27" mac so the font is too small. I know I can enlarge with C-x C-+ but I do not know how to set the font size and retain that setting so I need not change manually. Any advice? Thanks # Answer I ain't no expert on fonts. Let me know if this works for you (It's supposed to set font size to be 20): ``` (let ((fsize 20) ;; font size (fs (font-spec :name (frame-parameter nil 'font)))) (font-put fs :size fsize) (set-frame-font fs nil t) (let ((new-font (frame-parameter nil 'font)) (current-default (assq 'font default-frame-alist))) (if current-default (setcdr current-default new-font) (push (cons 'font new-font) default-frame-alist)))) ``` > 0 votes --- Tags: fonts, themes ---
thread-63526
https://emacs.stackexchange.com/questions/63526
How do I use global-unset-key for non ASCII characters?
2021-02-22T11:23:27.037
# Question Title: How do I use global-unset-key for non ASCII characters? I am using QWERTZ with Czech layout and to write certain characters like `{` and `}` I have to press down `option`, however in my emacs (using the emacsformacosx version) the `option` key is bound to the Meta key. In my `~/.emacs.d/init.el` file I added the following lines: ``` ;;; To unset the M- (global-unset-key (kbd "M-+")) (global-unset-key (kbd "M-ě")) (global-unset-key (kbd "M-š")) (global-unset-key (kbd "M-č")) (global-unset-key (kbd "M-ř")) (global-unset-key (kbd "M-ž")) (global-unset-key (kbd "M-ý")) (global-unset-key (kbd "M-á")) (global-unset-key (kbd "M-í")) (global-unset-key (kbd "M-é")) ``` however this does not work and I still keep getting the `M-<key> is undefined` in my buffer. I tried escaping the characters, but it did not work either, what is the correct approach to unset these key combinations? Thank you very much # Answer > 1 votes If those keys were defined in Emacs' global keymap then you would be unsetting them correctly, but the end result would be the same -- Emacs is receiving events it interprets as (say) `M-+` and it would tell you that nothing is bound to that key. I.e. you're trying to unbind keys which aren't bound to start with, so the result doesn't change. It's your OS which is failing to send `{` to Emacs. What you ideally want to do is tell your OS to send Emacs `{` instead of `M-<something>`, but I can't advise you how to do that. A less-ideal workaround would be to define those keys in Emacs to produce the desired result. E.g.: ``` (global-set-key (kbd "M-+") "{") ``` Or perhaps: ``` (define-key input-decode-map (kbd "M-+") "{") ``` --- Tags: org-mode, key-bindings, init-file ---
thread-63528
https://emacs.stackexchange.com/questions/63528
Persist variables (and maybe input history) across restarts
2021-02-22T11:44:31.850
# Question Title: Persist variables (and maybe input history) across restarts Sometimes I wish to persist the value of some variable when I quit emacs. For example, I would like to do this for `compile-command`. Now, I guess I could find the hook that is run when Emacs quits (assuming there is one, a quick scan through the list of hooks did not turn up an obvious candidate) and save that variable to a file of my own; and reload it in `init.el`. But surely someone else had the same need already. Is there a package or even some inbuilt way to achieve this? Bonus question: it would be *awesome* to also be able to save the history of the same. I.e., when I type `M-x compile`, I can scroll back through the previous compile commands. Would be great to keep that. Same for `M-!` with shell commands and so on. # Answer > 4 votes > Is there ... some inbuilt way to achieve this? Yes -- if you enable `savehist-mode` in your init file, then any variable you add to `savehist-additional-variables` will automatically be saved and restored between sessions. > Bonus question: it would be awesome to also be able to save the history of the same `savehist-mode` automatically saves most history variables, but this one is a bit different, so you'll need to treat it the same way. Try this: ``` (savehist-mode 1) (add-to-list 'savehist-additional-variables 'compile-command) (add-to-list 'savehist-additional-variables 'compile-history) ``` --- Tags: hooks, start-up, persistence, savehist-mode ---
thread-63517
https://emacs.stackexchange.com/questions/63517
Org Mode evaluate diff code block
2021-02-21T21:00:03.167
# Question Title: Org Mode evaluate diff code block I'm writing a programming tutorial. In between the prose I have diff code blocks that show exactly what changes are done to the code on each step. To make sure the diffs are correct I'd like to be able to evaluate them using `patch` command. Here is an example: ``` * Setup tests Bla bla bla... #+begin_src diff --- a/elm.json +++ b/elm.json @@ -18,7 +18,11 @@ } }, "test-dependencies": { - "direct": {}, - "indirect": {} + "direct": { + "elm-explorations/test": "1.2.2" + }, + "indirect": { + "elm/random": "1.0.0" + } } } ``` Is it possible to do this from Emacs? When I try to evaluate this code block (pressing Enter inside it) I get: ``` No org-babel-execute function for diff! ``` I'm using Doom Emacs on Linux. # Answer > 5 votes You can make your own execute function for diff blocks. ``` #+BEGIN_SRC emacs-lisp (defun org-babel-execute:diff (body params) (with-temp-buffer (insert body "\n") (shell-command-on-region (point-min) (point-max) "patch" "*patch*") (prog1 (with-current-buffer "*patch*" (buffer-string)) (kill-buffer "*patch*")))) #+END_SRC ``` #+RESULTS: : org-babel-execute:diff Here are two files that we should tangle, they differ only slightly in the second line. ``` #+BEGIN_SRC org :tangle a.org 1 2 #+END_SRC #+BEGIN_SRC org :tangle b.org 1 3 #+END_SRC ``` Now, run this block to generate the two files, and create the diff block. After that, you can "run" the diff block by typing C-c C-c in it, which will apply the patch to a.org. ``` #+BEGIN_SRC sh :results raw :var diff=(org-babel-tangle) :wrap src diff exec 2>&1 diff -u a.org b.org : #+END_SRC #+RESULTS: #+begin_src diff --- a.org 2021-02-21 20:20:27.000000000 -0500 +++ b.org 2021-02-21 20:20:27.000000000 -0500 @@ -1,2 +1,2 @@ 1 -2 +3 #+end_src #+RESULTS: : patching file a.org #+BEGIN_SRC sh cat a.org #+END_SRC #+RESULTS: | 1 | | 3 | ``` This is only tested on this example, but I guess should work for others. # Answer > 2 votes Another implementation, possibly shorter. Does not require elisp. ``` #+NAME: diff #+BEGIN_SRC bash :var a="foo.txt" b="bar.txt" :results verbatim :wrap src diff diff -u $a $b patch -s $a <(diff -u $a $b) #+END_SRC ``` ``` #+CALL: diff(a="foo.txt", b="bar.txt") ``` ``` #+RESULTS: #+begin_src diff --- foo.txt 2021-02-22 04:58:22.638960760 -0800 +++ bar.txt 2021-02-22 04:58:29.434904292 -0800 @@ -1,2 +1,2 @@ -hello +goodbye world #+end_src ``` --- Tags: org-mode, org-babel, diff ---
thread-63498
https://emacs.stackexchange.com/questions/63498
Citations with page numbers from helm-bibtex and org-ref
2021-02-21T00:13:45.157
# Question Title: Citations with page numbers from helm-bibtex and org-ref I currently use `org-ref` and `helm-bibtex` with one notes file per source to manage my library. For any given source, I may have several headers, each for notes on different chapters or topics I have captured. But now I want to cite a note, and I want to include the page numbers it references... But how do you do this with only one notes file per source? And if notes get broken out into individual files, each with their own citation, how do you avoid having multiple citations for each source show up in my helm-bibtex search window, each with the same title and author, etc? # Answer > 1 votes In org-ref, you can only cite a bibtex entry, and not a note. You can annotate the cite link with page numbers e.g. `[[cite:some-key][p200]]`, and that annotation is done manually. --- Tags: org-ref, helm-bibtex ---
thread-58773
https://emacs.stackexchange.com/questions/58773
How to pass arguments to a shell script using `make-process` function?
2020-05-28T07:35:36.973
# Question Title: How to pass arguments to a shell script using `make-process` function? Consider a script file: *~/project/script.sh* ``` echo "arg 1 $1" echo "arg 2 $2" echo "arg 3 $3" ``` And elisp file that invokes it using `make-process`: *~/project/special-mode/special-mode.el* ``` (let* ((script-file (shell-quote-argument (expand-file-name "~/project/script.sh"))) (argA (shell-quote-argument "A")) (argB (shell-quote-argument "B"))) (make-process :name "special-mode" :buffer "*SPECIAL-MODE*" :command `( "sh" "-c" ,script-file ,argA ,argB ) :connection-type 'pipe :sentinel nil))) ``` **Question** The function evaluates but the arguments to the shell script (argA and argB) are never passed. Any idea how to fix this? **Emacs Version** GNU Emacs 28.0.50 # Answer Your issue is the use of `sh -c`. When using the `-c` flag, the next argument is expected to be the full command line that will be expanded by the subshell. You can try this in a regular shell: ``` ditto:~% sh -c echo a b c ditto:~% sh -c 'echo a b c' a b c ditto:~% ``` In the first example, `echo` is being executed correctly, but because only the first argument after `-c` is being passed to the subshell, the `a b c` arguments are lost to `echo`. In the second example, the entire command line is being passed as a single argument, and thus `echo` is seeing `a b c` in the subshell. So naturally, you have to take this into account in your elisp by passing a *single* argument to `-c`: ``` (let* ((script-file (shell-quote-argument (expand-file-name "/bin/echo"))) (arg-a (shell-quote-argument "A")) (arg-b (shell-quote-argument "B"))) (make-process :name "special-mode" :buffer "*SPECIAL-MODE*" :command `("sh" "-c" ,(concat script-file " " arg-a " " arg-b)) :connection-type 'pipe :sentinel nil)) ``` I would recommend, however, that instead of using `sh -c`, just call your binaries directly unless you specifically *need* to use shell interpretatiton, because it works more naturally and has more predictable outcome. > 1 votes # Answer **Update:** As pointed out by xuchunyang, adding a shebang line to the script.sh and calling it like an ordinary executable is a much cleaner solution. That is: ``` #!/bin/bash echo "arg 1 $1" echo "arg 2 $2" echo "arg 3 $3" ``` **Old Solution** Removing the -c flag fixed the issue. The -c flag is used to call shell commands in-line(and probably more). ``` sh -c[-abCefhimnuvx][-o option][+abCefhimnuvx][+o option]command_string [command_name [argument...]] ``` From The Single UNIX ® Specification, Version 2 > ``` > -c Read commands from the command_string operand. Set the value of > special parameter 0 (see Special Parameters ) from the value of > the command_name operand and the positional parameters ($1, $2, > and so on) in sequence from the remaining argument operands. No > commands shall be read from the standard input. > > ``` > 0 votes --- Tags: shell, bash ---
thread-63539
https://emacs.stackexchange.com/questions/63539
Confused by what Paul Graham says about locality in his book "On Lisp"
2021-02-23T09:58:09.067
# Question Title: Confused by what Paul Graham says about locality in his book "On Lisp" https://sep.yimg.com/ty/cdn/paulgraham/onlisp.pdf On page 36 Paul writes the following: > The conditions above do not guarantee the perfect locality you get with purely functional code, though they do improve things somewhat. For example, suppose that f calls g as below: > > ``` > (defun f (x) > (let ((val (g x))) > ; safe to modify val here? > )) > > ``` > > Is it safe for f to nconc something onto val? Not if g is identity: then we would be modifying something originally passed as an argument to f itself. So even in programs which do follow the convention, we may have to look beyond f if we want to modify something there. However, we don’t have to look as far: instead of worrying about the whole program, we now only have to consider the subtree beginning with f. I don't understand what he means by saying that it is not safe for `f` to `nonc` if `g` is *identity*. Or I suppose I don't understand the idea that he's trying to convey in this paragraph in general. # Answer > 3 votes He's talking about side-effects of calling a function (and whether they can be avoided). A purely functional language would not allow a call to `f(x)` to modify the value of the argument being passed to that function; but because `nconc` is *destructive*, that's exactly what would happen here if `g` was the `identity` function (as then `val` would refer to the same cons cell as the argument to `f`). I.e. `val` would not be a value which was local to the function. --- Tags: lisp, localization ---
thread-63541
https://emacs.stackexchange.com/questions/63541
How to use Emacs to prevent screen lock from activating (Windows)
2021-02-23T15:06:33.390
# Question Title: How to use Emacs to prevent screen lock from activating (Windows) My employer has a pretty paranoid screen locking policy on Windows machines. There's no way to override the time settings for the lock. My colleagues an I have been experimenting with various homebrew methods to keep the lock from activating. I'd like to have an Emacs process jiggling the mouse cursor and potentially doing other things to fool the system into thinking there's activity. # Answer > 1 votes I cooked up the following piece of Elisp code. It consists of a lexical closure storing current cursor position and determines inactivity based on periodic comparisons. The closure is launched once every 60 seconds from a scheduler. There are also two commands for enabling and disabling this process. One thing that's missing in this version is that it only looks at the mouse cursor position, so keyboard-only activity is disregarded. I have a vague idea how to incorporate it, based on the keyboard buffer or some such. ``` ;; -*- lexical-binding: t; -*- (defvar *jiggle-max* 2 "dx/dy maximum increment for cursor jiggling") (defvar *jiggle-idle-seconds* 60 "interval between invocations") (defvar *mouse-jiggler* nil "handle for timer cancellation") (defun make-mouse-jiggler () "Perform a small cursor jiggle if inactivity detected. Inactivity is detected based on the cursor position stored in a lexical closure on previous run." (let ((old-pos (mouse-absolute-pixel-position))) (lambda () (let ((pos (mouse-absolute-pixel-position))) ;; If there was no cursor movement since last execution, or if ;; this is the first execution, jiggle the cursor (when (equal pos old-pos) (message "Jiggle...") (destructuring-bind (x . y) pos (let ((x (+ x (- *jiggle-max* (random (* 2 *jiggle-max*))))) (y (+ y (- *jiggle-max* (random (* 2 *jiggle-max*)))))) (set-mouse-absolute-pixel-position x y))) (cl-case system-type ((gnu/linux) (shell-command "setleds -F +num; setleds -F -num" nil)) ((windows-nt) (cl-loop repeat 2 do (shell-command (concat "powershell.exe " "-Command (New-Object -ComObject WScript.Shell)" ".SendKeys('{NUMLOCK}')") nil))) (t (message "OS detected: %s. Don't know how to toggle NumLock")))) (setq old-pos (mouse-absolute-pixel-position)))))) (defun enable-mouse-jiggler () (interactive) (setq *mouse-jiggler* (run-with-timer 0 *jiggle-idle-seconds* (make-mouse-jiggler)))) (defun disable-mouse-jiggler () (interactive) (cancel-timer *mouse-jiggler*)) ``` --- Tags: microsoft-windows, process ---
thread-63538
https://emacs.stackexchange.com/questions/63538
How to set env values for eshell in emacs on macOS?
2021-02-23T04:08:28.130
# Question Title: How to set env values for eshell in emacs on macOS? If use `iTerm` on macOS, we can set env values in its terminal. It also set path such as `/usr/local/bin/` in `~/.bashrc`. But in emacs' terminal as `eshell`, run `kubectl` shown `kubectl: No such file or directory`. It seems that it didn't find the command's path. How to set path for emacs? For example, in `spacemacs`. I found this exec-path-from-shell ``` M-x package-install exec-path-from-shell RET ``` Edit `~/.emacs.d/init.el` to add ``` (when (memq window-system '(mac ns x)) (exec-path-from-shell-initialize)) ``` to the bottom. Copy `PATH` from `.bashrc` to `.profile`. ``` $ cat ~/.profile export PATH=/usr/local/bin:/usr/bin:/bin ``` Start GNU Emacs For Max OS X still can't find the command's path in eshell. The `spacemacs` alert: ``` Warning (initialization): An error occurred while loading ‘/Users/user/.emacs.d/init.el’: Symbol's function definition is void: exec-path-from-shell-initialize 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. ``` The full file of `~/.emacs.d/init.el`: ``` ;;; init.el --- Spacemacs Initialization File -*- no-byte-compile: t -*- ;; ;; Copyright (c) 2012-2020 Sylvain Benner & Contributors ;; ;; Author: Sylvain Benner <sylvain.benner@gmail.com> ;; URL: https://github.com/syl20bnr/spacemacs ;; ;; This file is not part of GNU Emacs. ;; ;;; License: GPLv3 ;; Without this comment emacs25 adds (package-initialize) here ;; (package-initialize) ;; Avoid garbage collection during startup. ;; see `SPC h . dotspacemacs-gc-cons' for more info (defconst emacs-start-time (current-time)) (setq gc-cons-threshold 402653184 gc-cons-percentage 0.6) (load (concat (file-name-directory load-file-name) "core/core-versions.el") nil (not init-file-debug)) (load (concat (file-name-directory load-file-name) "core/core-load-paths.el") nil (not init-file-debug)) (load (concat spacemacs-core-directory "core-dumper.el") nil (not init-file-debug)) ;; Clean compiled files if they become stale or Emacs version has changed. (load (concat spacemacs-core-directory "core-compilation.el") nil (not init-file-debug)) (load spacemacs--last-emacs-version-file t (not init-file-debug)) (let ((default-directory spacemacs-start-directory)) (when (or (not (string= spacemacs--last-emacs-version emacs-version)) (spacemacs//contains-newer-than-byte-compiled-p spacemacs--compiled-files)) (spacemacs//remove-byte-compiled-files spacemacs--compiled-files))) (when (not (string= spacemacs--last-emacs-version emacs-version)) (spacemacs//update-last-emacs-version)) (if (not (version<= spacemacs-emacs-min-version emacs-version)) (error (concat "Your version of Emacs (%s) is too old. " "Spacemacs requires Emacs version %s or above.") emacs-version spacemacs-emacs-min-version) ;; Disable file-name-handlers for a speed boost during init (let ((file-name-handler-alist nil)) (require 'core-spacemacs) (spacemacs/dump-restore-load-path) (configuration-layer/load-lock-file) (spacemacs/init) (configuration-layer/stable-elpa-init) (configuration-layer/load) (spacemacs-buffer/display-startup-note) (spacemacs/setup-startup-hook) (spacemacs/dump-eval-delayed-functions) (when (and dotspacemacs-enable-server (not (spacemacs-is-dumping-p))) (require 'server) (when dotspacemacs-server-socket-dir (setq server-socket-dir dotspacemacs-server-socket-dir)) (unless (server-running-p) (message "Starting a server...") (server-start))))) (when (memq window-system '(mac ns x)) (exec-path-from-shell-initialize)) ``` # Answer The init file `~/.emacs.d/init.el` seems to be at the wrong place. It's better be at the **home folder** which is `~/` Besides, the code to inject the `PATH` contents into emacs seems wrong. So, comment them out and try adding the following into the `~/.emacs` which is the most conventional init file for emacs and change `~/.bash_profile` to whatever you use as the bash init file (in your case it seems to be `/.bashrc`) and then of course restart the emacs. ``` (let ((path (shell-command-to-string ". ~/.bash_profile; echo -n $PATH"))) ;; the dot . makes it execute the ~/bash_profile ;; echo -n $PATH prints out the PATH contents (setenv "PATH" path) (setq exec-path (append (split-string-and-unquote path ":") exec-path))) ``` Furthermore, first try it with the `M-x shell` not the `eshell` because `eshell` is an extra feature not essential. > 1 votes --- Tags: osx, terminal-emacs, eshell, environment, path ---
thread-62568
https://emacs.stackexchange.com/questions/62568
Opening a file from a new/different Projectile project in the same workspace in Doom Emacs
2021-01-02T22:32:20.110
# Question Title: Opening a file from a new/different Projectile project in the same workspace in Doom Emacs If I'm working on one project and I switch over to a buffer from another the default behavior of Doom Emacs seems to be to open the new buffer in a new workspace (when workspaces are enabled). I want the default behavior to be to open it in the current workspace, but I don't want to disable workspace functionality in general. Is there a good way to do this? After more research this seems to be an interaction between persp-mode and projectile. # Answer > 2 votes There is a variable called +workspaces-on-switch-project-behavior. Its documentation states ``` Controls the behavior of workspaces when switching to a new project. Can be one of the following: t Always create a new workspace for the project 'non-empty Only create a new workspace if the current one already has buffers associated with it. nil Never create a new workspace on project switch. ``` Setting it to nil gives me the desired behavior, which is that a new workspace is not created when switching projects. --- Tags: projectile, doom, persp-mode ---
thread-63536
https://emacs.stackexchange.com/questions/63536
where are org-mode issues tracked?
2021-02-22T20:52:46.430
# Question Title: where are org-mode issues tracked? Where are org-mode issues tracked? What I mean, why I ask: I'm having a problem with arbitrary text immediately preceding inline markup, which is the best way I can find to express the general problem underlying e.se.com posts like this and this and this. It's a problem I've previously encountered in reST. However, * reST has (IMHO) a reasonable, general, and clean solution for the general problem * IMHO the several workarounds I've seen offered for this problem in org-mode (see comments to the above questions) are either kludges or don't WFM. (YMMV, and note I'm not here to argue this point--it's just part of the motivation for *this* question.) At least one of the comments to the above questions suggested that this might/should be a bug on org-mode, so I thought I'd check. Assuming that Org would track their issues in the same UI with their repository (welcome to the 21st century `?-)` I searched for their repos, which are here, and particularly found the org-mode code repo here. It's a Gogs instance, and looks like a "normal" `git` front-end (e.g., bitbucket, github, gitlab) but ... no bugtracker? I did some more websearching and I got nothing. So apologies if * my websearch was incompetent. I searched but did not find, and am not posting this to LMGTFY. * this question should be asked in another SE. Given that org-mode is such a major part of Emacs, I guessed this would be the place to post, but ICBW. ... but I'd like to know, how to view org-mode issues? E.g., in order to see if a bug or feature has already been proposed? # Answer *\[Note: following still "under construction" and active investigation.\]* **summary:** ~~It's a mess.~~ Org-mode issue management seems to have "grown organically." **details:** Thanks to commenters to my question, and going down their rabbitholes, I *might* understand--*maybe*-- how org-mode issues are currently tracked. **TODO: ontological problems:** issue vs bug, help request vs (non-existent) 'feature request', 'update' as everything (bugs, help requests, patches, releases), etc. **TODO:** post the org-mode list about adding an `Issues` link to the currently-existing org-mode repo. # to propose a bug (aka, make a bug report) There are at least 4 ways to do this, all involving email at least indirectly. One can 1. From within any Emacs buffer, do `M-x org-submit-bug-report`. This launches a new buffer to gather information to send to the Org mailing list (aka *org-ML*) @ **emacs-orgmode@gnu.org**. 2. One can send an email directly to the org-ML. If you wish to do this, please * provide useful feedback as described here * format and add helpful metadata as described here 3. From within any Emacs buffer, do `M-x report-emacs-bug`. This launches a new buffer to gather information to send to the mailing list for Emacs bugs (aka *b.g.e-ML*) @ **bug-gnu-emacs@gnu.org**. Which of course means that one can also ... 4. ... send an email directly to b.g.e-ML. Before doing that, please # to request a feature (aka, make an FR) Unfortunately, AFAICS the org-mode tracking system (aka *OMTS*) ontology seems to lack this type. It *does* have a type=*help request*, which seems like a superset (FRs plus requests for assistance), or Something Completely Different. (**TODO:** investigate.) Given that "requesting help" is discussed here, you probably (and I really am guessing here!) *don't* want to use b.g.e-ML; instead do one of 1. `M-x org-submit-bug-report` (see previous section) 2. Send email directly to org-ML (see previous section) Either way, be sure to include the metadata discussed here. # to check status of a bug current issues (which means "new"? as in not "old"?) feed: https://feed2js.org//feed2js.php?src=https%3A%2F%2Fupdates.orgmode.org%2Ffeed%2Fbugs&chan=y&num=10&utf=y&html=y `RSS feed for new bugs`: https://updates.orgmode.org/feed/bugs **TODO:** determine difference (if any) between "current issue" and "new bug" `confirmed bugs` logged here old (but still open) issues: see https://orgmode.org/worg/org-issues.html#org43c43fd (**TODO:** needs stable/mnemonic anchor) org bugs via Emacs for completeness: check ML archives (b.g.e-ML and org-ML) # to check status of an FR 1st, note again the lack (IIRC) of a separate FR type. "help request" gets logged here for completeness: check ML archives (b.g.e and org) > 3 votes --- Tags: org-mode ---
thread-63533
https://emacs.stackexchange.com/questions/63533
Exit Emacs Calendar without having to save the diary file
2021-02-22T15:05:59.250
# Question Title: Exit Emacs Calendar without having to save the diary file When I create appointments in Emacs `diary` via the `calendar`, I have to save changes to the diary file before being able to exit the calendar. I have tried to set up Emacs to automatically save the diary file once changes have been made with this code: ``` (add-hook 'diary-mode-hook (lambda () (add-hook 'auto-save-hook 'diary-show-all-entries nil t) (auto-save-mode))) ``` However, hitting `q` in calendar still prompts me with these words: ``` Diary modified; do you really want to exit the calendar? (y or n) ``` This from calendar.el: ``` (defun calendar-exit (&optional kill) "Get out of the calendar window and hide it and related buffers." (interactive "P") (let ((diary-buffer (get-file-buffer diary-file)) (calendar-buffers (calendar-buffer-list))) (when (or (not diary-buffer) (not (buffer-modified-p diary-buffer)) (yes-or-no-p "Diary modified; do you really want to exit the calendar? ")) (if (and calendar-setup (display-multi-frame-p)) ;; FIXME: replace this cruft with the `quit-restore' window property (dolist (w (window-list-1 nil nil t)) (if (and (memq (window-buffer w) calendar-buffers) (window-dedicated-p w)) (if (eq (window-deletable-p w) 'frame) (if calendar-remove-frame-by-deleting (delete-frame (window-frame w)) (iconify-frame (window-frame w))) (quit-window kill w)))) (dolist (b calendar-buffers) (quit-windows-on b kill)))))) ``` I would like to be able to save the diary file automatically and exit calendar without confirmation. # Answer > 1 votes Here's a (lightly tested) implementation along the lines in the comments: ``` (defun my/save-diary-before-calendar-exit (_) (let ((diary-buffer (get-file-buffer diary-file))) (or (not diary-buffer) (not (buffer-modified-p diary-buffer)) (with-current-buffer diary-buffer (save-buffer))))) (advice-add 'calendar-exit :before #'my/save-diary-before-calendar-exit) ``` The tests are cribbed from `calendar-exit` itself: get the buffer of the diary file and if the buffer exists and is modified, save it. If you want to make this permanent, you need to add the code above to your init file. And if at any point you want to remove the advice, say: ``` (advice-remove 'calendar-exit #'my/save-diary-before-calendar-exit) ``` --- Tags: calendar, diary ---
thread-63553
https://emacs.stackexchange.com/questions/63553
Search and replace with many possible replacements?
2021-02-24T01:38:44.503
# Question Title: Search and replace with many possible replacements? Suppose I have a code base with many instances of string "`console.log(`" for example. I want to replace each one with one of the following six lines: ``` logger(FATAL, logger(ERROR, logger(WARNING, logger(INFO, logger(LOG, logger(DEBUG, ``` Each replacement is different and depends on the context in which the search string occurs (in a way that can only be judged by a human). So I want to do a search and replace, but instead of only typing "y" or "n", I want to type for example 1, 2, 3, 4, 5 and 6 (and the number I type determines which one of the set is used as the replacement for that instance). I prefer to do this in **one** pass, and I also want to avoid typing any of the replacement strings (in full) more than once as suggested here, Query replace with different replacements since the replacements will not occur consecutively but randomly. In a typical large code base there could be hundreds of changes between consecutive instances, and this will require typing the replacement strings too many times. **Attempted solution sketch (does not work):** Use search-and-replace but with a macro replacement, and the macro replacement itself invokes a little function to ask me what the replacement should be. For example something similar to this: ``` (defun prompt-me-for-replacement (response) (interactive (list (read-key "Choice [1-6]: "))) ; or this --> (interactive "cChoice [1-6]: ") (cond ((equal response 1) "logger(FATAL, ") ((equal response 2) "logger(ERROR, ") ((equal response 3) "logger(WARN, ") ((equal response 4) "logger(INFO, ") ((equal response 5) "logger(LOG, ") ((equal response 6) "logger(DEBUG, ") (t (prompt-me-for-replacement)))) ``` Then I want to invoke it with `query-replace-regexp` (or a similar function) and when I am prompted for the replacement string, I say `\,(prompt-me-for-replacement)`. This does not work, firstly because the function prompt-me-for-replacement will not even run once directly from the minibuffer. Secondly I don't know if an interactive form can be called from the middle of a search and replace operation like I'm trying to do, because it is one interactive operation in the middle of another interactive one. Any pointers/ideas will be greatly appreciated!!! # Answer > 1 votes How about this? ``` (defun my-query-replace-console-log () "Replace instances of console.log( from a menu of options." (interactive) (let ((prompt "1:fatal, 2:error, 3:warning, 4:info, 5:log, 6:debug ? ") (replacements '((?1 . "logger(FATAL,") (?2 . "logger(ERROR,") (?3 . "logger(WARNING,") (?4 . "logger(INFO,") (?5 . "logger(LOG,") (?6 . "logger(DEBUG,")))) (while (search-forward "console.log(" nil t) (when-let ((string (alist-get (read-char prompt) replacements))) (replace-match string))))) ``` Any key other than 1-6 will skip to the next match. --- Tags: query-replace-regexp ---
thread-51648
https://emacs.stackexchange.com/questions/51648
How to detect the number of lines scrolled from scroll up/down?
2019-07-16T06:51:34.017
# Question Title: How to detect the number of lines scrolled from scroll up/down? When running `scroll-up` or `scroll-down`, it's possible emacs isn't scrolling the number of lines requested (if you hit the start/end of the buffer for eg). Is there a convenient way to know how many lines were actually scrolled? # Answer > 0 votes Here's an attempt: ``` (defvar jpk/scroll-count 0 "Signed number of lines scrolled in the last scroll-up or scroll-down.") (make-variable-buffer-local 'jpk/scroll-count) (defun jpk/scroll-tracking (orig &rest args) (let ((start (window-start)) (error t)) (unwind-protect (prog1 (apply orig args) (setq error nil)) (when error (setq jpk/scroll-count 0))) (setq jpk/scroll-count (* (signum (- (window-start) start)) (count-lines (window-start) start))))) (advice-add 'scroll-up :around #'jpk/scroll-tracking) (advice-add 'scroll-down :around #'jpk/scroll-tracking) ``` I used `count-lines` because `line-number-at-pos` can be slow. But `count-lines` implicitly takes the absolute value, hence the `signum`. Also I'm not sure I got the error handling exactly right. # Answer > 0 votes ``` (setq max-lines (- (window-height) next-screen-context-lines)) (if (< (lines-before) max-lines) 0 max-lines) (if (< (lines-after) max-lines) 0 max-lines) (defun lines-before () "Report number of lines on current page, and how many are before or after point." (interactive) (save-excursion (let ( (opoint (point)) beg end total before after) (forward-page) (beginning-of-line) (or (looking-at page-delimiter) (end-of-line)) (setq end (point)) (backward-page) (setq beg (point)) (count-lines beg opoint)))) (defun lines-after () "Report number of lines on current page, and how many are before or after point." (interactive) (save-excursion (let ( (opoint (point)) beg end total before after) (forward-page) (beginning-of-line) (or (looking-at page-delimiter) (end-of-line)) (setq end (point)) (backward-page) (setq beg (point)) (count-lines opoint end)))) ``` I took the code from `count-lines-page` and turned it into two functions that outputs how many lines exist above and below the position at point. Then, it's just a matter of finding out if the scroll will take place. In the above case, I'm finding out how many lines will be scrolled if I hit `scroll-down-command` or `scroll-up-command`. Not sure if this helps. I'm a newbie in Elisp. # Answer > 0 votes I use a thing like this ``` (defun jump-length-test (window _window-start-after) (with-selected-window window (unless (> 0.001 (float-time (time-subtract (current-time) buffer-display-time))) ; Don't run this function after a change of buffer. (let* ((bottom-line-before (line-number-at-pos (window-end))) (bottom-line-after (line-number-at-pos (window-end nil 'update))) ; NB: ‘window-start’ doesn't take the ‘update’ argument. (vertical-displacement (- bottom-line-after bottom-line-before))) (message "Lines scrolled: %s" (abs vertical-displacement)))))) (add-hook 'window-scroll-functions #'jump-length-test) ``` It checks if the difference between the `current-time` and the `buffer-display-time` is under 0.001 s to avoid running when you change the buffer displayed by the window (which also triggers `window-scroll-functions`), and then it compares the line number of the bottom lines before and after the jump to get its length. --- Tags: scroll ---
thread-46988
https://emacs.stackexchange.com/questions/46988
Why do easy templates, .e.g, "< s TAB" in org 9.2 not work?
2019-01-08T22:01:42.110
# Question Title: Why do easy templates, .e.g, "< s TAB" in org 9.2 not work? Easy templates in Org 9.2 are not working for me on `GNU Emacs 26.1 (build 1, x86_64-w64-mingw32) of 2018-05-30`. I have changed my `elpa/` directory to `smelpa/`. I load `emacs -q` and switch to the `*scratch*` buffer and toggle `M-x org-mode`. A call to `org-version` returns ``` Org mode version 9.1.9 (release_9.1.9-65-g5e4542 @ c:/Program Files/emacs-26.1-x86_64/share/emacs/26.1/lisp/org/) ``` When I type `<s` `TAB`, the easy template expands as expected. ``` <s|<-----<press TAB here> #+BEGIN_SRC #+END_SRC ``` Now, to upgrade to Org 9.2, I do `list-packages` and install `org`. (For some reason `package-install` doesn't return `org`). Returning to the `*scratch*` buffer, running `org-version` returns ``` Org mode version 9.2 (9.2-elpa @ c:/Users/%USERNAME%/.emacs.d/elpa/org-9.2/) ``` It seems like Org 9.2 installed correctly. The same is true if I just directly install Org 9.2 and create a new `org` buffer (i.e. don't load the default `org` first). Easy templates won't work in Org 9.2. I looked around for a bug tracker, but I don't see anything on the official repo. * Did I install Org 9.2 correctly? * Is there perhaps some compiled file lingering somewhere from a bad install? * If this is a bug, how do I submit it? With `report-emacs-bug`? --- # Update To address the side questions: ## Did I install Org 9.2 correctly? Yes. Installing `org` via `list-packages` will "override" the default version. This can be seen by running `org-version`. Note that it may be necessary to restart Emacs (or the Emacs server). ## If this is a bug, how do I submit it? With report-emacs-bug? According to the org-mode homepage (at the bottom), use `M-x org-submit-bug-report`. Make sure you Ask Questions the Smart Way so as not to spam the developers! This would include checking the release notes of the new version! # Answer They changed the template system in orgmode 9.2. The new mechanism is called *structured template*. The command `org-insert-structure-template` bound to `C-c C-,` gives you a list of `#+begin_`-`#+end_` pairs that narrows down while you type and you can use completion. But, you can also get the old *easy template* system back, either * by adding `(require 'org-tempo)` to your init file or * by adding `org-tempo` to the list `org-modules`. You can do that by customizing `org-modules`. <sup>Note that the answer is mostly a citation of two answers in the corresponding reddit article.</sup> > 62 votes # Answer Others have stated that it's `C-c C-,` now to insert templates. One cool thing is that you can paste some code, then visual-select it and do `C-c C-, s` and it will wrap your selection inside `#+begin_src` and `#+end_src`. Before, when it was `<s TAB`, I had made a function to do that but now, I can do it with the native command. All I have to do is forget about `<s TAB`. Edit: I installed yasnippet and yasnippet-snippets recently and it adds the completions with \<s, \<q etc. ``` (use-package yasnippet-snippets :ensure t) (use-package yasnippet :ensure t :config (yas-global-mode 1)) ``` I am however glad that I lost those \<s completions since it lead me to discover `C-c C-,` which is useful with a visual selection. > 8 votes # Answer As described by Tobias, I had to `(require 'org-tempo)` in `.emacs`. Additionally, I had to remove any customization to `org-structure-template-alist` or revert it to standard. Then, `C-c C-,` triggers Org-Select menu for structure feature selection and `<s` triggers the usual src block directly. For org-version 9.3.7, emacs 26.3 > 4 votes # Answer You can get completion back by adding `org-tempo` to `org-modules` like so ``` (add-to-list 'org-modules 'org-tempo t) ``` You will need to restart emacs so when orgmode is loaded it will load `org-tempo` as well. Credit to agzam > 2 votes # Answer you can use menu bar `Org => Customize => Browse Org Group` to add > 1 votes --- Tags: org-mode, template ---
thread-44664
https://emacs.stackexchange.com/questions/44664
Apply ANSI color escape sequences for Org Babel results
2018-09-11T12:02:17.087
# Question Title: Apply ANSI color escape sequences for Org Babel results ## Feature There is a nice built-in Emacs feature to colorize strings with ANSI color escape sequences. So evaluating the following Elisp code, will insert the "Test text" at the `point` with proper colors. ``` (require 'ansi-color) (insert (ansi-color-apply "^[[33mTest text^[[0m")) ``` ## Problem I tried to use the `ansi-color-apply` function to colorize the results of my Org Babel code blocks using `:post` with the following filter block. ``` #+name:ansi-colorize #+begin_src emacs-lisp :var input="[33mTest text[0m" :results raw (ansi-color-apply input) #+end_src #+RESULTS: ansi-colorize Test text ``` Which only removes the color escape sequences, but the inserted text has no proper face attributes.: ## Notes: Since `ansi-color-apply` is a pure function, therefore does its job right and returns with: ``` #("Test text" 0 9 (font-lock-face (foreground-color . "#E6DB74"))) ``` Which does not have the expected effect when the result is inserted by Org Babel # Answer If I understand you question correctly you wish to interpret ansi color codes in the results of org babel code blocks. I achieved this by adding a hook to `org-babel-after-execute-hook`: ``` (defun ek/babel-ansi () (when-let ((beg (org-babel-where-is-src-block-result nil nil))) (save-excursion (goto-char beg) (when (looking-at org-babel-result-regexp) (let ((end (org-babel-result-end)) (ansi-color-context-region nil)) (ansi-color-apply-on-region beg end)))))) (add-hook 'org-babel-after-execute-hook 'ek/babel-ansi) ``` Now when I execute for example this code block ``` #+BEGIN_SRC shell echo -e "\e[31mTest\e[0m" #+END_SRC ``` I get nice red text in the result: > 9 votes --- Tags: org-mode, org-babel, font-lock ---
thread-63563
https://emacs.stackexchange.com/questions/63563
Binding option + arrow keys/backspace on Mac OS while still being able to enter special characters
2021-02-24T12:30:57.920
# Question Title: Binding option + arrow keys/backspace on Mac OS while still being able to enter special characters I want to be able to bind ⌥← to move the cursor to the previous word, ⌥→ to the next word, ⌥↓ to scroll down a page etc. in Emacs on Mac OS, as in native text editing controls, but also still be able to enter special characters using the option key. When I bind `mac-option-modifier` or `ns-alternate-modifier` to `'alt`, I can bind things like I want, but no longer enter special characters; when I bind it to `'none`, I can enter special characters but can’t use it for my key bindings. # Answer Emacs supports binding the Mac modifier keys to different internal keys depending on what kind of key event they’re used to trigger: > The value of each variable is either a symbol, describing the key for any purpose, or a list of the form (:ordinary symbol :function symbol :mouse symbol), which describes the modifier when used with ordinary keys, function keys (that do not produce a character, such as arrow keys), and mouse clicks. So you can use this to allow `A-` as the binding prefix for the option key when used in combination with ‘function keys’ (including arrow keys and backspace), but leave it set to `'none` for all other combinations, which enables typing special characters as usual: ``` (setq ns-alternate-modifier '(:ordinary none :function alt :mouse alt)) ``` The specific key bindings to emulate native Mac OS text controls are: ``` ;; note that scroll-up and scroll-down are reversed in Emacs compared to most apps (global-set-key (kbd "A-<up>") 'scroll-down-command) (global-set-key (kbd "A-<down>") 'scroll-up-command) (global-set-key (kbd "A-<left>") 'backward-word) (global-set-key (kbd "A-<right>") 'forward-word) (global-set-key (kbd "A-<backspace>") 'backward-kill-word) ;; the following key bindings emulate the native command key scrolling and text editing shortcuts (global-set-key (kbd "s-<up>") 'beginning-of-buffer) (global-set-key (kbd "s-<down>") 'end-of-buffer) (global-set-key (kbd "s-<left>") 'move-beginning-of-line) (global-set-key (kbd "s-<right>") 'move-end-of-line) (global-set-key (kbd "s-<backspace>") (lambda () (interactive) (kill-line 0))) ``` > 1 votes --- Tags: key-bindings, osx, cursor, modifier-key ---
thread-63558
https://emacs.stackexchange.com/questions/63558
How to distinguish a scroll from a change of buffer in a function called from ‘window-scroll-functions’?
2021-02-24T09:34:44.500
# Question Title: How to distinguish a scroll from a change of buffer in a function called from ‘window-scroll-functions’? I've written a function that recenters the point each time it makes a long jump and I added it to the hook `window-scroll-functions`. The length of the jump is determined by comparing the return value of `(line-number-at-pos (window-end))` to that of `(line-number-at-pos (window-end nil 'update))`, where the former holds the line number at the `window-end` position before the jump, and the latter after the jump. The problem is that `window-scroll-functions` runs also when I change the buffer displayed by the current window. In that case `(line-number-at-pos (window-end))` returns the line number at the `window-end` position *of the previous buffer*, and I can't figure out which one it was because (ref.): > At the time of the call, the display-start position of the argument window is already set to its new value, and the buffer to be displayed in the window is set as the current buffer. If the `window-end` of the previous buffer and the new one differ enough, my recentering function gets called even though it shouldn't. How can I find out whether it was a buffer change that triggered `window-scroll-functions`? # Answer > 0 votes One way to do it is by comparing the `current-time` with the `buffer-display-time`. If the gap is small enough it means it was most likely a buffer change that ran the hook. ``` (defun my-test-scroll-or-buffer-change (window _window-start-after) (with-selected-window window (if (> 0.001 (float-time (time-subtract (current-time) buffer-display-time))) (message "It was a buffer change") (message "it was a scroll")))) (add-hook 'window-scroll-functions #'my-test-scroll-or-buffer-change) ``` Not very pretty but it seems to work. --- Tags: buffers, window, hooks, scrolling ---
thread-53152
https://emacs.stackexchange.com/questions/53152
What exactly is the difference between `font-family` and `font-foundry`?
2019-10-14T22:38:54.320
# Question Title: What exactly is the difference between `font-family` and `font-foundry`? What is the historical context of these two terms? Why are they distinct? And why are they needed? What pragmatic utility is there in knowing how these two terms differ? In terms of Emacs/Emacs Lisp, where are they used/how are they used/why are they used? (A solid example would be nice). I am confused because I see no correlation anywhere in any modern-day files/GUI as to why I should know the differences between the meanings of *font foundry* and *font family*. But they seem so vital to know when dealing with fonts. # Answer > 2 votes A Font Foundry, more correctly a Type Foundry is the font manufacturer. Think Adobe, Bitstream, Monotype, etc. A Font Family is a collection of fonts under one name. Think Helvetica, Courier, Times New Roman. etc. A Font would be “Adobe’s Helvetica, semi-condensed bold italic in 12 point”. This definition comes from movable type. The evolution of electronic publishing and type, in addition to the evolution of GUI interfaces has blurred these definitions. Casual users don’t care about these aging nuances. The font is Helvetica and the size is the system default. Maybe you bump it up if you’re trying to stretch the length of your paper. Users in publishing or design might care more, especially if they paid for a font. # Answer > 1 votes As a practical answer to Part 2 of your question: ``` $ fc-list -f "%{fullname} : %{foundry} : %{family}\n" | grep Ubuntu ``` produces: ``` Ubuntu Medium : DAMA : Ubuntu,Ubuntu Light Ubuntu Mono Bold : DAMA : Ubuntu Mono Ubuntu Bold Italic : DAMA : Ubuntu Ubuntu Light : DAMA : Ubuntu,Ubuntu Light Ubuntu Condensed : DAMA : Ubuntu Condensed Ubuntu Medium Italic : DAMA : Ubuntu,Ubuntu Light Ubuntu Mono Bold Italic : DAMA : Ubuntu Mono Ubuntu Mono : DAMA : Ubuntu Mono Ubuntu Mono Italic : DAMA : Ubuntu Mono Ubuntu Thin : DAMA : Ubuntu,Ubuntu Thin Ubuntu Bold : DAMA : Ubuntu Ubuntu Light Italic : DAMA : Ubuntu,Ubuntu Light Ubuntu : DAMA : Ubuntu Ubuntu Italic : DAMA : Ubuntu ``` So e.g. you can then do this to use Ubuntu Mono Italic for a given face: ``` (custom-set-faces ;;; ... '(org-block-begin-line ((t (:inherit default :background "#3c3836" :foreground "aquamarine" :slant italic :height 0.5 :foundry "DAMA" :family "Ubuntu Mono")))) ;;; ... ) ``` --- Tags: fonts ---
thread-63344
https://emacs.stackexchange.com/questions/63344
Italics not shown in block quotes in orgmode
2021-02-12T10:21:47.187
# Question Title: Italics not shown in block quotes in orgmode In my blockquotes in org-mode, the fontification does not pick up on italics. I have looked at this question and answer that says it was fixed several years ago, but my issue persists. I have tried using `describe-face` to find the issue but it does not seem to contain any modifications that should affect or hide italics: ``` Face: org-quote (sample) (customize this face) Documentation: Face for #+BEGIN_QUOTE ... #+END_QUOTE blocks. Defined in ‘org-faces.el’. Family: unspecified Foundry: unspecified Width: unspecified Height: unspecified Weight: normal Slant: unspecified Foreground: #181818 DistantForeground: unspecified Background: grey95 Underline: unspecified Overline: unspecified Strike-through: unspecified Box: unspecified Inverse: unspecified Stipple: unspecified Font: unspecified Fontset: unspecified Extend: unspecified Inherit: unspecified ``` Italics show fine in other text. Here is an example showing the same text italicized, inside and outside a block quote: `C-u C-x =` on italicized text gives this: ``` position: 488528 of 488671 (100%), column: 30 character: n (displayed as n) (codepoint 110, #o156, #x6e) charset: ascii (ASCII (ISO646 IRV)) code point in charset: 0x6E script: latin syntax: w which means: word category: .:Base, L:Left-to-right (strong), a:ASCII, l:Latin, r:Roman to input: type "C-x 8 RET 6e" or "C-x 8 RET LATIN SMALL LETTER N" buffer code: #x6E file code: #x6E (encoded by coding system utf-8-unix) display: by this font (glyph code) mac-ct:-*-Libre Baskerville-normal-normal-normal-*-13-*-*-*-p-0-iso10646-1 (#x04) Character code properties: customize what to show name: LATIN SMALL LETTER N general-category: Ll (Letter, Lowercase) decomposition: (110) ('n') There are text properties here: face org-quote font-lock-fontified t font-lock-multiline t fontified t line-prefix [Show] org-emphasis t wrap-prefix [Show] ``` # Answer \[The answer version of my comment on the question.\] Check the value of `org-fontify-quote-and-verse-block`, which is nil by default, meaning those blocks should be fontified like regular org. > 2 votes --- Tags: org-mode, fonts, faces ---
thread-63557
https://emacs.stackexchange.com/questions/63557
How to make image-dired work on remote files?
2021-02-24T08:47:48.850
# Question Title: How to make image-dired work on remote files? I've tried `ssh`and `scp` for tramp's method (both work for tramp), yet image-dired thumbnail creation fails ``` Thumb could not be created for /scp:raspi:/media/pi/91D4-7E58//IMG_1.JPG: exited abnormally with code 1 ``` Do I need to setup filesharing e.g. `nfs` or is there something else I could try before? Both, tramp and image-dired work fine on local files # Answer > 3 votes `image-dired` uses `start-process` and `call-process`. This means, it cannot handle remote files. If you want support for remote files, you might write an Emacs bug report. --- Tags: dired, tramp, image-dired ---
thread-63560
https://emacs.stackexchange.com/questions/63560
Org-mode: disable abbrev-mode in source blocks
2021-02-24T10:37:04.623
# Question Title: Org-mode: disable abbrev-mode in source blocks I use org-mode to write an executable paper, combining text and code. I make use of abbrev-mode to insert text more efficiently (e.g. type 'bc' to insert 'because') and to correct spelling errors. Is there any way to switch off abbrev-mode in the source blocks to prevent it expanding my variables? I did run into this post, but don't see how to use that for my problem. Any help would be appreciated. # Answer > 3 votes One way might be like this, where expansion only occurs conditionally. Put this statement in an init file, or in an org-mode hook function and you should not get expansion in src-blocks. ``` (setq abbrev-expand-function (lambda () (unless (org-in-src-block-p) (abbrev--default-expand)))) ``` --- Tags: org-mode, org-babel, abbrev ---
thread-63551
https://emacs.stackexchange.com/questions/63551
I am writing Fortran code in emacs but the tab key behaviour changes in F90 mode. Can I change it back?
2021-02-23T23:37:55.237
# Question Title: I am writing Fortran code in emacs but the tab key behaviour changes in F90 mode. Can I change it back? On loading a f90 file, emacs changes to F90 mode, which changes some emacs behaviours. When I press `<tab>` emacs inserts two spaces at the left margin. Now when I use the backspace key it deletes those two spaces one at a time. Is there a modification I can make which will allow me to delete tabs with a single keystroke in F90 mode? # Answer Yes, what you want is a "hungry" or "greedy" delete/backspace. `f90-mode` doesn't come with such a thing, but `cc-mode` does. It includes two inter-related families of functions `c-electric-delete*` and `c-hungry-delete-*`. Specifically take a look at `c-hungry-delete-backwards` via Emacs's built in function help (`C-h f c-hungry-delete-backwards`). From there you can view its implementation; it's relatively small, and will give you a good start at implementing your own "hungry delete". Edit: Someone's done the work for you, see https://github.com/nflath/hungry-delete Edit: a naive function to delete two spaces could look something like this. In your `~/.emacs.d/init.el` you would add: ``` ;; define a toy function to delete two spaces at once ;; if the preceding two characters are indeed spaces (defun nega/two-space-delete () (interactive) (if (and (eq ?\ (char-before)) (eq ?\ (char-before (- (point) 1)))) (delete-backward-char 2) (delete-backward-char 1))) ;; after f90-mode is loaded, remap instances of (delete-backward-char) to ;; instead use our previously defined toy function (eval-after-load 'f90-mode '(define-key f90-mode-map [remap delete-backward-char] #'nega/two-space-delete)) ``` In your comment you stated > An elisp function which knows the tab-size in spaces and deletes the same number of spaces would solve the problem This would be the idea solution, but that's not how `f90-mode` works. Unlike many other modes, it has more than one `indent level`. In fact it has seven. * `f90-do-indent` -- Extra indentation within do blocks (default 3). * `f90-if-indent` -- Extra indentation within if/select/where/forall blocks (default 3). * `f90-type-indent` -- Extra indentation within type/enum/interface/block-data blocks (default 3). * `f90-program-indent` -- Extra indentation within program/module/subroutine/function blocks (default 2). * `f90-associate-indent` -- Extra indentation within associate blocks (default 2). * `f90-critical-indent` -- Extra indentation within critical/block blocks (default 2). * `f90-continuation-indent` -- Extra indentation applied to continuation lines (default 5). This complicates writing a comprehensive function that "deletes backwards one indentation level". A "greedy backwards delete" that deletes whitespace back to the beginning of the line, followed by a stroke of the `TAB` key to set you at the correct indent level would serve you well. > 3 votes --- Tags: indentation, tabs, fortran, backspace ---
thread-36857
https://emacs.stackexchange.com/questions/36857
How can I show the full path to the current file in the mode-line for Spacemacs (Spaceline)?
2017-11-13T19:41:05.413
# Question Title: How can I show the full path to the current file in the mode-line for Spacemacs (Spaceline)? I'd like to display the full path instead of just the filename itself. How can this be done? So essentially where it says `.spacemacs` in the below image (seems this mode-line is called "Spaceline"): # Answer > 3 votes Add this to your `dotspacemacs/user-config` function: ``` (spaceline-define-segment buffer-id (if (buffer-file-name) (abbreviate-file-name (buffer-file-name)) (powerline-buffer-id))) ``` # Answer > 0 votes ``` (setq-default mode-line-buffer-identification (list 'buffer-file-name (propertized-buffer-identification "%12f") (propertized-buffer-identification "%12b"))) ``` --- Tags: spacemacs, mode-line, spaceline ---
thread-33388
https://emacs.stackexchange.com/questions/33388
Show the full path to the file
2017-06-08T08:55:23.393
# Question Title: Show the full path to the file Windows 10, Emacs 25.1. Suppose I open file **D:/temp/test/myfile.txt**. But in the in the mode line show only file name (**myfile.txt**). But I need to show FULL path to file: **D:/temp/test/myfile.txt** This path can show on mode line OR in the frame title. How I can do this? # Answer > 7 votes The variable `buffer-file-name` contains an absolute path of the file you are visiting. To use in frame title: ``` (setq frame-title-format '("" invocation-name ": " (:eval (if buffer-file-name (abbreviate-file-name buffer-file-name) "%b")))) ``` To use it in the mode-line you can do the same, but for `mode-line-format` variable. If you need more help see `C-h v mode-line-format` You can also use `%f`, like `(setq-default frame-title-format "%b (%f)")` For a more thorough explanation see here and here # Answer > 1 votes To show the current file path in the minibuffer you can do this: ``` (setq-default mode-line-buffer-identification (list 'buffer-file-name (propertized-buffer-identification "%12f") (propertized-buffer-identification "%12b"))) ``` # Answer > 0 votes Did as follows: Began installing `xdotool` package via `apt install xdotool`. Then ran it via `xdotool getactivewindow getwindowgeometry` to get desired destination position, which gave me following output: ``` Window 69206023 Position: 2201,251 (screen: 0) Geometry: 774x568 ``` Entered it in a script, as: ``` #!/bin/bash xdotool getactivewindow windowmove 2201 251 windowsize 774 568 ``` Finally copied into `/usr/bin/moveright` and binded it on desired keystroke. --- Tags: mode-line ---
thread-63585
https://emacs.stackexchange.com/questions/63585
String-match: symbols variable void
2021-02-24T22:14:23.320
# Question Title: String-match: symbols variable void I am trying to write a small function where I extract two sub-strings from a cite-key, e.g. `cite:rammstein2017paris`. ``` (defun citekey-get-author-and-year () "Get the _author_ and _YEAR_ from a cite:authorYEARtitle key." (interactive) ; allow this to be user-callable (let ((regexp ":\(.*\)\([0-9]*\)[a-z]") ; the regex to parse author year (citekey (buffer-substring (line-beginning-position) (line-end-position))))) (when (string-match 'regexp 'citekey) (setq author (match-string 1 string) year (match-string 2 string))) ) ``` The above code gives me a "Wrong type argument: stringp, regexp" error. I came up with it after reading the manual. If I do it without the `'regexp 'citekey` line, I get the error "Symbols value as a variable is void: regexp". Based on the error description, the function doesn't know what regexp and citekey are, but why? --- I tried debugging it with `debug-on-entry`, as described here. Unfortunately I did not really see or understand where the error is. My code is inspired by the `string-match` documentation, and it confuses me very much that it doesn't work. ``` Demos #+BEGIN_SRC elisp (let ((string "Today is <2018-11-07>.")) (when (string-match "<\\([-0-9]+\\)>" string) (match-string 1 string))) #+END_SRC ``` When searching online for the error code, there are a bunch of results, but as the error seems very generic I didn't find anything that solved my problem. --- I believe that the mistake is really basic and obvious, it is just that my understanding of elisp is lacking, as this is the first function I write. # Answer > 1 votes Here's the corrected incantation: ``` (defun my-citekey-get-author-and-year () "Get the AUTHOR and YEAR from a cite:AUTHORYEARtitle key." (interactive) ; allow this to be user-callable (let ((regexp ":\\(.*\\)\\([0-9]*\\)[a-z]") ; the regex to parse (citekey (buffer-substring (line-beginning-position) (line-end-position))) author year) (when (string-match regexp citekey) (setq author (match-string 1 citekey) year (match-string 2 citekey))))) ``` Note the fixed parentheses around `let`'s bindings, regexp backslash syntax, variable referencing, and second argument to `match-string`, which needs to be the same string passed to `string-match`. In brief, the value of `'foo` is the canonical symbol with the name `foo`, whereas the value of `foo` is the value stored in the variable whose name is the symbol `foo`. For example, `(setq foo 1)` is actually shorthand for `(set 'foo 1)`. # Answer > 0 votes I think I solved it myself. Apparently I have to run my code *inside* the let(), not *outside*. The following works (= does not throw an error). Note the brackets. ``` (defun citekey-get-author-and-year () "Get the _author_ and _YEAR_ from a cite:authorYEARtitle key." (interactive) ; allow this to be user-callable (let ((regexp ":\(.*\)\([0-9]*\)[a-z]") ; the regex to parse author year (citekey (buffer-substring (line-beginning-position) (line-end-position)))) ; body (message regexp) (message citekey) (when (string-match ":\(.*\)\([0-9]*\)[a-z]" citekey) (when (string-match regexp 'citekey) (setq author (match-string 1 string) year (match-string 2 string)))) (message "---") (message author) (message year) )) ``` --- Now I only got to fix the regexp! :) --- E2: This is what I came up with myself. ``` (defun citekey-get-author-and-year () "Get the _author_ and _YEAR_ from a cite:authorYEARtitle key." (interactive) ; allow this to be user-callable (let ( ;; (regexp ":\(.*\)\([0-9]*\)[a-z]") ; the regex to parse (regexp (rx ":" (group (zero-or-more letter)) (group (one-or-more digit)) (one-or-more letter) )) author year (citekey (buffer-substring (line-beginning-position) (line-end-position)))) ; body (message regexp) (message citekey) (when (string-match regexp citekey) (setq author (match-string 1 citekey) year (match-string 2 citekey))) (message "---") (message (concat author " + " year)) )) ``` --- Tags: regular-expressions, quote ---
thread-63566
https://emacs.stackexchange.com/questions/63566
Is there a way to narrow down grep results?
2021-02-24T12:51:53.537
# Question Title: Is there a way to narrow down grep results? When I search with `grep`, I get the results like: > -*\- mode: grep; default-directory: "~/code/" -*\- Grep started at Wed Feb 24 12:40:28 > > find . -type d ... that is followed by multiple lines with results. Now when I have the result, how do I narrow the search to the relevant results? One way would be limiting the results to certain files in the folders listed. Another option would be narrowing it down to a more refined search. For example, I grep for 'select' then how do I narrow down the results to 'select\_email'? # Answer As Arkadiusz Drabczyk has suggested in his comment, > M-x occur is the best answer for my needs. Thank you very much! > 1 votes --- Tags: grep ---
thread-63416
https://emacs.stackexchange.com/questions/63416
Specify optional matches with pcase
2021-02-15T21:25:58.717
# Question Title: Specify optional matches with pcase Consider the following form: ``` (pcase '(:def "k" #'foo :wk "ho") (`(:def ,(and (or (pred stringp) (pred vectorp)) key) ,(and (pred xl-sharp-quoted-symbol-p) def) :wk ,(and (pred stringp) desc)) (format "%s | %s | %s" key def desc))) ;; => "k | #'foo | ho" ``` Suppose that I want the keywords `:def` and `:wk` to be optional. In other words I want the pcase form to successfully parse the following lists: ``` '("k" #'foo "bar") '("k" #'foo :wk "bar") '(:def "k" #'foo "bar") ``` Of course I realize it is possible to copy over the clause in my first example in all possible combinations omitting either `:def`, `:wk` or both. However, that's tedious and duplicates much code. I wish I could do something like this: ``` (pcase '(:def "k" #'foo :wk "ho") (`(,(optional :def) ,(and (or (pred stringp) (pred vectorp)) key) ,(and (pred xl-sharp-quoted-symbol-p) def) ,(optional :wk) ,(and (pred stringp) desc)) (format "%s | %s | %s" key def desc))) ``` Is there a way to do this concisely with `pcase`? If so, how? # Answer > 3 votes The backquote `pcase` pattern ``--pcase-macroexpander` is implemented using `pcase-defmacro` in the library `pcase.el`. There is no pattern included there that does what you discussed. But, it may be added as shown in the following Elisp code that defines an alternative `pcase` pattern `bq-opt`. The added lines are cleanly added as one block. This block is framed by two lines only consisting of semi-colons. ``` (pcase-defmacro bq-opt (qpat) "Pattern (bq-opt QPAT) dealing with ?\\, like the backquote pattern. QPAT can take the following forms: ((optional QPAT1) . QPAT2) matches if QPAT1 matches the car and QPAT2 matches the cdr or if QPAT2 matches (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr. ,PAT matches if the `pcase' pattern PAT matches. SYMBOL matches if EXPVAL is `equal' to SYMBOL. KEYWORD likewise for KEYWORD. NUMBER likewise for NUMBER. STRING likewise for STRING. The list or vector QPAT is a template. The predicate formed by a backquote-style pattern is a combination of those formed by any sub-patterns, wrapped in a top-level condition: EXPVAL must be \"congruent\" with the template. For example: (bq-opt technical ,forum) The predicate is the logical-AND of: - Is EXPVAL a list of two elements? - Is the first element the symbol `technical'? - True! (The second element can be anything, and for the sake of the body forms, its value is bound to the symbol `forum'.)" (declare (debug (pcase-QPAT))) (cond ((eq (car-safe qpat) '\,) (cadr qpat)) ((vectorp qpat) `(and (pred vectorp) (app length ,(length qpat)) ,@(let ((upats nil)) (dotimes (i (length qpat)) (push `(app (pcase--flip aref ,i) ,(list '\` (aref qpat i))) upats)) (nreverse upats)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Added case (optional QPAT) ((pcase qpat (`((optional ,qpat1) . ,qpat2) `(or (and (pred consp) (app car ,qpat1) (app cdr ,(list 'bq-opt qpat2))) ,(list 'bq-opt qpat2))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ((consp qpat) `(and (pred consp) (app car ,(list 'bq-opt (car qpat))) (app cdr ,(list 'bq-opt (cdr qpat))))) ((or (stringp qpat) (numberp qpat) (symbolp qpat)) `',qpat) ;; In all other cases just raise an error so we can't break ;; backward compatibility when adding \` support for other ;; compounded values that are not `consp' (t (error "Unknown QPAT: %S" qpat)))) ``` Usage example with optional keywords in `EXPVAL`: ``` (pcase '(:def "k" foo :wk "ho") ((bq-opt ((optional :def) ,(and (or (pred stringp) (pred vectorp)) key) ,(and (pred symbolp) def) (optional :wk) ,(and (pred stringp) desc) )) (format "%s | %s | %s" key def desc))) ``` Result: ``` "k | foo | ho" ``` Usage example without optional keywords in `EXPVAL`: ``` (pcase '("k" foo "ho") ((bq-opt ((optional :def) ,(and (or (pred stringp) (pred vectorp)) key) ,(and (pred symbolp) def) (optional :wk) ,(and (pred stringp) desc) )) (format "%s | %s | %s" key def desc))) ``` Result: ``` "k | foo | ho" ``` # Answer > 0 votes My second solution is not an attempt to modify or replace the backquote pattern of `pcase` but it introduces a new `pcase` macro that works in collaboration with backquote patterns. It does quite exactly what you proposed in your question: > Of course I realize it is possible to copy over the clause in my first example in all possible combinations omitting either :def, :wk or both. However, that's tedious and duplicates much code. But, the tedious duplication of code is done by the `pcase` macro `optional`. The doc-string of `optional` already describes quite good how it works. ``` (pcase-defmacro optional (pat-opt pat-tail) "Define a pattern (optional PAT-OPT PAT-TAIL) for `pcase'. The pattern matches - if EXPVAL is a cons with the car matching PAT-OPT and the cdr matching PAT-TAIL -- or -- - if EXPVAL matches PAT-TAIL." (declare (debug (pcase-PAT pcase-PAT))) `(or (and (app car ,pat-opt) (app cdr ,pat-tail)) ,pat-tail)) ``` As already mentioned, `optional` is a pattern keyword that you can use in conjunction with backquoted patterns. It is not parsed by a modified backquote-pcase-macro as in my first solution. Therefore, the pattern for your usage example looks a bit different from your proposed pattern. Nevertheless, you do **not** need to write the tail behind the optional keyword twice. ``` (pcase val ((optional :def `(,(and (or (pred stringp) (pred vectorp)) key) ,(and (pred symbolp) def) . ,(optional :wk `(,(and (pred stringp) desc))))) (format "%s | %s | %s" key def desc))) ``` The evaluation of this example gives: ``` "k | foo | ho" ``` --- Tags: conditionals, pcase ---
thread-63586
https://emacs.stackexchange.com/questions/63586
Abbreviate "/home/user/file" to "~/file" in formatted fields (frame-title-format, etc.)
2021-02-24T22:20:16.490
# Question Title: Abbreviate "/home/user/file" to "~/file" in formatted fields (frame-title-format, etc.) I have Emacs display the full path of the file in my window title: ``` (setq-default frame-title-format '("%f [%m] - Emacs")) ``` And in my mode-line: ``` (setq-default mode-line-buffer-identification (list 'buffer-file-name (propertized-buffer-identification "%12f") (propertized-buffer-identification "%12b"))) ``` But I would prefer it to not show my actual user name, how can I get this abbreviate standard unix path? # Answer Use function `abbreviate-file-name`. `C-h f` tells us: > `abbreviate-file-name` is a compiled Lisp function in `files.el`. > > `(abbreviate-file-name FILENAME)` > > Return a version of `FILENAME` shortened using `directory-abbrev-alist`. > > This also substitutes `~` for the user's home directory (unless the home directory is a root directory) and removes automounter prefixes (see the variable `automount-dir-prefix`). > > When this function is first called, it caches the user's home directory as a regexp in `abbreviated-home-dir`, and reuses it afterwards (so long as the home directory does not change; if you want to permanently change your home directory after having started Emacs, set `abbreviated-home-dir` to nil so it will be recalculated). If you want to use that in `frame-title-format` and `mode-line-format`, try this: ``` (setq-default frame-title-format '((:eval (list (abbreviate-file-name (expand-file-name buffer-file-name)) " [%m] - Emacs")))) (setq-default mode-line-buffer-identification '((:eval (list (abbreviate-file-name (expand-file-name buffer-file-name)))))) ``` > 6 votes --- Tags: filenames, mode-line-format, frame-title-format ---
thread-63596
https://emacs.stackexchange.com/questions/63596
When emacsclient open with eval using use-package it opens waiting M-x
2021-02-25T13:44:40.060
# Question Title: When emacsclient open with eval using use-package it opens waiting M-x I am trying to create a bash alias to open emacs with a calendar from terminal. To do so I am using calfw with use-package like so: ``` (use-package calfw :ensure ;TODO: :config (require 'calfw) (require 'calfw-org) (setq cfw:org-overwrite-default-keybinding t) (require 'calfw-ical) :bind ("C-c q" . 'cfw:open-org-calendar)) ``` When I try to do ``` em --eval "(execute-extended-command (cfw:open-org-calendar))" ``` it opens with the calendar open, but it waits for a M-x command Not sure what I am doing wrong. Thx! # Answer > 1 votes Look at the help for `execute-extended-command` (via `C-h f execute-extended-command`): > It is bound to , , M-x. > > (execute-extended-command PREFIXARG &optional COMMAND-NAME TYPED) > > This function is for interactive use only; in Lisp code use ‘command-execute’ instead. > > Read a command name, then read the arguments and call the command. To pass a prefix argument to the command you are invoking, give a prefix argument to ‘execute-extended-command’. This tells us that `execute-extended-command` is for *interactively* prompting the user for the name of a command to run. It is the command that is run when you enter `M-x`, so it makes sense that your client opens with the `M-x` prompt waiting for you. If you want to execute a function in elisp, you just need to call that function, you don't need to wrap it in `execute-extended-command`: ``` em --eval "(cfw:open-org-calendar)" ``` --- Tags: emacsclient, use-package, eval ---
thread-63595
https://emacs.stackexchange.com/questions/63595
Evaluating inline source code in Title
2021-02-25T10:43:52.717
# Question Title: Evaluating inline source code in Title Is there a way to make my document title dynamic, for instance like this : ``` #+Title: Annual report for year src_emacs-lisp{(- (string-to-number (format-time-string "%Y")) 1)} ``` Should render as : ## Annual report for year 2020 # Answer You can use an `orgmode` macro for this. It supports evaluating elisp code like this: > #+MACRO: year (eval (format-time-string "%Y")) > #+TITLE: Annual Report for {{{year}}} There's a built-in macro for rendering the time a document is exported, which takes a time format as an argument. This should handle your particular example: > #+TITLE: Annual Report for {{{time(%Y)}}} You can also use the built-in `date` macro, which allows you to format the value of the `DATE` keyword: > #+TITLE: Annual Report for {{{date(%Y)}}} > #+DATE: \<2020-02-25 Thu\> In order to format the `date` macro, the `DATE` keyword must be a timestamp. This would allow you to set the date in the DATE keyword, and have that value be rendered in the title, or other places in the document. Those values would stay the same no matter when you rendered the document, while the value for the `time` macro will be updated to reflect the latest rendering. > 2 votes --- Tags: org-mode ---
thread-3785
https://emacs.stackexchange.com/questions/3785
How to specify default header arguments in orgmode code blocks
2014-11-21T15:45:42.733
# Question Title: How to specify default header arguments in orgmode code blocks I'm tying to set default header arguments to the code blocks within my org file, like this: ``` #+PROPERTY: header-args :session *my_python_session* #+PROPERTY: header-args :results silent #+PROPERTY: header-args :tangle yes ``` My code blocks look like this: ``` #+BEGIN_SRC python import pandas as pd #+END_SRC ``` However, when I call `org-babel-tangle` from this buffer, I get *Tangled 0 code blocks from filename.org*. When I add `:tangle yes` to the end of the `#+BEGIN_SRC` line, the code block is exported when I call `org-babel-tangle`. I would expect that I don't need to set `:tangle yes` on each code block. What am I doing wrong? # Answer > 36 votes You should have every header argument in one line: ``` #+PROPERTY: header-args :session *my_python_session* :results silent :tangle yes ``` Having several `#+PROPERTY` lines is accepted, but not in the way you're trying to do it. From the Org manual (7.1 Property syntax): > If you want to add to the value of an existing property, append a ‘+’ to the property name. The following results in the property ‘var’ having the value “foo=1 bar=2”. > > ``` > #+PROPERTY: var foo=1 > #+PROPERTY: var+ bar=2 > > ``` So, since `header-args` is the property and `:session`, `:results` and `:tangle` are its values, it should be: ``` #+PROPERTY: header-args :session *my_python_session* #+PROPERTY: header-args+ :results silent #+PROPERTY: header-args+ :tangle yes ``` But it's easier to have just one line IMO. # Answer > 4 votes Been hit by this a few times, so here is my workings: ``` Some text before the properties, this should according to the manual, prevent properties from working... - Seems to work fine - which I like. # These work for 'shell' only, not 'sh'. #+PROPERTY: header-args:shell :var propC_headArgsCshell_0="1st" #+PROPERTY: header-args:shell+ :var propC_headArgsCshellY_1="dc=example,dc=com" #+PROPERTY: header-args:shell+ :var propC_headArgsCshellY_2="cn=Manager" # # While these apply to all: #+PROPERTY: header-args :var propC_headArgs_Cvar_1="dc0example,dc=com" #+PROPERTY: header-args+ :var propC_headArgsY_Cvar_2="cn=Manager" # # Following does not work, yes that is as shown in the guide! #+PROPERTY: var propC_var_1="dc=example,dc=com" #+PROPERTY: var+ propC_varY_2="cn=Manager" # #+begin_quote Properties can be inserted on buffer level. That means they apply before the propC_headArgsCshell_0 headline and can be inherited by all entries in a file. Property blocks defined before propC_headArgsCshell_0 headline needs to be located at the top of the buffer, allowing only comments above. #+end_quote - source [[https://orgmode.org/manual/Property-Syntax.html][Property Syntax (The Org Manual)]] Using org-mode version #+begin_src emacs-lisp (org-version) #+end_src #+results: : 9.4.4 * Example for shell #+begin_src shell :var Cvar_local0='dc=example,dc=net' Cvar_local1="cn=Manager,$Cvar_local0" echo Predict Arg Value echo value propC_headArgsCshell_0 $propC_headArgsCshell_0 echo value Cvar_local0 $Cvar_local0 echo value Cvar_local1 $Cvar_local1 echo value! propC_var_1 $propC_var_1 echo value! propC_varY_2 $propC_varY_2 echo value propC_headArgsCshellY_1 $propC_headArgsCshellY_1 echo value propC_headArgsCshellY_2 $propC_headArgsCshellY_2 echo value propC_headArgs_Cvar_1 $propC_headArgs_Cvar_1 echo value propC_headArgsY_Cvar_2 $propC_headArgsY_Cvar_2 #+end_src #+results: | Predict | Arg | Value | | value | propC_headArgsCshell_0 | 1st | | value | Cvar_local0 | dc=example | | value | Cvar_local1 | cn=Manager,$Cvar_local0 | | value! | propC_var_1 | | | value! | propC_varY_2 | | | value | propC_headArgsCshellY_1 | dc=example,dc=com | | value | propC_headArgsCshellY_2 | cn=Manager | | value | propC_headArgs_Cvar_1 | dc0example,dc=com | | value | propC_headArgsY_Cvar_2 | cn=Manager | * Example of sh using ~sh~ rather than shell, they are different: #+begin_src sh :var Cvar_local0='dc=example,dc=net' Cvar_local1="cn=Manager,$Cvar_local0" echo predict arg value echo blank propC_headArgsCshell_0 $propC_headArgsCshell_0 echo value Cvar_local0 $Cvar_local0 echo value Cvar_local1 $Cvar_local1 echo value! propC_var_1 $propC_var_1 echo value! propC_varY_2 $propC_varY_2 echo blank propC_headArgsCshellY_1 $propC_headArgsCshellY_1 echo blank propC_headArgsCshellY_2 $propC_headArgsCshellY_2 echo value propC_headArgs_Cvar_1 $propC_headArgs_Cvar_1 echo value propC_headArgsY_Cvar_2 $propC_headArgsY_Cvar_2 #+end_src #+results: | predict | arg | value | | blank | propC_headArgsCshell_0 | | | value | Cvar_local0 | dc=example | | value | Cvar_local1 | cn=Manager,$Cvar_local0 | | value! | propC_var_1 | | | value! | propC_varY_2 | | | blank | propC_headArgsCshellY_1 | | | blank | propC_headArgsCshellY_2 | | | value | propC_headArgs_Cvar_1 | dc0example,dc=com | | value | propC_headArgsY_Cvar_2 | cn=Manager | ``` Glad to get that down. --- Tags: org-mode, org-babel ---
thread-63348
https://emacs.stackexchange.com/questions/63348
Swap TAB and Escape in all modes including evil
2021-02-12T15:14:09.803
# Question Title: Swap TAB and Escape in all modes including evil `Escape` is too far away on modern keyboards and `Tab` could be easily typed as `Ctrl`+`i` in terminal applications. So I found it convenient to replace them in my alacritty terminal key bindings. I am used to these replacements and want them for Emacs also. What should I do, to replace `Esc` with `Tab` and vice versa in all buffers, modes, context etc allover Emacs(including evil-mode ofc)? I've tried this in my `init.el` ``` (define-key input-decode-map [tab] [?\e]) (define-key input-decode-map [escape] [?\t]) ``` But this doesn't trigger insert-to-normal transition in evil mode: I am pressing `tab`, I am seeng `ESC ESC ESC` in bottom bar, but evil state remains `<I>`. # Answer > 1 votes If I understand you correctly, most importantly, you would like `<tab>` to work as `<escape>` in various "evil states". With emacs, the way I see it, you are offered with more freedom than merely "switching" these two key strokes. To rebind `<tab>` for common evil states, you can first checkout with `C-h k <escape>` while under different states, to see the originally bound functions. I'll list each of them below: ``` (evil-global-set-key 'insert (kbd "<tab>") 'evil-normal-state) (evil-global-set-key 'replace (kbd "<tab>") 'evil-normal-state) (evil-global-set-key 'normal (kbd "<tab>") 'evil-force-normal-state) (evil-global-set-key 'visual (kbd "<tab>") 'evil-exit-visual-state) ``` **NOTE**: For other states like `operator` or `motion`, it's not quite relevant here. Also for operator state for instance, `C-g` works perfectly. If you want buffer local behavior instead of global (or special behavior in particular buffers, major modes, etc.), you can switch to `evil-local-set-key` for more precise keybindings. You can do the same for `(kbd "<escape>")`, and rebind to literally anything you want for each state. See what I mean by "freedom" in emacs. Hope this is what you expect. My whole point is instead of switching ESC and TAB completely, do whatever makes the most sense for your workflow. --- Tags: key-bindings, evil ---
thread-63604
https://emacs.stackexchange.com/questions/63604
Having a hard time understanding some of Paul Graham's example code in his book “On Lisp”
2021-02-26T01:36:21.503
# Question Title: Having a hard time understanding some of Paul Graham's example code in his book “On Lisp” https://sep.yimg.com/ty/cdn/paulgraham/onlisp.pdf On page 36 Paul introduces the following function: ``` (defun flatten (x) (labels ((rec (x acc) (cond ((null x) acc) ((atom x) (cons x acc)) (t (rec (car x) (rec (cdr x) acc)))))) (rec x nil))) ``` I'm trying to gain an intuition as to how he came to this implementation. I know that recursion is a big theme in Emacs Lisp (and Lisp in general), but trying to work through some of this code gives me a headache. Is there a strategy for studying code like this? Or does there need to be a paradigm shift in the way I'm reasoning about code such as this? Or an external resource that could give me a better intuition? Or, over time, will these idioms become more apparent to me (if this is in fact idiomatic Lisp)? For example, given this input to function `flatten`: `(flatten '(1 (2 3 (4 5))))` This is the trace of the given output: ``` { flatten args: ((1 (2 3 (4 5)))) :{ rec@cl-flet@381 args: ((1 (2 3 (4 5))) nil) ::{ rec@cl-flet@381 args: (((2 3 (4 5))) nil) :::{ rec@cl-flet@381 args: (nil nil) :::} rec@cl-flet@381 result: nil :::{ rec@cl-flet@381 args: ((2 3 (4 5)) nil) ::::{ rec@cl-flet@381 args: ((3 (4 5)) nil) :::::{ rec@cl-flet@381 args: (((4 5)) nil) ::::::{ rec@cl-flet@381 args: (nil nil) ::::::} rec@cl-flet@381 result: nil ::::::{ rec@cl-flet@381 args: ((4 5) nil) :::::::{ rec@cl-flet@381 args: ((5) nil) ::::::::{ rec@cl-flet@381 args: (nil nil) ::::::::} rec@cl-flet@381 result: nil ::::::::{ rec@cl-flet@381 args: (5 nil) ::::::::} rec@cl-flet@381 result: (5) :::::::} rec@cl-flet@381 result: (5) :::::::{ rec@cl-flet@381 args: (4 (5)) :::::::} rec@cl-flet@381 result: (4 5) ::::::} rec@cl-flet@381 result: (4 5) :::::} rec@cl-flet@381 result: (4 5) :::::{ rec@cl-flet@381 args: (3 (4 5)) :::::} rec@cl-flet@381 result: (3 4 5) ::::} rec@cl-flet@381 result: (3 4 5) ::::{ rec@cl-flet@381 args: (2 (3 4 5)) ::::} rec@cl-flet@381 result: (2 3 4 5) :::} rec@cl-flet@381 result: (2 3 4 5) ::} rec@cl-flet@381 result: (2 3 4 5) ::{ rec@cl-flet@381 args: (1 (2 3 4 5)) ::} rec@cl-flet@381 result: (1 2 3 4 5) :} rec@cl-flet@381 result: (1 2 3 4 5) } flatten result: (1 2 3 4 5) ``` What seems to be trivial input ends up becoming a web of recursive calls. So when you think about functions such as these, do you, in your head, reason from certain base-cases and proceed? Like, for example, would you consider the `(nil)` case first, then the `(1)` case, then `(1 2)`, then `(1 (2 3))` and so on? Or is that not necessary? # Answer I recommend watching some lectures from MIT's 6.001 course using The Structure and Interpretation of Computer Programs. It's the best software engineering textbook ever written, and the lectures are well done. (On the other hand the recordings are positively ancient, and display a lot of obvious defects from the equipment of the day. The material is timeless though, so don't let those defects distract you. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-001-structure-and-interpretation-of-computer-programs-spring-2005/video-lectures/ The reason I recommend these lectures is that they go over how you write software like this several times, in several different guises. You do indeed want to consider the base cases very carefully. In a case like this you would want to have a case for every kind of thing you could come across in a list that someone handed you. It could be nothing, it could be a number, a string, a symbol, or it could be a list. Luckily, in this case you'll end up doing the same thing with a number as you will do with a string, so we can group most of the cases into a single case that looks for atomic objects (things that aren't lists). And then it's just a matter of working out what to do with the complicated case. In this case you want to flatten the cdr of the list. That seems like a lot of work until you remember that you could just call a function that flattens any list, if you have one available. Guess what? We do have a function called rec which will flatten lists, so we just call that. Never mind that we haven't actually finished writing it yet; once we do finish writing it it will flatten lists for us. Looking at the trace is also a very good idea. You'll get something very similar to the trace if you apply the substitution model that is presented in lecture 1B. In lecture 9A they describe a register machine that can execute Scheme (aka Lisp) code, and describe how that chain of function calls that builds up in the substitution model turns into a stack stored in memory. > 2 votes --- Tags: recursion ---
thread-62823
https://emacs.stackexchange.com/questions/62823
Execute function by using evil-set-register
2021-01-16T19:22:18.503
# Question Title: Execute function by using evil-set-register I use evil and I want to execute a function by using Emacs macro system. Let's say I have the following macro. ``` (evil-set-register ?f [?i ?f ?o ?o ?b ?a ?r escape]) ``` I can run the macro by using `@f`. But this system is not easy to read and maintain. # Question How to execute an interactive function by using `@f` shortcut? ## Example Here's function `insert-foobar` which inserts string `foobar`: ``` (defun insert-foobar nil "Insert foobar." (interactive) (call-interactively 'evil-append) (insert "foobar") (evil-normal-state)) ``` ``` (evil-set-register ?f (call-interactively 'insert-foobar)) ;; This does not work (evil-set-register ?f (insert-foobar)) ;; This does not work too ``` # Answer > 1 votes ``` (evil-set-register ?f (lambda nil "documentation" (call-interactively 'insert-foobar))) ``` --- Tags: evil, keyboard-macros ---
thread-55697
https://emacs.stackexchange.com/questions/55697
calculate the sum of the muplication of 2 columns in org table
2020-02-22T03:22:05.723
# Question Title: calculate the sum of the muplication of 2 columns in org table I have a org table: ``` | a | b | c | |---+---+---| | 1 | 2 | i | | 3 | 4 | j | |---+---+---| | 4 | 6 | | ``` I want to multiply columns `a` and `b` and sum them up (except last row: `1*2+3*4`) and put into the last cell: ``` | a | b | c | |---+---+---| | 1 | 2 | i | | 3 | 4 | j | |---+---+---| | 4 | 6 | 14| ``` What is the formula to achieve this? I tried `#+TBLFM: @>$>=sum($1 * $2)` without luck. My org version: Org mode version 9.1.9 (release\_9.1.9-65-g5e4542 @ /Applications/Emacs.app/Contents/Resources/lisp/org/) # Answer > 8 votes ``` @4$3=(@2$1..@3$1)*(@2$2..@3$2) ``` or ``` @>$>=(@<<$<..@>>$<)*(@<<$<<..@>>$<<) ``` or ``` @>$>=(@I$1..@II$1)*(@I$2..@II$2) ``` using the horizontal lines to delimit instead of explicit row numbers. The relevant section of the manual is dense but well-worth reading (and re-reading). # Answer > 0 votes You could use the `Orgtbl-Aggregate` package available on Melpa The sums are in a separate table, easy to update ``` #+name: mytable | a | b | c | |---+---+---| | 1 | 2 | i | | 3 | 4 | j | #+BEGIN: aggregate :table "mytable" :cols "vsum(a) vsum(b) vsum(a*b)" | vsum(a) | vsum(b) | vsum(a*b) | |---------+---------+-----------| | 4 | 6 | 14 | #+END: ``` --- Tags: org-mode, org-table ---
thread-5613
https://emacs.stackexchange.com/questions/5613
How to convert lines to an org-mode checklist?
2014-12-21T07:00:25.517
# Question Title: How to convert lines to an org-mode checklist? Suppose I have the following list. I'd like to convert it to a checklist. ``` Lec 1 | 1:20:36 Lec 2 | 1:10:32 Lec 3 | 1:08:33 Lec 4 | 1:20:33 Lec 5 | 1:16:50 Lec 6 | 1:08:49 Lec 7 | 1:17:40 Lec 8 | 1:19:47 Lec 9 | 1:21:22 Lec 10 | 1:23:52 Lec 11 | 1:23:45 Lec 12 | 1:25:32 Lec 13 | 1:19:06 Lec 14 | 1:14:28 Lec 15 | 1:11:01 Lec 16 | 1:24:07 Lec 17 | 1:24:34 Lec 18 | 1:17:17 Lec 19 | 1:14:59 Lec 22 | 1:15:08 Lec 23 | 1:16:48 Lec 24 | 1:24:47 Lec 25 | 1:25:21 ``` How to do it? (I did it in using kbd-macro. I wonder is there an `org` command to do it?) # Answer Simplest way I could think of: 1. Select the list. 2. Move the point to the first column. 3. `C-x r t``- [ ]``RET` You are done. > 33 votes # Answer Vanilla org-mode: * `C-c -` (`org-ctrl-c-minus`) - Convert selected text into a plain list * `C-u C-c C-x C-b` (`org-toggle-checkbox`) - Convert selected plain list into a list with checkboxes Spacemacs: * `, -` (`org-ctrl-c-minus`) - Convert selected text into a plain list * `SPC u , T c` (`org-toggle-checkbox`) - Convert selected plain list into a list with checkboxes > 21 votes # Answer First, some semantics for clarity. In `org-mode`, a *plain list* is either ordered or unordered, starting with either a `-`, `+`, or `*` (for unordered), or a number followed by either a `.` or a `)` (for ordered). So: the "list" you describe in your example is not yet an `org-mode` list, because it doesn't start with any of these bullets. Second, I presume by "checklist" you mean the checkboxes that `org-mode` uses in its plain lists, as in: ``` - [X] A checked list item - [ ] An unchecked list item ``` Here's a very simple function that will convert all lines in the selected region to an unordered list with checkboxes (not extensively tested, but works on your example): ``` (defun org-convert-lines-to-checklist (beg end) "Convert all plain lines in region to a plain list with checkboxes." (interactive "r") (save-excursion (goto-char beg) (dotimes (_ (- (line-number-at-pos end) (line-number-at-pos beg))) (insert "- [ ] ") (indent-according-to-mode) (forward-line 1)))) ``` > 11 votes # Answer Below is another **fun** way to transform text into an `org-mode` checklist. **Use Org-mode Code Blocks to Convert Text into List of Checkboxes** > Note: To generate the results use `C-c` `C-c` while the cursor is within a code block. > Then answer `yes` when prompted. 1. Wrap your list inside a named dynamic block ``` #+NAME: my-list-block #+BEGIN: Lec 1 | 1:20:36' Lec 2 | 1:10:32 Lec 3 | 1:08:33 Lec 4 | 1:20:33 ... More ... Lec 24 | 1:24:47 Lec 25 | 1:25:21 #+END: ``` 2. Write an `org-mode` code block in your favorite programming language. **Example 1** \- Using an `elisp` Code Block ``` #+name: list-into-checklist-elisp #+header: :results list raw replace output #+header: :var data=my-list-block() #+begin_src elisp (dolist (x (split-string data "\n")) (princ (format "[ ] %s\n" x))) #+end_src #+RESULTS: list-into-checklist-elisp - [ ] Lec 1 | 1:20:36 - [ ] Lec 2 | 1:10:32 - [ ] Lec 3 | 1:08:33 - [ ] Lec 4 | 1:20:33 - [ ] ... More ... - [ ] Lec 24 | 1:24:47 - [ ] Lec 25 | 1:25:21 ``` **Example 2** \- Using a `perl` Code Block ``` #+name: list-into-checklist-perl #+header: :results list raw replace output #+header: :var data=my-list-block() #+begin_src perl map { printf qq([ ] %s\n), $_ } split(/\n/, $data); #+end_src #+RESULTS: list-into-checklist-perl - [ ] Lec 1 | 1:20:36 - [ ] Lec 2 | 1:10:32 - [ ] Lec 3 | 1:08:33 - [ ] Lec 4 | 1:20:33 - [ ] ... More ... - [ ] Lec 24 | 1:24:47 - [ ] Lec 25 | 1:25:21 ``` **Example 3** \- Using a `bash` Code Block ``` #+name: list-into-checklist-bash #+header: :results list raw replace output #+header: :shebang #!/usr/bin/env bash #+header: :var data=my-list-block() #+begin_src sh while IFS="\n" read -ra ADDR; do for i in "${ADDR[@]}"; do echo "[X] $i" done done <<< "$data" #+end_src #+RESULTS: list-into-checklist-bash - [X] Lec 1 | 1:20:36 - [X] Lec 2 | 1:10:32 - [X] Lec 3 | 1:08:33 - [X] Lec 4 | 1:20:33 - [X] ... More ... - [X] Lec 24 | 1:24:47 - [X] Lec 25 | 1:25:21 ``` **Example 4** \- Using a `python` Code Block ``` #+name: list-into-checklist-python #+header: :results list raw replace output #+header: :var data=my-list-block() #+Begin_src python l = ["[ ] {x}".format(x=row) for row in data.splitlines()] for i in l: print i #+end_src #+RESULTS: list-into-checklist-python - [ ] Lec 1 | 1:20:36 - [ ] Lec 2 | 1:10:32 - [ ] Lec 3 | 1:08:33 - [ ] Lec 4 | 1:20:33 - [ ] ... More ... - [ ] Lec 24 | 1:24:47 - [ ] Lec 25 | 1:25:21 ``` **Example 5** \- Using a `ruby` Code Block ``` #+name: list-into-checklist-ruby #+header: :results list raw replace output #+header: :var data=my-list-block() #+Begin_src ruby for l in data.split("\n") puts "[ ] #{l}" end #+end_src #+RESULTS: list-into-checklist-ruby - [ ] Lec 1 | 1:20:36 - [ ] Lec 2 | 1:10:32 - [ ] Lec 3 | 1:08:33 - [ ] Lec 4 | 1:20:33 - [ ] ... More ... - [ ] Lec 24 | 1:24:47 - [ ] Lec 25 | 1:25:21 ``` Thanks for asking your question! Hope that helped! Note: This code was tested using the following versions of emacs and org-mode. ``` GNU Emacs 24.4.1 (x86_64-apple-darwin14.0.0, NS apple-appkit-1343.14) Org-mode version 8.2.10 (8.2.10-29-g89a0ac-elpa) ``` > 9 votes # Answer Using search and replace: `M-%`Lec `Enter` \- \[ \] Lec `Enter` Note that there are spaces around the checkbox, although they don't show up well here. > 7 votes # Answer In Evil mode or Spacemacs you can do this, assuming you have not changed the default key-bindings: 1. In Normal state (equivalent to Vim's Normal mode), move the cursor to the beginning of the **first** line in your list. 2. Press `Ctrl`+`v`. 3. Press `j` once for each **remaining** line in your list. *(Alternatively, type the number of remaining lines in your list, followed by the `j` key. E.g. for your example: `2``4``j`.)* 4. Press `Shift`+`i`. 5. Type `- [ ]`. 6. Press `Esc`. > 3 votes # Answer For short, `C-u C-c C-c` on the first item of a list can turn the whole list into checklist. Checkboxes (The Org Manual) says > `C-c C-c` (`org-toggle-checkbox`) > > Toggle checkbox status or — with prefix argument — checkbox presence at point. > > * With a single prefix argument, add an empty checkbox or remove the current one. > * With a double prefix argument, set it to ‘\[-\]’, which is considered to be an intermediate state. There is a note on the single prefix argument: > `C-u C-c C-c` on the *first* item of a list with no checkbox adds checkboxes to the rest of the list. > 3 votes --- Tags: org-mode ---
thread-63612
https://emacs.stackexchange.com/questions/63612
org-roam and persp-mode.el: persp-def-auto-persp has nil (buffer-file-name)
2021-02-26T10:23:38.320
# Question Title: org-roam and persp-mode.el: persp-def-auto-persp has nil (buffer-file-name) I would like all org-roam buffers to automatically go into a `persp-mode.el` perspective. `org-roam-mode` is a global minor mode, so I can't use that as a way to detect whether a new buffer is for org-roam. I tried this: ``` (defun my/roam-buffer (_buffer state) (let ((name (buffer-file-name))) (when (and name (s-contains-p "/org-roam/" name)) (if (null state) 't state)))) (with-eval-after-load 'org-roam (setq org-roam-db-location (expand-file-name "~/.org-roam.sqlite")) (persp-def-auto-persp "org-roam" :parameters '((dont-save-to-file . t)) :predicate 'my/roam-buffer :dyn-env '(after-switch-to-buffer-functions ;; prevent recursion (persp-add-buffer-on-find-file nil) persp-add-buffer-on-after-change-major-mode) :hooks '(after-switch-to-buffer-functions) :switch 'frame)) ``` However, `(buffer-file-name)` in `my/roam-buffer` is `nil`. I'm guessing that's because initially when the buffer is created (again I'm guessing persp is hooking into that), it's not linked to a file yet? How can I achieve what I want? # Answer > 1 votes It appears as though `org-roam` has a hook specifically for this: `org-roam-file-setup-hook`. It's not well documented, but from reading the code it looks like it's called whenever an `org-roam` file is opened. From my testing, that means when it's done through the normal `find-file` means, from `org-roam-find-file`, and probably just about everything else that opens files. This includes creating new files. Here's the code I used to test, which you can adjust for your needs: ``` (defun bjc/test-roam-hook () (message "org roam buffer opened in %S for file %S" (current-buffer) (buffer-file-name))) (add-hook 'org-roam-file-setup-hook 'bjc/test-roam-hook) ``` --- Tags: hooks, org-roam, persp-mode ---
thread-63603
https://emacs.stackexchange.com/questions/63603
How to select and replace the content of all specific org-headings?
2021-02-26T00:13:29.627
# Question Title: How to select and replace the content of all specific org-headings? I am trying to select each content-heading extracted with org-noter and then remove all erroneous newlines. --- This is my function. ``` (defun sanitize-noter-import () "Sanitizes org-noter imports. This removes white-spaces from all '* Contents' headings." (interactive) (let (($headings nil) (nl " ") ; newline (nlb "- ") ; newline with hyphen-break heading) (org-map-entries (lambda () (setq heading (org-entry-get (point) "ITEM")) (if (string= heading "Contents") (progn (message heading) (next-line) (mark-paragraph) (replace-string nlb "" nil (point) (mark)) ; reconnect hyphenated words (replace-string nl " " nil (point) (mark)) ; remove line breaks (message "point is %s" (point)) (message "mark is %s" (mark)) )))) )) ``` --- This is some example text. ``` ** Skeleton *** Highlight on page 2 :PROPERTIES: :NOTER_PAGE: (2 . 0.18962766666666667) :END: **** Contents Gamification is the application of game features, mainly video game elements, into non-game context for the purpose of promoting motivation and engagement in learning. The application of gamification in a pedagogical context provides some remedy for many students who find themselves alienated by traditional methods of instruction. The use of gamifica- tion could provide... ``` --- When I call the function nothing gets replaced and I get the output ``` Contents point is 3983 mark is 4022 Mark set Replaced 0 occurrences ``` Point and marker are here: ``` *** Highlight on page 2 :PROPERTIES: :NOTER_PAGE: (2 . 0.18962766666666667) // point :END: // marker ``` --- How do I select the headings "body" and perform a text-operation on it? # Answer > 1 votes I solved it myself! ``` (defun sanitize-noter-import () "Sanitizes org-noter imports. This operates on '* Contents' headings" (interactive) (let (heading cbeg cend) (org-map-entries (lambda () (if (string= "Contents" (org-element-property :title (org-element-at-point))) (progn (message "Found 'Contents' heading") (message "%s" (org-element-context)) (setq cbeg (org-element-property :contents-begin (org-element-at-point))) (setq cend (org-element-property :contents-end (org-element-at-point))) (sanitize-region cbeg cend) ) ) ) ) )) (defun sanitize-region (cbeg cend) "Removes all line-breaks between CBEG and CEND" (let ((nl " ") (nlb "- ")) (message "contents-begin: %s contents-end: cend" cbeg) (message "Removing hyphen-breaks") (replace-string nlb "" nil cbeg cend) (message "Removing newlines") (replace-string nl " " nil cbeg cend) )) ``` --- --- What I don't really understand is why the `cend` does not delimit the full end, but instead points to a space two chars before. If I do `(goto-char cend) (insert "END")`, then it would insert it like `last woENDrd`. --- Tags: org-mode, replace, mark, selection ---
thread-63602
https://emacs.stackexchange.com/questions/63602
Prevent `(keyboard-quit)` from closing `*compile*` windows
2021-02-25T22:14:43.763
# Question Title: Prevent `(keyboard-quit)` from closing `*compile*` windows After a recent update to my Spacemacs install, I noticed that `C-g` i.e. `keyboard-quit` closes `*compilation*` buffers that result from an `M-x recompile`. How can I prevent this behavior? I don't want `C-g` to close `*compilation*` buffers. # Answer The culprit turned out to be `popwin`. I fixed it with `M-x customize-group RET popwin RET` and removing `compilation-mode` from the "Popwin Special Display Config" list. > 2 votes # Answer Try this: ``` (defun revert-spacemacs-C-g-doing (func &rest r) "Revert rebind of `keyboard-quit' from calling `pupo/after-display'" (apply func r) (global-set-key [remap keyboard-quit] nil)) (advice-add 'pupo/after-display :around 'revert-spacemacs-C-g-doing) ``` > 1 votes --- Tags: key-bindings, spacemacs, compilation ---
thread-63469
https://emacs.stackexchange.com/questions/63469
Position the cursor at a specific point in a custom Emacs grep command
2021-02-19T14:58:51.013
# Question Title: Position the cursor at a specific point in a custom Emacs grep command I have created this custom grep command in Emacs to search for contacts: ``` '(grep-command "grep --color -nH --null grep -ie '^name' -A 1 ~/diary/*.org") ``` I would like to be able to position my cursor automatically in the minibuffer at the start of `^name` rather than at the end of the string. Is this possible? # Answer Set your grep command to a cons cell whose car is the string you are now using, and whose cadr is the character index where you want the cursor: ``` '(grep-command (cons "grep --color -nH --null grep -ie '^name' -A 1 ~/diary/*.org" 35)) ``` One thing to look out for is, (I don’t use customize) if the expression has to be evaluated when you set it (because evaluation would break when it is executed) then you would replace the single quote with a back-tick and put a comma before the ‘cons form so that it is immediately evaluated. > 1 votes # Answer This doesn't precisely answer your question, but it shows how to position the cursor in the interactive prompt and maybe a different way you might like to solve your original problem: ``` (defun my/current-path () (or (buffer-file-name) default-directory)) (defun my/git-root () (let ((dir-path (my/current-path))) (and dir-path (file-truename (locate-dominating-file dir-path ".git"))))) (defun my/symbol-name-at-point-or-empty () (if (symbol-at-point) (symbol-name (symbol-at-point)) "")) (defun my/ag-grep-find (command-args) (interactive (progn (grep-compute-defaults) (let* ( (cmd (concat "do-search " (my/symbol-name-at-point-or-empty))) (one-based-cursor-position (+ (length cmd) 1))) (list (read-shell-command "Run find (like this): " (cons cmd one-based-cursor-position) (cons 'grep-find-history 1)))))) (when command-args (let ( (null-device nil) ; see grep (default-directory (my/git-root))) (grep command-args)))) ``` The command do-search is a little script I made that basically does (it's actually a python script because it also adds a bunch of --exclude flags, I'm translating to bash here without testing it, sorry): ``` #!/bin/bash set -e exec rg --color=never --line-number --smart-case --no-heading --stats -M 512 --max-columns-preview -- "$@" . ``` > 1 votes --- Tags: cursor, grep ---
thread-63618
https://emacs.stackexchange.com/questions/63618
How to remove first line indentation in org-mode, in the editor?
2021-02-26T21:45:12.110
# Question Title: How to remove first line indentation in org-mode, in the editor? In org, whenever I create a new tree and make a new line, the editor automatically indents only this first line (different behavior of older versions). I'd like the editor to behave so that it does not automatically indent that first line. I have `org-indent-mode` disabled. ***Note from author:** this question was extract from: How to remove first line indentation in org-mode, in the editor? #3872 made by @leonkis (Github). The reason why I put it here was because it was hard to find. Also, I copied the answer from @hlissner (Github) from here: https://github.com/hlissner/doom-emacs/issues/3872#issuecomment-684176505* ***2nd note:** This behavior changed in Emacs 24.4, as you can see here.* # Answer Unless you meant this occurs when you press RET on a new line. In which case, that's `electric-indent-mode`. ``` (electric-indent-mode -1) ; globally ;; or (add-hook! 'org-mode-hook (electric-indent-local-mode -1)) ``` *From: https://github.com/hlissner/doom-emacs/issues/3872#issuecomment-684176505 by @hlissner (Github).* > 2 votes --- Tags: org-mode ---
thread-63622
https://emacs.stackexchange.com/questions/63622
How to open multiple files from desktop in the same emacs session?
2021-02-26T23:37:02.307
# Question Title: How to open multiple files from desktop in the same emacs session? I use Pop OS 20.04 on my desktop. When I start Emacs on login, I run the command `(server-start)`. So when I open a file using the command `emacsclient <filename>` it opens it in the currently running emacs session. I love this. However, when I double click text files in the native file explorer a new Emacs session is started. How do I force all files to open in the same Emacs session? # Answer The details will depend on the particular file browser you're using, but you need to set the default program for opening text files to `emacsclient`, rather than `emacs`. > 1 votes --- Tags: server, session ---
thread-63521
https://emacs.stackexchange.com/questions/63521
Fetching email from multiple accounts via both Lieer (gmailieer) and isync with Notmuch
2021-02-22T02:07:39.607
# Question Title: Fetching email from multiple accounts via both Lieer (gmailieer) and isync with Notmuch I was wondering if I can use both isync and Lieer (gmailieer) at the same time to pull email from multiple Gmail and multiple non-Gmail accounts (each account being in a separate subdirectory in my mail directory which is where Notmuch resides)? I know I am asking this before trying but I have sensitive Email setup and I am worried I might mess things up. I really like having access to my Gmail tags, that's why I started using Lieer. I tried to fetching non-Gmail accounts through Lieer and it (maybe obviously) fails, that's why I am looking to use isync for other accounts. Is there anything I should be aware or careful about with regards to: a. Using both Lieer and isync at the same time? b. Having multiple accounts in such a setup (I am also using msmtp to send emails)? c. I am using Doom Emacs, is there anything to be done on that setup? Thank you! # Answer > 0 votes I figured this out. There was no problem doing that. The only thing to do is to add `mbsync -a` to pre-new hook for Notmuch. --- Tags: doom, notmuch ---
thread-63519
https://emacs.stackexchange.com/questions/63519
Replying to all recipients with Notmuch and msmtp
2021-02-22T01:08:56.363
# Question Title: Replying to all recipients with Notmuch and msmtp I have tested sending an email to multiple recipients with Notmuch through msmtp and it works. I can also copy all recipients of email to kill-ring (via `notmuch-show-stash-to`), no problem. However, when I reply all (with "R", actually "c R" since I am on Doom Emacs), the reply message is only addressed to one of the recipients, not all of them. Can anybody help me solve this problem? # Answer > 0 votes This was not a problem actually. I had listed all my accounts in Notmuch setup and I was testing by sending emails to myself. And it only sends an email to one of your accounts. I tried replying to an email with multiple recipients other than myself and it totally works. My only problem now is to figure out how to control which of my emails is used to send the reply, other than manually entering the correct email in the from header every time (and also adjusting the ... writes accordingly). --- Tags: doom, notmuch ---
thread-48561
https://emacs.stackexchange.com/questions/48561
Is there an X11-free build of Emacs that can run on Wayland (not going through XWayland)
2019-03-24T21:21:44.653
# Question Title: Is there an X11-free build of Emacs that can run on Wayland (not going through XWayland) I am running Wayland on Ubuntu 18.04. According to the Wayland FAX, one of it's advantages, compared to X11, is that > Wayland allows better isolation between processes: one window cannot access resources from, or inject keystrokes into, another window. That same Wayland document also says that > because Emacs is not a real GTK apps, it still talks with X11 and therefore will use XWayland where XWayland is described as: > Note that any X program will still run, as there is a XWayland server that provides backwards compatibility with X program. Those programs will not, however, benefit from the security and performance improvements Wayland provides. There is a 2016 devlevel discussion thread which considers removing X11 dependency from Emacs - notably a condition already achieved in Win23 and NS versions of Emacs. It's now 2019 and so my question is, as the title states: **Is there an X11-free build of Emacs that can run on Wayland (not going through XWayland)?** If the answer is no, I do have another question which is probably off topic for this list: **Why can't Wayland just intercept all X11 calls in XWayland and convert them into proper Wayland calls?** --- Edit Background Info: Apparently Electron (which the editor Atom uses to interface with Linux) has some X-call dependencies which require a setting `DISABLE_WAYLAND=1` causing it to run via XWayland when running on Wayland. Also see Arch docs on Wayland which suggests setting `GDK_BACKEND=x11` for Electron. So it's by no means an Emacs only issue. --- Edit: Clarification (c.f. @phils very helpful and through provoking comments) Wayland does intercept X11-calls, and of course Wayland-calls. However, the Wayland documention suggests only the Wayland calls enjoy the security benefits that Wayland has to offer. As @phils and @wasamasa point out, `emacs-nox` makes no X-calls, so it should theoretically be able to run on a terminal-emulator (e.g. *terminology*, *termite*) which itself is using only Wayland protocol, and not X-protocol. Testing that on Ubuntu has turned out not to simple, as even with a Wayland desktop on 18.04 it seems to use XWayland as the default. So the dual Wayland/X compatible *terminology* terminal emulator runs in X mode by default. From *terminology*: ``` ~$ echo $XDG_SESSION_TYPE x11 ``` --- FINISHED Emacs-nox runs well in Fedora 29 (personally ran it), and Fedora 29 doesn't support X at all. By default it seems to not share the system clipboard - the same as seen in emacs-nox on Ubuntu. But emacs-nox can be modified easily enough to work with @wasamasa' s answer below and custom emacs calls to external clipboardhere and here. # Answer > 3 votes There is no graphical Emacs build for Linux without X, no. As suggested in the commentary, you can use textual Emacs instead and customize the parts interacting with the clipboard to use wl-clipboard instead. # Answer > 11 votes As of early 2021, the previously accepted answer is no longer the case. **Emacs can now be ran in Wayland without XWayland.** Core Emacs code has been (quite labouriously!) updated to use pure GTK, and this should be available to the general public as of Emacs 28. For now, Arch Linux users can use the updated Emacs by switching to this AUR package. Other distributions may have similar luck by searching for "emacs pgtk" builds. For more information, see this news article. --- Tags: x11, build ---
thread-147
https://emacs.stackexchange.com/questions/147
How can I get a ruler at column 80?
2014-09-24T09:41:21.340
# Question Title: How can I get a ruler at column 80? As a programmer, I want to see a ruler at a specific column (usually 80), both so I see when I cross that column, but also to see how close I am getting to it so I can reformat my code early. The options I have found so far are all not achieving this goal: * `whitespace-mode`, `column-enforce-mode`, and `column-marker` only highlight individual rows after the text in the row has already passed the `fill-column`. I'd like to see when I am getting close to the column, not just when I cross it. * `fill-column-indicator` would be a good solution, except it breaks `auto-complete-mode`, `company-mode`, `avy`, and more. These are issues that seem hard to fix, each requiring an individual workaround -- e.g., see the `company-mode` issue and the `auto-complete-mode` issue, the latter over two years old). Are there any better alternatives? # Answer > 58 votes **Note that as of Emacs 27, you should probably use the built-in `display-fill-column-indicator-mode`, as noted by the newer answer from Basil.** `fill-column-indicator` is the most mature solution, and if you find overlay-based code with which it conflicts, you can add code to suspend `fci-mode` while the conflicting code is active. For example, the following code makes it work with `auto-complete`: ``` (defun sanityinc/fci-enabled-p () (symbol-value 'fci-mode)) (defvar sanityinc/fci-mode-suppressed nil) (make-variable-buffer-local 'sanityinc/fci-mode-suppressed) (defadvice popup-create (before suppress-fci-mode activate) "Suspend fci-mode while popups are visible" (let ((fci-enabled (sanityinc/fci-enabled-p))) (when fci-enabled (setq sanityinc/fci-mode-suppressed fci-enabled) (turn-off-fci-mode)))) (defadvice popup-delete (after restore-fci-mode activate) "Restore fci-mode when all popups have closed" (when (and sanityinc/fci-mode-suppressed (null popup-instances)) (setq sanityinc/fci-mode-suppressed nil) (turn-on-fci-mode))) ``` # Answer > 57 votes > Are there any better alternatives? Emacs 27 (officially released 2020-08-11) added support for a fill column indicator natively by way of the buffer-local minor mode `display-fill-column-indicator-mode` and its global counterpart `global-display-fill-column-indicator-mode` (see `(info "(emacs) Minor Modes")`). For example, you can enable it in most programming language modes by adding something like the following to your `user-init-file` (see `(info "(emacs) Hooks")`): ``` (add-hook 'prog-mode-hook #'display-fill-column-indicator-mode) ``` Here it is in action: Quoth `(info "(emacs) Displaying Boundaries")`: ``` 14.15 Displaying Boundaries =========================== Emacs can display an indication of the ‘fill-column’ position (see Fill Commands). The fill-column indicator is a useful functionality especially in ‘prog-mode’ and its descendants (see Major Modes) to indicate the position of a specific column that has some special meaning for formatting the source code of a program. To activate the fill-column indication display, use the minor modes ‘M-x display-fill-column-indicator-mode’ and ‘M-x global-display-fill-column-indicator-mode’, which enable the indicator locally or globally, respectively. Alternatively, you can set the two buffer-local variables ‘display-fill-column-indicator’ and ‘display-fill-column-indicator-character’ to activate the indicator and control the character used for the indication. Note that both variables must be non-‘nil’ for the indication to be displayed. (Turning on the minor mode sets both these variables.) There are 2 buffer local variables and a face to customize this mode: ‘display-fill-column-indicator-column’ Specifies the column number where the indicator should be set. It can take positive numerical values for the column, or the special value ‘t’, which means that the value of the variable ‘fill-column’ will be used. Any other value disables the indicator. The default value is ‘t’. ‘display-fill-column-indicator-character’ Specifies the character used for the indicator. This character can be any valid character including Unicode ones if the font supports them. The value ‘nil’ disables the indicator. When the mode is enabled through the functions ‘display-fill-column-indicator-mode’ or ‘global-display-fill-column-indicator-mode’, they will use the character specified by this variable, if it is non-‘nil’; otherwise Emacs will use the character ‘U+2502 VERTICAL LINE’, falling back to ‘|’ if ‘U+2502’ cannot be displayed. ‘fill-column-indicator’ Specifies the face used to display the indicator. It inherits its default values from the face ‘shadow’, but without background color. To change the indicator color, you need only set the foreground color of this face. ``` # Answer > 27 votes Here is one option which is more robust, it breaks almost nothing (occasionally company-mode being a noteworthy exception), but is not as convenient as `fill-column-indicator`. **Use header-line-format to mark the 80th column on the header.** Something like the following should suffice: ``` (setq-default header-line-format (list " " (make-string 79 ?-) "|")) ``` You should change the number of spaces in that first string depending on the size of your left fringe. But other than that, this should work reasonably well. It's not as convenient as a ruler in the actual buffer, but it helps. You can also set it to apply only on programming buffers. ``` (defun prog-mode-header-line () "Setup the `header-line-format' on for buffers." (setq header-line-format (list " " (make-string 79 ?-) "|"))) (add-hook 'prog-mode-hook #'prog-mode-header-line) ``` **Result:** You should get something like the following (the first line is not actually in the buffer, but in the header). ``` -------------------------------------------------------------------------------| ;; This is what your buffer should look like all the way up to column number 80. (setq some-dummy-variable we-are-all-friends) ``` # Answer > 22 votes After much suffering because of various bugs `fill-column-indicator` introduces, I eliminated it from my config for good. What I currently use is built-in Emacs functionality to highlight lines that are too long. This even looks better, I wouldn't enable `fill-column-indicator` now even if it were bug-free. For a start you may grab my setup: ``` (setq-default whitespace-line-column 80 whitespace-style '(face lines-tail)) ``` Then enable it where you want. I use it only in programming context: ``` (add-hook 'prog-mode-hook #'whitespace-mode) ``` # Answer > 9 votes *This EmacsWiki page* is about **Ruler Mode**, a minor mode that shows a ruler for columns at the top of a window. It also shows you the current column and the positions of `comment-column`, `fill-column`, `goal-column`, and the tab stops (as in `tab-stop-list`). And *this EmacsWiki page* is about a ruler that pops up on demand, then disappears. --- *This other EmacsWiki page* has lots of information about different ways to mark a particular column or otherwise let you know when you go past it. The one I use is Mode Line Position. But others include showing a vertical line at the column (Column Marker, Fill-Column Indicator) and using whitespace mode to highlight text that goes past the column. (If you need the line to be far to the right of all text in all rows, you can always turn on `picture-mode`, but that is probably useful here only as a temporary workaround.) See also Find Long Lines for ways to find long lines on demand. # Answer > 7 votes Not exactually what you want, but ruler like @Malabarba♦ will waster space, here is better solution: There is a built-in package in `emacs-goodies-el`(recommend to install it in terminal) called highlight-beyond-fill-column.el, add this to your `.emacs` or `init.el`: ``` (setq-default fill-column 80) (add-hook 'prog-mode-hook 'highlight-beyond-fill-column) (custom-set-faces '(highlight-beyond-fill-column-face ((t (:foreground "red" ))))) ``` The text beyond `fill-column` which is 80 in the snippet will be highlighted with the color of `red`. You can set the face as you like. # Answer > 1 votes Since `fill-column-indicator` is quite heavy, this solution shows a character to the right of the current line. So when you're typing you can see the line limit before you exceed it. This defines the minor-mode `hl-line-margin-mode`: ``` ;; Global, ensures one active margin for the active buffer. (defvar hl-line-margin--overlay nil) (defun hl-line-margin--overlay-clear () "Clear the overlays." (when hl-line-margin--overlay (delete-overlay hl-line-margin--overlay) (setq hl-line-margin--overlay nil))) (defun hl-line-margin--overlay () "Create the line highlighting overlay." ;; Remove in the event of a changed buffer, ;; ensures we update for a modified fill-column. (when (and hl-line-margin--overlay (not (eq (current-buffer) (overlay-buffer hl-line-margin--overlay)))) (hl-line-margin--overlay-clear)) (unless hl-line-margin--overlay (setq hl-line-margin--overlay (make-overlay 0 0)) (let ((space `((space :align-to ,fill-column) (space :width 0)))) (overlay-put hl-line-margin--overlay 'after-string (concat (propertize " " 'display space 'cursor t) (propertize " " 'face '(:inverse-video t)))))) (let ((eol (line-end-position))) (unless (eql eol (overlay-start hl-line-margin--overlay)) (move-overlay hl-line-margin--overlay eol eol)))) (defun hl-line-margin-mode-enable () "Turn on `hl-line-margin-mode' for the current buffer." (add-hook 'post-command-hook #'hl-line-margin--overlay nil t)) (defun hl-line-margin-mode-disable () "Turn off `hl-line-margin-mode' for the current buffer." (hl-line-margin--overlay-clear) (remove-hook 'post-command-hook #'hl-line-margin--overlay t)) ;;;###autoload (define-minor-mode hl-line-margin-mode "Show a character at the fill column of the current line." :lighter "" (cond (hl-line-margin-mode (jit-lock-unregister #'hl-line-margin-mode-enable) (hl-line-margin-mode-enable)) (t (jit-lock-unregister #'hl-line-margin-mode-disable) (hl-line-margin-mode-disable)))) ``` If you use `evil-mode` and want to limit this to insert mode you can add the following hooks: ``` (add-hook 'evil-insert-state-entry-hook #'hl-line-margin-mode-enable) (add-hook 'evil-insert-state-exit-hook #'hl-line-margin-mode-disable) ``` # Answer > 1 votes In Spacemacs this functionality is easily toggled using `SPC t f`. I'm not sure exactly how it is implemented but Spacemacs seems to use the `fill-column-indicator` package (defined in the `.emacs.d/layers/+source-control/git/packages.el` file). Spacemacs also implements company and avy, I'm not sure if the `fill-column-indicator` breaks anything there. Anyway for ease of configuration it is worth to take a look at Spacemacs # Answer > 1 votes ### Updated Answer Since *Emacs 27*, use `display-fill-column-indicator-mode`. In practice, one may utilize it by **toggling the mode** with a custom keybinding, like shown below: ``` ;; Mnemonics: `b' Buffer, `i' Indicator (of fIll). (global-set-key (kbd "C-c b i") #'display-fill-column-indicator-mode) ``` Or enable the mode **for particular `major-mode`**, for instance: ``` (defun my-message-mode () ;; Optional check for earlier Emacs versions. (when (fboundp 'display-fill-column-indicator-mode) (display-fill-column-indicator-mode 1))) (add-hook 'message-mode-hook 'my-message-mode) ``` Or **enable it globally** (in all buffers) with: ``` (global-display-fill-column-indicator-mode 1) ``` ### Initial Answer Probably one of the simplest ways that could be enough in many cases, is to use column-number-mode. With this mode enabled, the current column number is shown in the **mode line**. This mode does not display a ruler, but provides information that is essentially needed in the first place. Arguably, this prevents a buffer from cluttering. To enable the mode in your `user-init-file`, use ``` (column-number-mode) ``` Example screenshot with the column number shown in the mode line: --- Tags: display, font-lock, programming ---
thread-12459
https://emacs.stackexchange.com/questions/12459
Save buffer at each modification
2015-05-17T03:16:15.983
# Question Title: Save buffer at each modification I'd like to know if it is possible the buffer is saved at the exact moment of modification; at the instant of the key up event. # Answer ``` (defun my-instant-save-buffer (eins zwei drei) "To be hooked into list `after-change-functions' `after-change-functions' expects functions receiving three arguments. Arguments are ignored here, but slots needed by add-hook" (save-buffer)) (add-hook 'after-change-functions 'my-instant-save-buffer) ``` > 11 votes # Answer I had the same requirement and auto-save feature of emacs hasn't worked well for me because it can't addadvice to c functions. So, I wrote a package real-auto-save for that. It is available on melpa. You can install it by ``` M-x package-install RET real-auto-save ``` and in your config you can add ``` (require 'real-auto-save) (add-hook 'prog-mode-hook 'real-auto-save-mode) (setq real-auto-save-interval 1) ;; in seconds ``` After every second, if your buffer is modified, it will be saved automatically. If you specifically want to save after key up event, you can write a lisp function for that. > 7 votes # Answer You can enable `auto-save-mode`, so Emacs automatically saves your current buffer in a different file. Then, add this function to `auto-save-hook` to also write it directly on the actual file you are editing: ``` (defun save-buffer-if-visiting-file (&optional args) "Save the current buffer only if it is visiting a file" (interactive) (if (and (buffer-file-name) (buffer-modified-p)) (save-buffer args))) (add-hook 'auto-save-hook 'save-buffer-if-visiting-file) ``` According to the Emacs manual on auto-save control: > The variable auto-save-interval specifies how many characters there are between auto-saves. By default, it is 300. Emacs doesn’t accept values that are too small: if you customize auto-save-interval to a value less than 20, Emacs will behave as if the value is 20. So, if you want Emacs to save for every key press, change `auto-save-interval` to `1`: ``` (setq auto-save-interval 1) ``` > 3 votes # Answer It's a little bit elaborated version of @andreas-röhler's answer somewhat adressing @NickD comment. Saves after 50 milliseconds of inactivity and rapid buffer changes would not cause tons of savings. ``` (let ((timeout 0.05) (timers-alist nil)) (cl-flet* ((get-timer (key) (cdr (assoc key timers-alist))) (set-timer (key timer) (push (cons key timer) timers-alist)) (drop-timer (key) (setq timers-alist (assoc-delete-all key timers-alist))) (save-buffer-and-drop-timer (buffer) (with-current-buffer buffer (progn (save-buffer) (drop-timer buffer)))) (save-buffer-deffered (buffer) (unless (get-timer buffer) (set-timer buffer (run-with-idle-timer timeout nil #'save-buffer-and-drop-timer buffer))))) (defun save-file-buffer-deffered (&rest args) (if (buffer-file-name) (save-buffer-deffered (current-buffer)))))) (add-hook 'after-change-functions 'save-file-buffer-deffered) ``` > 0 votes --- Tags: auto-save ---
thread-45490
https://emacs.stackexchange.com/questions/45490
changing display function in define-word package
2018-10-21T19:13:50.517
# Question Title: changing display function in define-word package How to replace the displayfn from `message` to a function which displays the result in a temporary window? (I have limited knowledge of elisp.) # Answer To give a bit of context, `define-word` is an Emacs mode which provides dictionary definitions given a word \[1\]. By default it sends its output to the `messages` buffer, but it provides an overridable display function. Here's my solution to redirect the output, which is by no means an "advanced" one. First, based on the answer by choroba, I defined my display function like so: ``` (defun my/display-word (&rest args) "Create a buffer for display word instead of using messages." (interactive) (let ((buffer (generate-new-buffer "Define Word"))) (set-buffer buffer) (set-buffer-major-mode buffer) (apply 'insert args) (display-buffer buffer)) ) ``` Then I copied the code from Henrik Lissner's config \[2\], which loops through all available services and adds them to the alist: ``` (setq define-word-displayfn-alist (cl-loop for (service . _) in define-word-services collect (cons service #'my/display-word))) ``` The end result is as follows: If you are interested in the details of my investigation, please see the ticket I raised against the project \[3\]. **Update 1** Actually, I found the creation of many buffers quite annoying so I updated the function to this: ``` (defun my/display-word (&rest args) "Create a buffer for display word instead of using messages." (interactive) (let ((buffer (get-buffer-create "Define Word"))) (set-buffer buffer) (erase-buffer) (set-buffer-major-mode buffer) (apply 'insert args) (display-buffer buffer)) ) ``` \[1\] define-word GitHub repo \[2\] Henrik Lissner's config \[3\] #29: Redefining display function to output to a buffer instead of messages > 1 votes # Answer Instead of ``` (message "ahoy") ``` create a new buffer, switch to it and insert the message there: ``` (progn (switch-to-buffer (generate-new-buffer "message")) (insert "ahoy")) ``` > 0 votes --- Tags: message, popup ---
thread-63621
https://emacs.stackexchange.com/questions/63621
How do I solve `Lisp error: (void-function -compose)` when using lsp-dart?
2021-02-26T23:19:30.450
# Question Title: How do I solve `Lisp error: (void-function -compose)` when using lsp-dart? When I load a Dart file with GNU Emacs 27.1-1 for OS X I get the following little error novel. ``` Debugger entered--Lisp error: (void-function -compose) (-compose #'lsp--client-path->uri-fn #'lsp--workspace-client) (-keep (-compose #'lsp--client-path->uri-fn #'lsp--workspace-client) (lsp-workspaces)) (cl-first (-keep (-compose #'lsp--client-path->uri-fn #'lsp--workspace-client) (lsp-workspaces))) (and t (cl-first (-keep (-compose #'lsp--client-path->uri-fn #'lsp--workspace-client) (lsp-workspaces)))) (let* ((uri-fn (and t (cl-first (-keep (-compose #'lsp--client-path->uri-fn #'lsp--workspace-client) (lsp-workspaces)))))) (if uri-fn (funcall uri-fn path) (lsp--path-to-uri-1 path))) lsp--path-to-uri("/Users/sam/.emacs.d/index.sqlite") (closure (t) nil (lsp--path-to-uri (f-join user-emacs-directory "index.sqlite")))() funcall((closure (t) nil (lsp--path-to-uri (f-join user-emacs-directory "index.sqlite")))) eval((funcall #'(closure (t) nil (lsp--path-to-uri (f-join user-emacs-directory "index.sqlite"))))) custom-initialize-reset(lsp-serenata-index-database-uri (funcall #'(closure (t) nil (lsp--path-to-uri (f-join user-emacs-directory "index.sqlite"))))) custom-declare-variable(lsp-serenata-index-database-uri (funcall #'(closure (t) nil (lsp--path-to-uri (f-join user-emacs-directory "index.sqlite")))) "The location to store the index database.\nNote tha..." :group lsp-serenata :type file) eval-buffer(#<buffer *load*> nil "/Users/sam/.emacs.d/elpa/lsp-mode-20210222.1457/lsp..." nil t) ; Reading at buffer position 12399 load-with-code-conversion("/Users/sam/.emacs.d/elpa/lsp-mode-20210222.1457/lsp..." "/Users/sam/.emacs.d/elpa/lsp-mode-20210222.1457/lsp..." t t) require(lsp-php nil t) (if (featurep package) nil (require package nil t)) (closure (company-mode cl-struct-lsp--log-entry-tags cl-struct-lsp-session-tags cl-struct-lsp--workspace-tags cl-struct-lsp--registered-capability-tags lsp-mode-menu cl-struct-lsp--folding-range-tags cl-struct-lsp-watch-tags cl-struct-lsp--client-tags lsp--log-lines dap-ui-menu-items company-backends t) (package) (if (featurep package) nil (require package nil t)))(lsp-php) mapc((closure (company-mode cl-struct-lsp--log-entry-tags cl-struct-lsp-session-tags cl-struct-lsp--workspace-tags cl-struct-lsp--registered-capability-tags lsp-mode-menu cl-struct-lsp--folding-range-tags cl-struct-lsp-watch-tags cl-struct-lsp--client-tags lsp--log-lines dap-ui-menu-items company-backends t) (package) (if (featurep package) nil (require package nil t))) (ccls lsp-actionscript lsp-ada lsp-angular lsp-bash lsp-clangd lsp-clojure lsp-cmake lsp-crystal lsp-csharp lsp-css lsp-dart lsp-dhall lsp-dockerfile lsp-elm lsp-elixir lsp-erlang lsp-eslint lsp-fortran lsp-fsharp lsp-gdscript lsp-go lsp-hack lsp-groovy lsp-haskell lsp-haxe lsp-java lsp-javascript lsp-json lsp-kotlin lsp-lua lsp-nim lsp-nix lsp-metals lsp-ocaml lsp-perl lsp-php lsp-pwsh lsp-pyls lsp-python-ms lsp-purescript lsp-r lsp-rf lsp-rust lsp-solargraph lsp-sorbet lsp-tex lsp-terraform lsp-vala lsp-verilog ...)) seq-do((closure (company-mode cl-struct-lsp--log-entry-tags cl-struct-lsp-session-tags cl-struct-lsp--workspace-tags cl-struct-lsp--registered-capability-tags lsp-mode-menu cl-struct-lsp--folding-range-tags cl-struct-lsp-watch-tags cl-struct-lsp--client-tags lsp--log-lines dap-ui-menu-items company-backends t) (package) (if (featurep package) nil (require package nil t))) (ccls lsp-actionscript lsp-ada lsp-angular lsp-bash lsp-clangd lsp-clojure lsp-cmake lsp-crystal lsp-csharp lsp-css lsp-dart lsp-dhall lsp-dockerfile lsp-elm lsp-elixir lsp-erlang lsp-eslint lsp-fortran lsp-fsharp lsp-gdscript lsp-go lsp-hack lsp-groovy lsp-haskell lsp-haxe lsp-java lsp-javascript lsp-json lsp-kotlin lsp-lua lsp-nim lsp-nix lsp-metals lsp-ocaml lsp-perl lsp-php lsp-pwsh lsp-pyls lsp-python-ms lsp-purescript lsp-r lsp-rf lsp-rust lsp-solargraph lsp-sorbet lsp-tex lsp-terraform lsp-vala lsp-verilog ...)) (progn (seq-do #'(lambda (package) (if (featurep package) nil (require package nil t))) lsp-client-packages) (setq lsp--client-packages-required t)) (if (and lsp-auto-configure (not lsp--client-packages-required)) (progn (seq-do #'(lambda (package) (if (featurep package) nil (require package nil t))) lsp-client-packages) (setq lsp--client-packages-required t))) lsp--require-packages() lsp() run-hooks(change-major-mode-after-body-hook prog-mode-hook dart-mode-hook) apply(run-hooks (change-major-mode-after-body-hook prog-mode-hook dart-mode-hook)) run-mode-hooks(dart-mode-hook) dart-mode() set-auto-mode-0(dart-mode nil) set-auto-mode() normal-mode(t) after-find-file(nil t) find-file-noselect-1(#<buffer main.dart> "~/sam/flutter/proj9/lib/main.dart" nil nil "~/sam/flutter/proj9/lib/main.dart" (15751399 16777223)) find-file-noselect("/Users/sam/flutter/proj9/lib/mai..." nil nil nil) find-file("/Users/sam/flutter/proj9/lib/mai...") dired-find-file() funcall-interactively(dired-find-file) call-interactively(dired-find-file nil nil) command-execute(dired-find-file) ``` How do I solve `Lisp error: (void-function -compose)` when using lsp-dart? # Answer > 4 votes By chance, after commenting on this, hours later I ran into exactly the same issue. The cause was that spacemacs had for a while pinned its version of dash at 2.17.0, and `-compose` was introduced in 2.18.0 (moved over from the now obsolete package `dash-functional`). The latest lsp-mode.el uses that function. I fixed it by updating my spacemacs checkout to the latest on branch `develop`. I suspect the issue was fixed for me by https://github.com/syl20bnr/spacemacs/commit/ae65f3cedd7328b7f346f01e4597979671d67f5a --- Tags: debugging, use-package, package-repositories, lsp-mode, dash.el ---
thread-59474
https://emacs.stackexchange.com/questions/59474
prettify-symbols-mode enabled for major mode, but ligatures don't show until toggling prettify on and off
2020-07-05T21:09:23.330
# Question Title: prettify-symbols-mode enabled for major mode, but ligatures don't show until toggling prettify on and off I'm pretty new to emacs and giving it a shot because it seems to be much better integrated with the OCaml tool chain than any other editor. Since OCaml uses a lot of symbols, I want to enable ligature support. If it's relevant, I'm using spacemacs. Here's what I've added to my `dotspacemacs/user-config()` ``` (load "~/.emacs.d/private/local/pragmatapro-prettify-symbols-v0.828.el") (add-hook 'tuareg-mode-hook #'prettify-hook) (global-prettify-symbols-mode t) ``` The `.el` file I'm using is available here for reference and defines `prettify-hook`. The strange thing is that after opening a `.ml` file in Tuareg mode, I can see that prettify-symbols-mode is active, but none of the symbols are converted to ligatures. However, if I toggle prettify-symbols-mode off and then back on, the symbols render correctly. Has anyone else had this issue or have any ideas how I can get it to work automatically upon opening a the file? **Edit:** So, interestingly enough, after looking again it seems like some sort of symbol replacement is happening, but it isn't happening with the correct glyphs or for all of the patterns defined in the .el file. For example \<= is replaced with a reasonable, but incorrect glyph; |\> is not replaced at all. After toggling the mode I end up with the correct replacement glyphs. See the answers section for the solution I came up with. # Answer > 0 votes I came up with a working solution after fiddling around and figuring out the information I edited into the original question. I'm not sure if this is the best approach, but it resolved my issue. After these changes the correct ligatures are displayed within OCaml's Tuareg mode automatically. First, I deleted ``` (global-prettify-symbols-mode t) ``` from my config file. I'm not 100% sure if this is necessary, but since I only want ligatures in Tuareg mode it seemed cleaner not to enable them globally. Secondly, I added a function to toggle `prettify-symbols-mode` off and on in the `.el` file I linked above and added it to the `prettify-hook` that runs when Tuareg mode is activated. I'm still not sure why this is necessary, but it does the trick. ``` (defun refresh-pretty () (prettify-symbols-mode -1) (prettify-symbols-mode +1)) ;; main hook fn (defun prettify-hook () (add-pragmatapro-prettify-symbols-alist) (setup-compose-predicate) (refresh-pretty)) ``` # Answer > 0 votes I have the same problem, and I'm not sure if this is the *correct* way to work with it, but it does work for me. I believe the problem is one of hook order. Because `prettify-symbols-alist` is buffer local, you either have to `setq-default` it or have it set via some hook when a buffer is opened. The latter should be the preferred way to do it, as different languages have different ideas of what symbols mean; you probably don't want "and" rendered as "∧" in `text-mode`. So, given that: 1. `prettify-symbols-alist` is buffer-local (ideally), and, 2. `prettify-symbols-mode` only looks at `prettify-symbols-alist` once, when it starts you have to ensure that step 1 happens before step 2. I have two solutions: 1. Use `(global-prettify-symbols-mode 1)` in your `.emacs` (or equivalent). Then set up the `prettify-symbols-alist` in your programming hook: ``` (defun bjc/lisp-mode-hook () "Hook when entering ‘lisp-mode’." (mapc (lambda (elt) (push elt prettify-symbols-alist)) '(("<=" . ?≤) (">=" . ?≥) ("and" . ?∧) ("or" . ?∨) ("xor" . ?⊕) ("->" . ?→) ("<-" . ?←)))) (global-prettify-symbols-mode 1) (add-hook 'emacs-lisp-mode-hook 'bjc/lisp-mode-hook) ``` 2. Arrange to have `prettify-symbols-mode` called *after* your particular major mode hook. The easiest way to do this is to simply call it from the hook that sets up `prettify-symbols-alist`: ``` (defun bjc/lisp-mode-hook () "Hook when entering ‘lisp-mode’." (mapc (lambda (elt) (push elt prettify-symbols-alist)) '(("<=" . ?≤) (">=" . ?≥) ("and" . ?∧) ("or" . ?∨) ("xor" . ?⊕) ("->" . ?→) ("<-" . ?←))) (prettify-symbols-mode 1)) ``` Personally, I've gone with the former, because it seems cleaner to me, but YMMV. --- Tags: spacemacs, prettify-symbols-mode ---
thread-63652
https://emacs.stackexchange.com/questions/63652
Woes with installing and loading s.el
2021-03-01T03:11:55.490
# Question Title: Woes with installing and loading s.el I'm running Emacs 27.1(9.0) on OSX 11.2.2 and have failed at installing and configuring the package `s.el` from https://github.com/magnars/s.el/ Here's a list of things that I tried: 1. Copied `s.el` into `~/.emacs.d/elisp/` 2. Added `(add-to-list 'load-path "/Users/username/.emacs.d/lisp")` \# replace `username` with actual username 3. Verified that emacs does not complain when loading. Running `M-x s-trim-<TAB>` does **not** show any of the functions in `s.el`. 4. From the mini-buffer, loaded the file using `M-x load-file` and then typing `/Users/username/.emacs.d/lisp/s.el` \- no errors observed here. However, `M-x s-trim<TAB>` does not display any functions in `s.el` 5. Opened up `s.el` in emacs, selected the first function `s-trim-right` and evaluated it with `C-x C-e`. Even though it evaluated without errors, `M-x s-trim<TAB>` does not list this function. 6. Repeat steps 1-5 from terminal by launching emacs with `emacs --debug-init` I'm totally lost on how to get this working. The github page https://github.com/magnars/s.el/ says that the package can be installed by running `M-x package-install s`. However, `M-x package-install` does **not** list `s` as a valid package name. I only see a list of packages that have the letter `s` in their names. # Answer > 3 votes You have loaded s.el properly. The functions you are trying to call aren't interactive, what we call 'commands' in elisp. You can only call them from elisp code, they don't work with M-x. --- Tags: package ---
thread-975
https://emacs.stackexchange.com/questions/975
Getting number of occurrences, during incremental search (C-s / isearch-forward)
2014-10-09T20:47:49.633
# Question Title: Getting number of occurrences, during incremental search (C-s / isearch-forward) Inspired by modern browsers, I'd love to be able to see *how* many occurrences there are of some string, when I search for it – like the "10 of 37" at the top-right corner of the screenshot below. Is there a way of getting this in Emacs? Presumably, so as to not be slow, it should run only after some idle time. # Answer The `anzu` package does that. > anzu.el provides a minor mode which displays current match and total matches information in the mode-line in various search modes. > 15 votes # Answer Here are some possibilities that aren't very slick, that have the advantage of working with a stock Emacs. If you press `M-s o` (`isearch-occur`) during an incremental search, an Occur buffer pops up with the current search expression. At the top of the `*Occur*` buffer is the number of matching lines. The command `how-many` displays the number of occurrences of a regexp (including repeated occurrences). Unfortunately it isn't integrated with incremental search. Here's a proof-of-concept isearch integration: press `M-s #` during isearch to show the number of matches. ``` (defun isearch-how-many (regexp) "Run `how-many' using the last search string as the regexp. Interactively, REGEXP is constructed as with `isearch-occur'." (interactive (list (cond ((functionp isearch-word) (funcall isearch-word isearch-string)) (isearch-word (word-search-regexp isearch-string)) (isearch-regexp isearch-string) (t (regexp-quote isearch-string))))) (how-many regexp nil nil (interactive-p))) (define-key isearch-mode-map [?\M-s ?#] 'isearch-how-many) ``` > 14 votes # Answer As of emacs 27.1, this is now built-in to `isearch`. To turn on: ``` (setq isearch-lazy-count t) ``` To compare with anzu, the count is shows in the minibuffer prompt, rather than the modeline. See the manual for details. > 9 votes # Answer I would like to suggest Swiper! > Swiper is an alternative to isearch that uses ivy to show an overview of all matches. > 3 votes # Answer One possibility that requires no package at all is `M-x` `count-matches` (or, similarly, and also very expressive, `M-x` `how-many`). It works with both strings and regular expressions! > 2 votes --- Tags: search ---
thread-63644
https://emacs.stackexchange.com/questions/63644
Left-align equation previews (Auctex)
2021-02-28T17:55:49.707
# Question Title: Left-align equation previews (Auctex) I would like to left-align equations in Auctex's preview's generated by preview-latex. I imagine that this would involve putting `fleqn` in the `documentclass` options in whatever latex file things are generated from. How can I do this? I have tried to find this location but have not had much success. # Answer What about using `align`? You can use `align` as follows, ``` \begin{align} x &= y + z\\ \beta &= \alpha\gamma \end{align} ``` > 0 votes --- Tags: latex, auctex, preview-latex ---
thread-63405
https://emacs.stackexchange.com/questions/63405
Read only mode in mu4e
2021-02-14T20:42:37.543
# Question Title: Read only mode in mu4e Is there a "read only mode" in mu4e? I recently had the case to use mu4e to read emails from a system using thunderbird with maildir. I noticed that for example a file called `somemessage.eml` was renamed by mu4e to `somemessage.eml:2,S`. Then I noticed that thunderbird couldn't read this message anymore. After renaming it back, thunderbird was able to read it again. So, is there a way to prevent mu4e to interfer with thunderbird in this case, for example by setting it into a read only mode? # Answer I figured out a solution by doing it just on os level. Using bindfs you could create a "read only" view to the maildir. For example if your maildir is `~/maildir` create an empty directory `~/maildir_ro` and then do ``` bindfs --perms=a-w .maildir .maildir_ro ``` Then change `~/maildir` to `~/maildir_ro` in your init file for mu4e as well. > 1 votes --- Tags: mu4e, read-only-mode ---
thread-63646
https://emacs.stackexchange.com/questions/63646
How can I make a theme use particular face attributes for a given face in a single buffer?
2021-02-28T20:00:50.287
# Question Title: How can I make a theme use particular face attributes for a given face in a single buffer? I'm loading a `deftheme` theme using `(load-theme)`. I'm very happy with it most cases, but in `yaml-mode` I'd like to change attributes for `font-lock-variable-name-face`. How can I make the theme use different face attributes for it in a single buffer? # Answer > 0 votes As @lawlist suggested I used `face-remap-add-relative` to achieve the required effect: ``` (add-hook 'yaml-mode-hook (lambda () (face-remap-add-relative 'font-lock-variable-name-face :foreground "#fec66c"))) ``` --- Tags: faces, themes ---
thread-63660
https://emacs.stackexchange.com/questions/63660
Unable to let emms understand metadata
2021-03-01T10:14:55.027
# Question Title: Unable to let emms understand metadata I don't understand why all my music artist/genre/album *etc.* are classified under misc/unknown given the fact that I'm confident that 90% of 200G music do have metadata. I managed to get the source of `emms-print-metadata` and installed it, tested it on an `mp3` and it does return a result. I have the following configuration. There is nothing special: I just followed the documentation and tweaked a bit to use `mpv` as default player. ``` (use-package emms :ensure t :requires (emms-setup emms-player-mpv) :config (emms-all) (setq emms-player-list '(emms-player-mpv) emms-browser-covers 'emms-browser-cache-thumbnail-async emms-source-file-default-directory "~/Music/" emms-info-functions '(emms-info-libtag) emms-player-mpv-parameters '("--really-quiet" "--no-video")) (when (executable-find "emms-print-metadata") (require 'emms-info-libtag) (add-to-list 'emms-info-functions 'emms-info-libtag))) ``` **Question.** How to let `emms` understand metadata and display them correctly in `emms-browser-search-by-*` buffers ? # Answer > 1 votes Try resetting the cache `M-x emms-cache-reset` and then re-importing your music `M-x emms-add-directory-tree`. Then `emms-info-libtag` will cook away in the background for a bit and, after a few minutes, you should see your metadata. --- Tags: emms ---
thread-63534
https://emacs.stackexchange.com/questions/63534
In latex-mode is it possible to disable auto-fill-mode in between `\begin{figure}, \end{figure}`
2021-02-22T16:33:27.967
# Question Title: In latex-mode is it possible to disable auto-fill-mode in between `\begin{figure}, \end{figure}` I am working on `tex` files with `LaTeX-mode`. If possible, I want to use `auto-fill-mode` in some conditions. I was wondering is it possible to disable it in between some patterns like: ``` \begin{figure}[ht] … \end{figure} ``` where I want to apply `auto-fill-mode` only for pure text? and not apply it under `\begin{figure} ... \end{figure}` or any matematical formula notations. # Answer You can do this by defining your own `auto-fill-function`, and configuring LaTeX mode to use that: ``` ;; define environments we don't want to autofill: (defvar unfillable-envs '("figure")) ;; add more environments if you like, eg: ;; (defvar unfillable-envs '("figure" "tikzpicture")) ;; create a function to check the environment first, then fill: (defun my-filtered-fill () (unless (member (LaTeX-current-environment) unfillable-envs) (do-auto-fill))) ;; setup LaTeX/AucTex to use auto-fill-mode, but with our fill-function: (defun my-tex-auto-fill () (auto-fill-mode) (setq auto-fill-function 'my-filtered-fill)) (add-hook 'LaTeX-mode-hook 'my-tex-auto-fill) ``` Note that you can add different environments to `unfillable-envs` if you want to block filling in other places. You could accomplish the same thing by advising the fill function, but that can lead to unexpected problems if you're not careful. > 4 votes --- Tags: latex ---
thread-63666
https://emacs.stackexchange.com/questions/63666
Set auto-fill in markdown mode, but exclude code block headers
2021-03-01T17:55:38.757
# Question Title: Set auto-fill in markdown mode, but exclude code block headers I want to use `auto-fill-mode` in Markdown files. By default, it works fine, with one exception. I'm using the RMarkdown variant of markdown. This requires that code block headers remain on one line. They are frequently much longer than my fill-column, so if I use `auto-fill`, they get wrapped. How can I exclude these lines from getting filled? # Answer `auto-fill-mode` refers to the variable `auto-fill-function` to determine how to fill lines. `auto-fill-function` is always a local variable, making it easy to define your own function for any mode you like. To solve my own problem, I use the following: <pre><code>(defun tws-markdown-auto-fill () (auto-fill-mode) (setq auto-fill-function 'tws-markdown-fill-function)) (defun tws-markdown-fill-function () (unless (save-excursion (beginning-of-line) (looking-at "```{")) (do-auto-fill))) (add-hook 'markdown-mode-hook 'tws-markdown-auto-fill) </code></pre> > 0 votes --- Tags: markdown-mode, auto-fill-mode ---
thread-63662
https://emacs.stackexchange.com/questions/63662
File-local variables not parsed in lilypond file
2021-03-01T13:20:53.853
# Question Title: File-local variables not parsed in lilypond file I have a `definitions.ly` file that ends with the following: ``` %%% Local Variables: %%% LilyPond-master-file: "score.ly" %%% End: ``` However, the value of `LilyPond-master-file` is still `nil` when I visit the file. If I do `M-: RET (inibit-local-variables-p) RET` I get `nil`. If I save the exact same file with a different extension (eg. `.foo`), emacs asks me (upon loading) if I want to set the unsafe variable, as expected. I've tried using a directory-local variable, but it doesn't work either. I've tried setting another variable, like `fill-column`, using the snippet above, in the same file, without success. Maybe there's something in lilypond-mode preventing the parsing of local variables? I'm out of ideas and I don't know how to debug this... # Answer > 1 votes I can reproduce this and it's probably a bug, but `lilypond-mode.el` (at least my version of it) is very old and has not seen much updating. Not even sure where to report the bug. As a workaround however, you can do it in the mode hook: ``` (defun ndk/lilypond-mode-prep () (hack-local-variables) ;; maybe other stuff ) (add-to-hook 'LilyPond-mode-hook #'ndk/lilypond-mode-prep) ``` --- Tags: file-local-variables, lilypond ---
thread-63664
https://emacs.stackexchange.com/questions/63664
Filtering list of files to those recently edited
2021-03-01T16:36:39.313
# Question Title: Filtering list of files to those recently edited Suppose I have a list of files: ``` (setq files '("/path/to/file1" ...)) ``` Is there a way to reduce this list to only those files which were edited within the past, say, 10 days? # Answer > 1 votes > Is there a way to reduce this list to only those files which were edited within the past, say, 10 days? Something like this? It assumes Emacs 26+, but to support earlier versions you can easily replace `(file-attribute-modification-time ...)` with `(nth 5 ...)`, `seq-filter` with other ways of filtering lists, the `nil` argument to `time-subtract` with `(current-time)`, etc. ``` (autoload 'seq-filter "seq") (defun my-files-since (files days) "Return subset of FILES modified within the last DAYS." (let ((since (time-subtract nil (days-to-time days)))) (seq-filter (lambda (file) (let* ((attrs (file-attributes file)) (mtime (file-attribute-modification-time attrs))) (time-less-p since mtime))) files))) (my-files-since '("/path/to/foo" "bar" ...) 10) ``` References: --- Tags: files, time-date ---
thread-63659
https://emacs.stackexchange.com/questions/63659
In dired how can I omit executables?
2021-03-01T07:48:07.317
# Question Title: In dired how can I omit executables? On Linux/macOS, using `omit-mode` in Dired is there a way to omit executables? Executables are files which have the Unix executable flag set and are then listed via `ls -lF` with an `*` after the filename. **Note:** I do know how to *colorise* executables in Dired: Via the diredful package (install from melpa) it is easy to setup a rule for this. Diredful can colorioser dried entries according to the full ls line (including the `*` character for executables). - I am wondering whether something like this is possible for omitting as well. # Answer > 1 votes `dired-omit-mode`, as currently defined, looks only at the (relative) file name. It does not look at the permission bits. You would need to define a mode that (1) does first what `dired-omit-mode` does - match file names and omit them, and (2) then matches the `x` permission bits at the beginning of the file line. The second is a separate operation because `dired-omit-expunge`, which does the work of `dired-omit-mode`, matches a regexp against only the file names. The regexp to use, to match the `x` permission bits, is the value of variable `dired-re-exe`. But again, you need to match that against the full line, not just the file name. --- This should do the trick: `M-x my-dired-omit-mode`. These are just `dired-omit-mode` and `dired-omit-expunge`, but tweaked to also omit executables. ``` (defcustom diredp-omit-line-regexp dired-re-exe "Regexp matching lines to be omitted. This has effect only when `dired-omit-mode' is non-nil See command `my-dired-omit-mode' (\\[my-dired-omit-mode]). The default regexp matches lines for executable files." :type 'regexp :group 'dired-x) (define-minor-mode my-dired-omit-mode "Toggle omission of uninteresting files in Dired (Dired-Omit mode). With a prefix argument ARG, enable Dired-Omit mode if ARG is positive, and disable it otherwise. If called from Lisp, enable the mode if ARG is omitted or nil. My-Dired-Omit mode is a buffer-local minor mode. When enabled in a Dired buffer, Dired does not list files whose filenames match regexp `dired-omit-files', files ending with extensions in `dired-omit-extensions', or files on lines matching `diredp-omit-line-regexp'. To enable omitting in every Dired buffer, you can put this in your init file: (add-hook \\='dired-mode-hook (lambda () (dired-omit-mode))) See Info node `(dired-x) Omitting Variables' for more information." nil nil nil (if (not my-dired-omit-mode) (revert-buffer) (let ((dired-omit-size-limit nil)) (my-dired-omit-expunge) ;; THIS omits lines with an executable file. (my-dired-omit-expunge diredp-omit-line-regexp t)))) ;; Added optional arg LINEP. ;; (defun my-dired-omit-expunge (&optional regexp linep) "Erases all unmarked files whose names match REGEXP. Does nothing if global variable `my-dired-omit-mode' is nil, or if called non-interactively and buffer is bigger than `dired-omit-size-limit'. If REGEXP is nil or not specified, use `dired-omit-files', and also omit filenames ending in `dired-omit-extensions'. If REGEXP is the empty string, this function is a no-op. With a prefix arg (non-nil LINEP when called from Lisp), match REGEXP against the whole line, not just the file name. This temporarily binds `dired-marker-char' to `dired-omit-marker-char' and calls `dired-do-kill-lines'." (interactive "sOmit files (regexp): \nP") (if (and my-dired-omit-mode (or (called-interactively-p 'interactive) (not dired-omit-size-limit) (< (buffer-size) dired-omit-size-limit) (progn (when dired-omit-verbose (message "Not omitting: directory larger than %d characters." dired-omit-size-limit)) (setq my-dired-omit-mode nil) nil))) (let ((omit-re (or regexp (dired-omit-regexp))) (old-modified-p (buffer-modified-p)) count) (unless (string= omit-re "") (let ((dired-marker-char dired-omit-marker-char)) (when dired-omit-verbose (message "Omitting...")) (if (if linep (not (dired-mark-if (and (= (following-char) ?\s) ; not already marked (string-match-p omit-re (buffer-substring (line-beginning-position) (line-end-position)))) nil)) (not (dired-mark-unmarked-files omit-re nil nil dired-omit-localp (dired-omit-case-fold-p (if (stringp dired-directory) dired-directory (car dired-directory)))))) (when dired-omit-verbose (message "(Nothing to omit)")) (setq count (dired-do-kill-lines nil (if dired-omit-verbose "Omitted %d line%s" ""))) (force-mode-line-update)))) ;; Try to preserve modified state of buffer. So `%*' doesn't appear ;; in mode-line of omitted buffers. (set-buffer-modified-p (and old-modified-p (save-excursion (goto-char (point-min)) (re-search-forward dired-re-mark nil t)))) count))) ``` --- **UPDATE** I've added this feature of omitting lines that match a regexp (not just lines with a file name that matches a regexp) to Dired+. The behavior is governed by a new user option, **`diredp-omit-line-regexp`**. --- Tags: dired, dired-omit-mode ---
thread-63671
https://emacs.stackexchange.com/questions/63671
Is there a command (and ideally a key binding) to navigate to the top (or bottom) of an org table?
2021-03-01T19:07:52.207
# Question Title: Is there a command (and ideally a key binding) to navigate to the top (or bottom) of an org table? I have read Built-in Table Editor, and searched `apropos-function org table` for `top`, `bottom`, `beginning`, and `end`. I found `org-table-beginning-of-field`, but not anything like `org-table-beginning-of-table`. `M-{` is bound to `org-backward-element`, so inside a table it doesn't go back a paragraph but just a line. `C-M-a` is still bound in `org-mode` to `beginning-of-defun`, which inside a table just goes up one line. Is there some standard text-mode key binding that gets you to the top of the table that I haven't thought of trying yet? There must already be a way to do this? # Answer > 4 votes Not that I know of, but Org mode provides the ingredients to roll your own easily: ``` (defun org-table-goto-beginning () (interactive) (goto-char (org-table-begin))) (defun org-table-goto-end () (interactive) (goto-char (org-table-end))) (define-key org-mode-map (kbd "C-c t b") #'org-table-goto-beginning) (define-key org-mode-map (kbd "C-c t e") #'org-table-goto-end) ``` Both of these assume that when they are called, `point` is within a table. Both could probably use some error handling if that is not the case. --- Tags: org-mode, key-bindings, org-table, navigation ---
thread-63675
https://emacs.stackexchange.com/questions/63675
How to widen all live buffers?
2021-03-01T21:34:43.260
# Question Title: How to widen all live buffers? I'd like to apply e.g. `widen` to all active buffers, rather than the current one. How can I do this? # Answer > 2 votes Iterate among all buffers that are displayed (i.e., have a window), widening each: ``` (defun foo () "..." (interactive) (dolist (buf (buffer-list)) (when (get-buffer-window buf 0) (with-current-buffer buf (widen))))) ``` Or if you want to do it to all (live) buffers, even if they aren't displayed in a window, then this: ``` (defun foo () "..." (interactive) (dolist (buf (buffer-list)) (when (buffer-live-p buf) (with-current-buffer buf (widen))))) ``` --- Tags: buffers, narrowing ---
thread-20587
https://emacs.stackexchange.com/questions/20587
How do I change permanently the encoding of a text file?
2016-02-25T16:14:56.260
# Question Title: How do I change permanently the encoding of a text file? I have a bunch of html files encoded as iso-8859-1-unix and a few encoded in utf-8-unix. What I want is to encode all of them in utf-8-unix. I have already tried (I think they are the same command, actually): ``` C-x C-m f utf-8-unix C-x RET f utf-8-unix ``` the modeline changes from 1 to U, but after I close the file and reopen it, the modeline shows 1 again. It seems that I cannot make the change permanent no matter what I try and I don't understand why. Following the suggestions below, I have created a new file with this content ``` <ul class="navbar"> <li><a href="index.php">home</a></li> <li><a href="bio.php">bio</a></li> <li><a href="research.php">research</a></li> <li><a href="software.php">software</a></li> <li><a href="contacts.php">contacts</a></li> </ul> ``` `C-h v buffer-file-coding-system` returns this: ``` Its value is utf-8-unix Local in buffer new.htm; global value is the same. ``` so it looks okay. I save, kill the buffer, reopen the file and `C-h v buffer-file-coding-system` returns this: ``` Its value is undecided-unix Local in buffer new.htm; global value is utf-8-unix ``` I am really confused. EDIT: thanks everybody for helping making this clear! # Answer **N.B.**: Question answered in comments. > 0 votes --- Tags: character-encoding ---
thread-63678
https://emacs.stackexchange.com/questions/63678
When reloading an org mode file, why do I get a whole bunch of `^M` chars in my file?
2021-03-01T22:47:50.573
# Question Title: When reloading an org mode file, why do I get a whole bunch of `^M` chars in my file? I'm just learning emacs and I'm using spacemacs configuration. I created a `.org` file and everything looks normal when I save it, but when I reload it I get a whole bunch of `^M` chars at the end of each line. How do I avoid this? # Answer > 2 votes `^M` is the "carriage return" character. DOS and Windows computers use the two-character sequence `^M^N` to mark the end of every line, while Linux uses just `^N` (the "line feed" character). There are a number of Emacs settings which can control how files are encoded when saving them and when opening them, but by default it simply assumes that files will have the proper line endings for the system you're running. Thus, if you're on Linux then Emacs will assume that files have only `^N` characters at the end of every line, and that `^M` characters have no special meaning. It sounds like you choose to save the file in a specific encoding, such as `utf-8-dos` or `us-ascii-dos`, which caused it to use the DOS line endings instead. There are a number of different ways you can get into that state, so I'm not going to try to guess how you did it. If it asked you to choose a coding system when you saved the file, then just don't choose one with `-dos` in the name next time. # Answer > 0 votes You probably have a file with mixed DOS/Unix carriage return characters. If you do `C-x-RET f` you can select the coding system you prefer. Then save the file and you should be all set. --- Tags: character-encoding, control-characters ---
thread-63683
https://emacs.stackexchange.com/questions/63683
How to jump to a ledger-report by key
2021-03-02T15:03:28.963
# Question Title: How to jump to a ledger-report by key This keybind **only works after I've opened a ledger file**. ``` (spacemacs/set-leader-keys "jL" 'ledger-report ) ``` Thus I presume `ledger-mode` is required. Yet adding `(require 'ledger-mode)` ``` (spacemacs/set-leader-keys "jL" (require 'ledger-mode) 'ledger-report ) ``` returns ``` kbd: Wrong type argument: integer-or-marker-p, ledger-report ``` `ledger-report`: https://github.com/ledger/ledger-mode/blob/3495d1224ee73aa96c1d5bd131dc3a7f23d46336/ledger-report.el#L264 # Answer I don't know anything about spacemacs, but on general principles I would try this: ``` (spacemacs/set-leader-keys "jL" (lambda () (interactive) (require 'ledger-mode) (call-interactively #'ledger-report))) ``` > 0 votes --- Tags: spacemacs, ledger ---
thread-63674
https://emacs.stackexchange.com/questions/63674
doom-modeline module with line(w) status
2021-03-01T20:17:11.160
# Question Title: doom-modeline module with line(w) status As the title implies, what package or feature does `line(w)` denote? When active, it deletes lines in `evil-insert-state` upon pressing `Enter` and then `i` immediately afterward. # Answer Found it; the package was `objed`! As quoted from the Github README: > A global minor-mode to navigate and edit text objects. Objed also enables modal editing and composition of commands. It combines ideas of versor-mode and other Editors like Vim or Kakoune and tries to align them with regular Emacs conventions. > 1 votes --- Tags: evil, doom ---
thread-63686
https://emacs.stackexchange.com/questions/63686
How do I get org-mode to treat the output of a non-latex code block as latex?
2021-03-02T22:54:35.623
# Question Title: How do I get org-mode to treat the output of a non-latex code block as latex? (Emacs: v27.1, Org: v9.5, pdfTeX: v3.14159265-2.6-1.40.21) I am using the following Python code block to print LaTeX code: ``` #+BEGIN_SRC python :session :exports both :results output :wrap math ... #+END_SRC ``` That prints: ``` M^{1} = \left[\begin{matrix}15000.0 \\ 15000.0\end{matrix}\right] \\ ... ``` However, when I export to a LaTeX document, it is interpreted as: ``` M\textsuperscript{1} = [15000.0 $\backslash$\ 15000.0] \\ ... ``` And that causes the LaTeX compilation to fail. How can I prevent Emacs from reinterpreting the output? # Answer > 1 votes I think you should change `:wrap math` to `:wrap export latex`. That should wrap the output in a `#+begin_latex:` block, which should in turn export the way you want. --- Tags: org-mode, latex, org-babel, python ---
thread-63633
https://emacs.stackexchange.com/questions/63633
Using org-mode babel, how do I quickly export some html soure block to a separate file?
2021-02-28T08:32:56.033
# Question Title: Using org-mode babel, how do I quickly export some html soure block to a separate file? I am taking notes on a course in org-mode. I am using HTML source-blocks to write down examples of html code. This serves me because I have text and code in one file and it will be easier to export it to a blog for example. ``` #+begin_src html #some html code #+end_src ``` However, sometimes I want to test the code in a source block and would want to export it to a separate html file. Any tipps on how to achieve this quickly? Exporting via `C-c C-e h o` always exports the whole buffer or the subtree. But I want to export only the code in the source block. Any tipps on how to do this? # Answer `C-c C-v C-t` runs `org-babel-tangle` and exports all code blocks to the current buffer name plus the correct code extension (e.g. html blocks get `.html`, python blocks get `.py`). You can specify the tangled filename with the `:tangle` property at the header, section, or file level. Run `C-u C-c C-v C-t` to only tangle the current code block containing the point. > 1 votes # Answer Just realized the answer to my question: hit `C-c '` for `org-edit-special` and then save the buffer to a new file. > 0 votes --- Tags: org-mode, html, babel ---
thread-63692
https://emacs.stackexchange.com/questions/63692
Toggle org-html-head-include- only when publishing
2021-03-03T00:38:54.397
# Question Title: Toggle org-html-head-include- only when publishing I use `org-mode` to publish a blog which is based on org files in a particular directory. I've customized values in *html-head*, *html-preamble*, and *html-postamble* with some Bootstrap code to get the desired html code marked up and everything works well. Accordingly, I've set `org-html-head-include-default-style` and `org-html-head-include-scripts` to `nil`. I also sometimes use `org-mode` to export files in other locations to html which I may sometimes share (e.g., with coworkers). However, because I've set `org-html-head-include-default-style` and `org-html-head-include-scripts` to `nil`, those exports are boring (lack HTML tags that are included by default). I'd like to toggle `org-html-head-include-default-style` and `org-html-head-include-scripts` depending on where I'm publishing from (e.g., `nil` when exporting from my blog directory, other `t` when exporting from anywhere else). How do I achieve this? My `org-mode` config is something like the following: ``` (setq org-html-htmlize-output-type 'css) (setq org-html-head-include-default-style nil) (setq org-html-head-include-scripts nil) (setq org-publish-project-alist '(("orgfiles" :base-directory "~/blog/content/" :base-extension "org" :publishing-directory "/ssh:user@blog.com#22:/blog/" :recursive t :html-head "<!-- 3rd party css and js --> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://blog.com/site/3rdParty.css\"/> <script src=\"https://blog.com/site/3rdParty.js\"></script> <!-- Site css and js --> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://blog.com/site/site.css\"/> <script src=\"https://blog.com/site/site.js\"></script>" :html-preamble "... preamble code ..." :html-postamble "... postamble code ..."))) ``` Do I need to create some function (to toggle `org-html-head-include-default-style` and `org-html-head-include-scripts`) and a hook for `org-publish` depending on my present working directory? # Answer You should be able to use directory-local variables for this: do `C-h i g(emacs)Per-directory local variables RET` to find out more information. Briefly, create a file named `.dir-locals.el` in your blog directory where the Org mode files that you publish are kept. Put the following in the file: ``` ((org-mode . ((org-html-head-include-default-style . nil) (org-html-head-include-scripts . nil)))) ``` Every Org mode file in that directory will have those two variables locally set to `nil`. Other Org mode files in other directories will not be affected. > 1 votes --- Tags: org-mode, org-publish ---
thread-63689
https://emacs.stackexchange.com/questions/63689
magit equivalent to `git push -u origin newLocalBranch`
2021-03-02T23:38:30.407
# Question Title: magit equivalent to `git push -u origin newLocalBranch` I often create new branches locally (e.g., *newLocalBranch*), and then push them to the upstream remote origin, thus creating a new remote branch, using `git push -u origin newLocalBranch`. Is there a `magit` function equivalent to this operation? # Answer `magit-push-current-to-pushremote` actually works perfect for me. If the branch already exists upstream, `magit-push-current-to-pushremote` will just push the committed changes upstream. If the branch does not yet have an upstream location set, `magit-push-current-to-pushremote` will prompt to select a remote location from the minibuffer (e.g., *origin*) to the branch to, defaulting to the same local name (i.e., *newLocalBranch*). Using `magit-push`, instead, would fail because no upstream location has been set for the *newLocalBranch* yet. Per the documentation for `magit-push-current-to-pushremote`: > Push the current branch to ‘branch.\<name\>.pushRemote’. If that variable is unset, then push to ‘remote.pushDefault’. > > When ‘magit-push-current-set-remote-if-missing’ is non-nil and the push-remote is not configured, then read the push-remote from the user, set it, and then push to it. > 2 votes --- Tags: magit, git ---
thread-63697
https://emacs.stackexchange.com/questions/63697
How to run shrink-window-horizontally multiple times, or how to repeat a function multiple times in general?
2021-03-03T04:28:46.590
# Question Title: How to run shrink-window-horizontally multiple times, or how to repeat a function multiple times in general? I wanted to define a function to execute a command multiple times and ended up using `fset`: ``` (fset 'my-shrink (kbd "C-u 43 C-x {")) ``` Now, I want to include this in a function, like this: ``` (defun my-todo () (interactive) (find-file "~/Dropbox/orgfiles/tasks.org") (split-window-right) (my-shrink) ; this won't work ) ``` but it failed with "Invalid function: my-shrink". Apparently, `my-shrink` is not a function, so I can I call it in a function? Or, alternatively, how to do something similar to my-shrink in a function? BTW, all `my-shrink` does it to run `shrink-window-horizontally` 43 times. # Answer Well, you could define it this way: ``` (defun my-shrink () (interactive) (dotimes (_ 43) (shrink-window-horizontally 1))) ``` But that's not quite as elegant as this: ``` (defun my-shrink () (interactive) (shrink-window-horizontally 43)) ``` And since that's so short, maybe you don't even need to define anything at all. Just call `(shrink-window-horizontally 43)` in `my-todo`. > 3 votes --- Tags: window, functions ---
thread-26225
https://emacs.stackexchange.com/questions/26225
Don't pair quotes in electric-pair-mode
2016-08-12T14:04:24.943
# Question Title: Don't pair quotes in electric-pair-mode How can I get `electric-pair-mode` to *not* pair quotation marks (single or double)? I still want it to pair everything else (brackets, braces, etc.), just not quotes. # Answer Add the following to your emacs init file: ``` (setq electric-pair-inhibit-predicate (lambda (c) (if (char-equal c ?\") t (electric-pair-default-inhibit c)))) ``` Reference from my blog post: https://www.topbug.net/blog/2016/09/29/emacs-disable-certain-pairs-for-electric-pair-mode/ > 11 votes # Answer Update: @xuhdev's answer is preferable as it doesn't interfere with Emacs' code. Might be worth a feature request having that customizable. For the moment, it looks trivial to modify the code in question. Afterwards load your own variant of electric-pair-post-self-insert-function Open elec-pair.el and copy from there ``` (defun electric-pair-post-self-insert-function () [ ... ] ) ``` Then look into the body for any ``` (memq syntax '(?\( ?\) ?\" ?\$)) ``` and delete the `?\"` from there, i.e. ``` (memq syntax '(?\( ?\) ?\$)) ``` but not delete ?\\" at other places(!) and reload i.e. evaluate the changed function. To reload at next session put it into some file "my-changed-stuff.el" and load this from your init-file. > 2 votes # Answer It appears you cannot. The various customizations only allow you to add pairs. If you're willing to use a different package to do your pairing, you can try smartparens. You can set quotation marks to not pair as follows: ``` (sp-pair "'" nil :actions :rem) (sp-pair "\"" nil :actions :rem) ``` > 1 votes # Answer I think it could be simpler, based on @xuhdev's answer: ``` (setq electric-pair-inhibit-predicate (lambda (c) (char-equal c ?\"))) ``` The doc says > The function is called with a single char (the opening char just inserted). If it returns non-nil, then ‘electric-pair-mode’ will not insert a matching closer. So the lambda only needs to return a boolean. > 1 votes --- Tags: quote, electric-pair-mode, pairing ---
thread-63598
https://emacs.stackexchange.com/questions/63598
How do I bind C-x p to the project.el project-prefix-map?
2021-02-25T16:03:48.367
# Question Title: How do I bind C-x p to the project.el project-prefix-map? Following the advice of Mastering Emacs I'm trying to use the `project.el` package. My problem is that `C-x p` isn't bound to the prefix keymap and I can't figure out how to bind it correctly. I'm pretty sure I'm trying to get this part of the package to load: https://github.com/emacs-mirror/emacs/blob/master/lisp/progmodes/project.el#L618 I've tried this: ``` (use-package project :bind-keymap ("C-x p" . project-prefix-map)) ``` but I get a `Wrong type argument: sequencep` I've tried `bind-key` but I don't know what to put in for the `COMMAND` argument so I tried this: ``` (bind-key "C-x p" project-prefix-map) ``` which is also wrong. I'm running Emacs on MacOS. The Emacs version is GNU Emacs 27.1 (build 1, x86\_64-apple-darwin19.6.0, NS appkit-1894.60 Version 10.15.7 (Build 19H15)) installed using macports. # Answer I found that upgrading the `project.el` package to 0.5.3 fixes the binding problem. To do this I first had to fix the GNU TLS algorithm priority as described in this Emacs Stack Exchange answer. Once this was added I could successfully load the GNU ELPA package list and upgrade to the latest `project.el` package. With the 0.5.3 version I can use `(require 'project)` or `use-package` to load project and get the key map bound correctly. > 2 votes --- Tags: key-bindings, prefix-keys, project ---
thread-36380
https://emacs.stackexchange.com/questions/36380
Use several Emacs configurations/versions simultaneously
2017-10-24T01:44:41.207
# Question Title: Use several Emacs configurations/versions simultaneously I want to use several emacs configurations/versions simultaneously so that no configuration disturbs each other, each with their own configuration directory and elpa repository. I heard about the trick with symlinking `~/.emacs.d` and `~/.emacs`, but that is not what I want, because it'd be best if I can run my default emacs installation and *simultaneously* a testing installation (new emacs releases) or another setup like Spacemacs or Prelude. Is there any decent way to do this? # Answer I just did that using chemacs. Considering you don't have an .emacs file in your home folder you can follow this instruction to install it: Clone the Git repository, and run install.sh ``` $ git clone https://github.com/plexus/chemacs.git $ cd chemacs $ ./install.sh ``` you should get this message: ``` OK Creating symlink ~/.emacs -> /home/arne/chemacs/.emacs ``` If you already have an .emacs file, rename or move it somewhere. Next step, create the file: *.emacs-profiles.el* in your home folder: ``` $ touch .emacs-profiles.el ``` Here is an example of the this file: ``` (("default" . ((user-emacs-directory . "~/.emacs.d"))) ("spacemacs" . ((user-emacs-directory . "~/spacemacs")))) ``` Mine looks like this: ``` (("default" . ((user-emacs-directory . "~/.emacs.d"))) ;; DoomEmacs, my default emacs ("prelude" . ((user-emacs-directory . "~/emacsprelude/.emacs.d"))) ;; Prelude ("goodemacs" . ((user-emacs-directory . "~/myemacs/.emacs.d"))) ;; my own config ("spacemacs" . ((user-emacs-directory . "~/spacemacs/.emacs.d")))) ;; Spacemacs ``` Here I create the file `~/myemacs/.emacs.d/init.el`, for my own config. Now to use a config, I run one of the following command: ``` $ emacs --with-profile $ emacs --with-profile myemacs $ emacs --with-profile prelude $ emacs --with-profile spacemacs ``` Hope this help. **Update:** There is a newer version of chemacs called chemacs2. **Update 2:** Emacs 29 has now this feature built-in. > 7 votes # Answer I wanted the same and stumbled across a tip at the Spacemacs Github site, so I came up with the following script, which assumes that alternate configurations are stored in `~/alternate-emacsen/*NAME-OF-CONFIG*`. I use this eg. to test emacs26 pre-release while working with a plain emacs25 and being able to use spacemacs, doom emacs or any variant configuration whenever I want to. The script resides in `~/bin` and assumes that `<name-of-config>` and the name of the softlink which calls it are identical; eg. if you want to launch the config stored in `~/alternate-emacsen/deepin-emacs` you need a softlink `~/bin/deepin-emacs`. Be sure to put `.emacs.d` inside the `<name-of-config>` directory since the latter is used as a fake home directory, so that the actual `~/.emacs.d` and `~/.emacs` do not get touched. If you think this is useful or suits your needs, feel free to use it. ``` #!/bin/bash # alternate-emacsen –– A bash script to launch Emacs in completely different # configurations, like GNU default, Deepin Emacs, # Spacemacs, CL server,… from their own config directory # trees. # Usage: # – create a directory $HOME/alternate-emacsen/name-of-config, containing an # .emacs.d with all the base configuration inside it. Put the init file into # <name-of-config> if necessary. # – create a link to this script, eg. # ln -s $HOME/bin/alternate-emacsen.sh $HOME/bin/emacs-unstable # ln -s $HOME/bin/alternate-emacsen.sh $HOME/bin/spacemacs # ln -s $HOME/bin/alternate-emacsen.sh $HOME/bin/doom-emacs # ln -s $HOME/bin/alternate-emacsen.sh $HOME/bin/deepin-emacs # ln -s $HOME/bin/alternate-emacsen.sh $HOME/bin/prelude-emacs # ln -s $HOME/bin/alternate-emacsen.sh $HOME/bin/emacsstarterkit # ln -s $HOME/bin/alternate-emacsen.sh $HOME/bin/exwm # ln -s $HOME/bin/alternate-emacsen.sh $HOME/bin/clemacsd # – set $emacsbin below to the emacs version you prefer/use. or set it to # /usr/bin/emacs for the system's default. I use emacs-25.2 with the # Athena/Lucid X widget set as my default GUI (not GTK because I do not like # it for several reasons), so it is set as default. # – edit the emacs2x entries to reflect your preferences like in the previous # step. self="emacs config launcher"; emacsconfig=`basename -- "$0"`; userhome=$HOME; HOME=$HOME/alternate-emacsen/$emacsconfig; test -d "$HOME" || { \ echo >&2 "$self: ERROR –– $HOME does not exist!"; exit 1; }; # On my system, Emacs 23.2/GTK2 (in /usr/bin) is the default, but I prefer Emacs # 25 with pure X11 Lucid interface. Also, the system default uses partly # incompatible ELisp packages (both to Emacs 23 and Emacs 25), so I ignore them # by not using /usr/share/* at all (the other Emacsen are compiled to reside in # /usr/local and thus ignore the outer /usr tree). emacsbin=/usr/local/bin/emacs-25.2-lucid; sysdefaultemacs=/usr/bin/emacs; emacs23=$sysdefaultemacs; emacs24=/usr/local/bin/emacs-24.4-lucid; emacs25=/usr/local/bin/emacs-25.2-lucid; emacs26=/usr/local/bin/emacs-26; emacstesting=$emacs26; case $emacsconfig in spacemacs|deepin-emacs|clemacs|doom-emacs|prelude-emacs|emacsstarterkit) emacsbin=${emacs25}; ;; exwm) emacsbin=${emacs24}; ;; emacs-testing|emacs-unstable) emacsbin=${emacstesting}; ;; *) HOME=$userhome; ;; # use emacsbin as defined in the settings esac export HOME; unset userhome; cd "$HOME"; if test -e "$emacsbin"; then $emacsbin "$@" else echo >&2 "$self: ERROR –– not found: $emacsbin"; exit 1 fi ``` > 2 votes # Answer I would recommend using docker to setup multiple versions. This would mean you need docker installed. Docker is used to build containers, which are light-weight isolated virtual environment running on your machine. Containers have complete isolation from your current machine therefore allowing you to set up isolated environments for each version of emacs. If you are familiar with python virtual environment, it is the same but more generic and may require more technical understanding. It may be worth the investment to learn docker. Here is the link to dockerfile use to build images... https://github.com/Silex/docker-emacs Good luck! > -1 votes --- Tags: init-file, config ---
thread-63723
https://emacs.stackexchange.com/questions/63723
start-process: Setting current directory: No such file or directory
2021-03-04T07:47:42.193
# Question Title: start-process: Setting current directory: No such file or directory I have a timer which call a function itself calling `start-process`. Whenever the current buffer's directory changed (deleted/moved), I have the error ``` start-process: Setting current directory: No such file or directory ``` The command ran by `start-process` is not directory specific, it can be run anywhere. So my workaround is setting `default-directory` to a directory which probably exists: ``` (let ((default-directory user-emacs-directory)) (start-process ...)) ``` **Question.** Is that a common workaround to prevent `start-process` fail ? # Answer > 4 votes Yes, that's the established technique. In my code I use `temporary-file-directory` instead, but this is just a detail. --- Tags: subprocess, timers ---
thread-63725
https://emacs.stackexchange.com/questions/63725
copy string at point func
2021-03-04T08:55:41.280
# Question Title: copy string at point func I'm trying to build a simple proc that copies the text on which the point is set and returns the point to where it was, but can't make it work properly. Before you say "thing-at-point" - I cannot install it (work network). My proc looks like this: ``` (defun string-at-point () "copy string around point" (interactive "") (point-to-register ?y) (re-search-backward "\_<" nil t 1) (setq mark-active t) (re-search-forward "\_>" nil t 1) (call-interactively 'kill-ring-save) (register-to-point ?y) ) ``` Thing is, it only copies parts of the text. Sample text: *this is some /very/long/name-of/my.file/that-might\_contain\_letters/andnumbers0-9/anywhere in it.* I expect my proc, when placed inside the long string (say - point is at 0), to copy the string and leave the point back at 0. instead, it copies *0-9/anywhere in it.* (meaning - until the end of the line). Also tried using `"\\_>"` and `"\\_<"` in the re-searches, but got even weirder results... What am I doing wrong? # Answer You can try the following command. It has certainly lots of corner cases as it uses a simple whitespace syntax. If your intention is to copy arbitrary text, it's easier to select the region `C-SPC` (`set-mark-command`), then copy it `M-w` (`kill-ring-save`). ``` (defun my-string-at-point () "Save the space-delimited string at point to the kill ring." (interactive) (save-excursion (let ((beg (progn (skip-syntax-backward "^ " (line-beginning-position)) (point))) (end (progn (skip-syntax-forward "^ " (line-end-position)) (point)))) (copy-region-as-kill beg end)))) ``` > 2 votes # Answer > Before you say "thing-at-point" - I cannot install it (work network). `thing-at-point` has been built into Emacs since 1993. ``` thing-at-point is an autoloaded compiled Lisp function in ‘thingatpt.el’. (thing-at-point THING &optional NO-PROPERTIES) Probably introduced at or before Emacs version 20. Return the THING at point. THING should be a symbol specifying a type of syntactic entity. Possibilities include ‘symbol’, ‘list’, ‘sexp’, ‘defun’, ‘filename’, ‘url’, ‘email’, ‘uuid’, ‘word’, ‘sentence’, ‘whitespace’, ‘line’, ‘number’, and ‘page’. When the optional argument NO-PROPERTIES is non-nil, strip text properties from the return value. See the file ‘thingatpt.el’ for documentation on how to define a symbol as a valid THING. ``` For example: ``` (thing-at-point 'word) (thing-at-point 'symbol) ``` > `(re-search-backward "\_<" nil t 1)` This is invalid regexp syntax - it should be either `"\\<"` for "beginning of word", or `"\\_<"` for "beginning of symbol". Similarly with the matching "end of X" regexp. See `(info "(elisp) Syntax of Regexps")` and its subnodes. > *this is some /very/long/name-of/my.file/that-might\_contain\_letters/andnumbers0-9/anywhere in it.* Hm, that's not an easy construct. The problem is that word/symbol boundaries depend on the current buffer's syntax table, so they will work differently depending on which buffer you're in. This means you need to specify exactly what constitutes your desired boundaries, or in which mode you will be using this command. For instance, the following should work with your example in a Lisp buffer: ``` (defun my-save-symbol-at-point () "Make symbol at point the latest kill in the kill ring." (interactive) (let ((symbol (thing-at-point 'symbol))) (when symbol (kill-new symbol)))) ``` But it won't work the same in a Text buffer. Ideally the following should work more reliably regardless of mode: ``` (defun my-save-filename-at-point () "Make file name at point the latest kill in the kill ring." (interactive) (let ((file (thing-at-point 'filename))) (when file (kill-new file)))) ``` You could even complete different types of thing at point that you may be interested in: ``` (defun my-save-thing-at-point (&optional thing) "Make THING at point the latest kill in the kill ring. See `thing-at-point' for possible values of THING. It defaults to `filename'. With a prefix argument, select a type of THING with completion." (interactive (when current-prefix-arg ;; Add whatever you like here. (let ((things '("filename" "symbol" "sexp" "url" "word"))) (list (intern (completing-read "Type of thing (default filename): " things nil t nil nil things)))))) (kill-new (or (thing-at-point (or thing 'filename)) (user-error "No such thing at point")))) ``` If all you want is to detect text boundaries that consist of spaces, then see Firmin Martin's answer. > 2 votes --- Tags: interactive, defun ---
thread-63733
https://emacs.stackexchange.com/questions/63733
Launch an external command prompt (cmd.exe) in a specific folder
2021-03-04T15:34:44.310
# Question Title: Launch an external command prompt (cmd.exe) in a specific folder I'm trying to build a `cmd` interactive function in Emacs, which would open a Windows command prompt - exactly like `Win+R` `cmd` does. Within Emacs, it would be accessible with `M-x` `cmd`, and it would open the Windows terminal on the current folder. The reason I want to build this function is that there are cases where the Emacs shell does not give the outputs properly (see this), and in these cases I'd like to open a Windows terminal quickly, and at the location I'm at. I know how to get the current folder in Emacs, but I can't seem to find how to launch the Windows console from Emacs. `call-process` works for programs like firefox.exe or explorer.exe, yet when I try the following, nothing appears (it doesn't matter if I write the full path or not): ``` (call-process "cmd.exe") ``` **TL;DR**: So, what would be the command to launch, from Emacs, an **external** command prompt at a specific path? # Answer I came up with the following, which works: ``` (defun cmd() "Open an external Windows cmd in the current directory" (interactive) (let ((default-directory (if (buffer-file-name) (file-name-directory (buffer-file-name)) default-directory)))) (call-process-shell-command "start cmd")) ``` The idea to use `start cmd` instead of `cmd` comes from this SO question: it's the standard way to open a new `cmd` from a runnning one, in Windows. The idea to use `call-process-shell-command` comes from multiple tries and errors. > 0 votes --- Tags: microsoft-windows, shell ---
thread-63727
https://emacs.stackexchange.com/questions/63727
How to hierarchically find available functions in the minibuffer with stock emacs
2021-03-04T10:25:56.243
# Question Title: How to hierarchically find available functions in the minibuffer with stock emacs I accidentally pressed some keys and found a feature that looked really useful. It gave me the option to hierarchically select a command/function to run in the minibuffer. There was some explanatory text at the top, saying I could use PageUp to go to the window to select completions. I hesitate to call it completions, because, while it was very similar to the window you get with `M-x ?`, it wasn't that (for one, that text about PageUp isn't there). With the latter you get an alphabetical list of commands. With the feature I stumbled upon, there was some hierarchy to it. E.g. there was an option "file". When I selected that with `f` I got more options, like `find-file`. I immediately installed `command-log-mode`, but I haven't reached it again so far. Emacs version: `GNU Emacs 27.1 (build 1, x86_64-w64-mingw32) of 2020-08-21` # Answer I downloaded the emacs sources and grepped for the text I remembered. Apparently I just described the text interface to the menu bar, reached with `M-`` by default. Case closed (and not as useful as it looked at first glance). > 1 votes --- Tags: completion, minibuffer ---
thread-63730
https://emacs.stackexchange.com/questions/63730
Org mode exam template with question and results in combination with latex
2021-03-04T12:15:12.710
# Question Title: Org mode exam template with question and results in combination with latex I would like to use Org mode for creating exam questions and including the templates for the corresponding results for each question. A general template is shown here ``` #+TITLE: Lecture #+AUTHOR: #+EMAIL: #+DATE: Jan 2020 #+INSTITUTE: UoW #+DESCRIPTION: #+KEYWORDS: * Fire Modeling :PROPERTIES: :andere_VL: Fire Modeling :END: ** Calculation 1 Please add $1$ and $2$ together. *** Results #+BEGIN_SRC python :session results: value res = 1 + 2 res #+END_SRC #+RESULTS: : 3 The results is \(1 + 2 = 3\) *** Results - Variables #+BEGIN_SRC python :session results: value res = variable1 + variable2 res #+END_SRC #+RESULTS: : 3 The results is \(variable1 + variable2 = variableResults\) ** Calculation 2 ``` This looks as a screenshot like: The above example includes two sections for "results". In the first one the plain numbers are displayed for clarity (I hope). In the second section "Results - Variables" I try to show how the variables need to be accessed. The idea is now that I am able to set and use variables in the actual text, which is then used for the python calculation. This would be step one. And the next step would be to include the python result inside the resulting latex equation. ### Update Maybe a macro approach is suitable and convenient; a simple example is shown below: ``` ** Calculation 2 - Macros #+MACRO: var1 16 #+MACRO: var2 16 Please add {{{var1}}} and ${{{var2}}}$ together. *** Results - Variables - MACROS This works without {{{var1}}}, but only without math...!? #+BEGIN_SRC python :session :results {{{var1}}} #+END_SRC ``` The corresponding screenshot is This results as final tex in something like: ``` \subsection{Calculation 2 - Macros} Please add 16 and \({{{var2}}}\) together. \subsubsection{Results - Variables - MACROS} This works without 16, but only without math\ldots{}!? ``` So this could be a good approach, when I can use it for the latex math enviroment and also within python src region. ### Update -end Does anyone have an idea how to achieve this? Maybe there exists already another add-on for this or similar task!? I would be happy about any kind of suggestion! With jupyter there seems to be the option for the second part... # Answer > 0 votes I don't think you can use macros in a src-block, or in a latex snippet. You can do what you want with some preprocessing, and a special syntax for the expansions. For example with this org file, and using the mustache template syntax (https://github.com/Wilfred/mustache.el/blob/master/mustache.el): ``` ** Calculation 2 - Macros #+var1: 16 #+var2: \SI{20}{\kW} Please add {{var1}} and ${{var2}}$ together. *** Results - Variables #+BEGIN_SRC python :session {{var1}} #+END_SRC ``` You can set up this before parsing hook function to render the template ``` (require 'mustache) (require 'ht) (defun preprocess (_) (let ((kws (eval `(ht ,@(org-element-map (org-element-parse-buffer 'element) 'keyword (lambda (elem) ;; org returns an upcased keyword, I downcase it here. ;; I don't know a way to reliably match case here ;; you need a convention to only downcase. (list (downcase (org-element-property :key elem)) (org-element-property :value elem)))))))) (message "KWS: %S" kws) (setf (buffer-string) (mustache-render (org-no-properties (buffer-string)) kws)))) (add-hook 'org-export-before-parsing-hook 'preprocess t) ``` Which for me generates this LaTeX: ``` \section{Calculation 2 - Macros} \label{sec:org8139f6c} Please add 16 and \(\SI{20}{\kW}\) together. \subsection{Results - Variables} \label{sec:orge8e7364} \begin{minted}[frame=lines,fontsize=\scriptsize,linenos]{python} 16 \end{minted} \end{document} ``` You might be able to use other template solutions, e.g. s-format, etc, as long as it is compatible with the latex snippets. One downside of this is you cannot execute the src block with the {{var}} syntax in it. I couldn't see an easy way to get the expansion in the text and in the src block though otherwise. --- Tags: org-mode, latex, org-babel ---