text:
Can one enable display-line-numbers in buffer's startup?
How would one enable line numbers on a buffer basis? What I have in mind is a statement in the preamble of the buffer of this form:
#+STARTUP: [...(turn on line numbers)...]

add display-line-numbers-mode to the specific buffer’s hook?

@Shynur hasn't worked for me.

The #+STARTUP: syntax is Org mode specific: are you talking about Org mode files only or something more general? If more general. on what basis is one to decide whether display-line-numbers-mode should be turned on?

For an individual buffer, all you have to do is M-x display-line-numbers-mode. That toggles the mode on: if you do it again, it toggles it off.

@NickD M-x ... does not persist from one session to the next. Yes, org files.

Use the mode hook as @Shynur suggests then: (with-eval-after-load 'org (add-hook 'org-mode-hook #'display-line-numbers-mode)). Add that to your init file. That ensures that the hook will be modified only after the file org.elc or org.el is loaded: the hook variable is defined in that file and as you now know, the variable has to be defined before it can be modified.

@NickD "...as you now know, the variable has to be defined before it can be modified." You can set hook variables with add-hook without defining and/or setting them first. (The doc of add-hook clarifies that the value of the variable can be void.)

@NickD I don't even know what "buffer's hook" refers to.

@Erwann: "what "buffer's hook" refers to." --- Any hook, as long as it will run when you open a new buffer.  (e.g., a buffer's major mode's hook)

@Erwann: I gave you a line of code to cut-and-paste (but as @Tobias points out it can be simplified: add-hook is careful to define the variable if it finds it undefined (but make sure to spell it correctly :-)  ) so you can leave out the with-eval-after-load part, although leaving it in does not hurt). You can just add then (add-hook 'org-mode-hook #'display-line-numbers-mode) to your init file, restart Emacs and you should be all set.

@NickD it seems that this instruction in the init file has the same effect as '(global-display-line-numbers-mode t). Has it not? My intention was to control the numbering display setting on an buffer basis.

No, it onlyaffects Org mode buffers, which I thought is what you wanted, but I was mistaken. See my answer for a per-file solution.

Add the following local variables section to the end of any Org mode file where you want display-line-numbers-mode to be enabled. Adding it as a COMMENT section makes sure that Org mode ignores it:
...
* COMMENT File local variables
Local Variables:
eval: (display-line-numbers-mode 1)
End:

Make sure that this is the last section in the file at the very bottom. See Specifying File variables in the Emacs manual. After adding the section, save and kill the buffer and reopen it in order to have the Local Variables settings take effect.

“save and kill the buffer and reopen” --- revert-buffer also works well in my Emacs.

So does M-x normal-mode - there are many ways to do that.


text:
Write a function that prompts for a file from within a list
As a starting point, this:
(defvar myfoo "~/org/test-file-1.org" "myfoo") ; C-x C-e
(defun mybar()
(newline-and-indent)
(insert-file-contents myfoo)) ; C-x C-e
(mybar) ; C-x C-e
Iure repudiandae non alias.
Rerum quia dicta sunt.
Omnis veniam velit nemo saepe in.

I'm trying to modify mybar such that, instead of using myfoo,
the user is presented with a predefined list of files (say those matching ~/org/test-file-*.org), and is expected to choose the one to be processed. How would I do that?

UPDATE:
Based on the answer,
(setq completions '("~/org/test-file-1.org" "~/org/test-file-2.org")) ; C-x C-e
(defun mybar()
(newline-and-indent)
(insert-file-contents (completing-read "Type something, use TAB for completion: " completions nil t))) ; C-x C-e
(mybar) ; C-x C-e

prompts "Type something, use TAB for completion: ". Followed by TAB, "Type something, use TAB for completion: ~/org/test-file-", and then TAB opens a buffer showing the candidate files:

You can use completing-read like this:
(setq completions '("foo" "bar" "baz"))

(completing-read "Type something, use TAB for completion: " completions nil t)

The fourth argument being t will allow the call to return only if a value from the list is chosen. Read the doc string of the function with C-h f completing-read - you can also search the index of the Emacs Lisp Reference manual for it with C-h i g(elisp) RET i completing TAB RET (and note that this last command to get the documentation of completing-read uses completing-read for its implementation - for the record, that's the command Info-index).

I wished I didn't have to press tab twice to get the candidate files to be displayed. Should I post anew to automate that?

If I press a single TAB at the prompt before typing anything else, I get all the candidates listed. If I've typed something, then a TAB will complete as far as it can (e.g. if I type b, it will complete to ba) and then a second TAB will show all the candidates that satisfy what's been completed so far. This is standard (and I should say, expected by users) behavior, so I would not do it differently for now. In any case, changing the question thereby invalidating an answer that satisfied whatever conditions you imposed to begin with is frowned upon.

Changing the question? I need two tabs to get all the candidate listed.

I described it inaccurately: first TAB gets you the longest common prefix. In my example, there was no  common prefix, so I got the complete list; in your case, there is a common prefix, so you get that on first TAB and you need to press a second to get the complete list. Since completion works like that in all cases (at least with the out-of-the-box completion framework that Emacs provides), it is consistent and not a burden, but you may think differently.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Is it possible to automate completions?
Continued from this post:
(setq completions '("~/org/test-file-1.org" "~/org/test-file-2.org")) ; C-x C-e
(defun mybar()
(newline-and-indent)
(insert-file-contents (completing-read "Type something, use TAB for completion: " completions nil t))) ; C-x C-e
(mybar) ; C-x C-e

Following these evaluations, in the minibuffer: (1) The first TAB gets the longest common prefix (2) a second TAB is needed to pop up a *Completions* buffer with the complete list of candidates.
Assuming the candidate files share a non empty common prefix, how would one modify the code above to automate step (1), and to jump to (2) for the stated pattern (test-file-[digit].org)?
PS: and also, once the candidate files are displayed, one has to (3) activate the completions buffer and (4) select a file from there. I wished (3) could be automated too.
C-h o completing-read

completing-read is a built-in function in ‘C source code’.
(completing-read PROMPT COLLECTION &optional PREDICATE REQUIRE-MATCH
INITIAL-INPUT HIST DEF INHERIT-INPUT-METHOD)
Read a string in the minibuffer, with completion. PROMPT is a string
to prompt with; normally it ends in a colon and a space. COLLECTION
can be a list of strings, an alist, an obarray or a hash table.
COLLECTION can also be a function to do the completion itself.
PREDICATE limits completion to a subset of COLLECTION. See
‘try-completion’, ‘all-completions’, ‘test-completion’, and
‘completion-boundaries’, for more details on completion, COLLECTION,
and PREDICATE.  See also Info node ‘(elisp)Basic Completion’ for the
details about completion, and Info node ‘(elisp)Programmed Completion’
for expectations from COLLECTION when it’s a function.
REQUIRE-MATCH can take the following values:

t means that the user is not allowed to exit unless the input is (or   completes to) an element of COLLECTION or is null.
nil means that the user can exit with any input.
‘confirm’ means that the user can exit with any input, but she needs   to confirm her choice if the input is not an element of COLLECTION.
‘confirm-after-completion’ means that the user can exit with any   input, but she needs to confirm her choice if she called
‘minibuffer-complete’ right before ‘minibuffer-complete-and-exit’
and the input is not an element of COLLECTION.
anything else behaves like t except that typing RET does not exit if it   does non-null completion.

If the input is null, ‘completing-read’ returns DEF, or the first
element of the list of default values, or an empty string if DEF is
nil, regardless of the value of REQUIRE-MATCH.
If INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
with point positioned at the end.  If it is (STRING . POSITION), the
initial input is STRING, but point is placed at zero-indexed
position POSITION in STRING.  (Note that this is different from
‘read-from-minibuffer’ and related functions, which use one-indexing
for POSITION.)  This feature is deprecated--it is best to pass nil
for INITIAL-INPUT and supply the default value DEF instead.  The
user can yank the default value into the minibuffer easily using
M-n.
HIST, if non-nil, specifies a history list and optionally the initial
position in the list.  It can be a symbol, which is the history list
variable to use, or it can be a cons cell (HISTVAR . HISTPOS).  In
that case, HISTVAR is the history list variable to use, and HISTPOS
is the initial position (the position in the list used by the
minibuffer history commands).  For consistency, you should also
specify that element of the history as the value of INITIAL-INPUT.
(This is the only case in which you should use INITIAL-INPUT instead
of DEF.)  Positions are counted starting from 1 at the beginning of
the list.  The variable ‘history-length’ controls the maximum length
of a history list.  If HIST is t, history is not recorded.
DEF, if non-nil, is the default value or the list of default values.
If INHERIT-INPUT-METHOD is non-nil, the minibuffer inherits the
current input method and the setting of ‘enable-multibyte-characters’.
Completion ignores case if the ambient value of
‘completion-ignore-case’ is non-nil.
See also ‘completing-read-function’.
Probably introduced at or before Emacs version 1.6.

One way to do it is to calculate the common prefix yourself and provide it to completing-read as the INITIAL-INPUT argument (see the doc string C-h v completing-read for usage).

"... one has to (3) activate the completions buffer and (4) select a file from there." Are you using a GUI Emacs? If so, all you have to do is click on it.

Apart from @NickD's helpful comment that you can calculate the common prefix yourself (maybe it should be an answer instead of just a comment):

No, as far as I know, vanilla Emacs doesn't show matches without user input (TAB).
(Various 3rd-party completion frameworks can do this. Icicles has offered this incremental completion since 2005, for instance.)
M-x report-emacs-bug for enhancement requests.  See option completion-auto-help, for example -- you might want to request another value for this option that does what you want (show completions without having to hit TAB).

Given my noted propensity to not get things, I think it would be better for someone who does to do an enhancement request.

[I made my comment into an answer and supplied an implementation of longest common prefix as well].
The first TAB typed in completing-read's prompt fills in the longest common prefix of the completions. The second TAB then shows you the list of completiong for you to choose. If instead you type something else and then press TAB again, completion will limit the available choices further. You can continue like this until there is only one choice left and the final TAB completes the input to match that choice.
If you want the first TAB to just list all your choices, one way to do it is to calculate the common prefix yourself and provide it to completing-read as the INITIAL-INPUT argument. As the doc string of completing-read says:

If INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
with point positioned at the end.

It's as if you typed it in up to that point, so pressing TAB pops up a *Completions* buffer with all the choices.
Let's assume that there is a function lcp that takes a list of strings and returns the longest common prefix of all the string in the list. For convenience, we'll assume that the list is already sorted (which is no burden, since you will probably get it by calling directory-files which sorts the list by default).
So if completions is the list of all completions, then (lcp completions) will be the longest common prefix of all the completions. In your example, it will return "~/org/test-file-". Then you can use that as the INITIAL-INPUT argument of completing-read:
   ...
   (completing-read "PROMPT: " completions nil t (lcp completions))
   ...

Here's an implementation of lcp:
  (defun my/longest-common-prefix (list-of-strings)
    "Longest common prefix of strings in a list.
  The list is assumed to be sorted (but we really only need
  the (lexicographically) smallest and largest strings:
  the first and last elements of the list if the list is sorted)."
    (let ((s1 (first sl))
          (s2 (car (last sl)))
          (i 0))
      (while (eq (aref s1 i) (aref s2 i))
        (setq i (1+ i)))
      (substring s1 0 i)))

It assumes that the list of strings handed to it is sorted, so that the "smallest" element (lexicographically speaking) is the first element and the "largest" element is the last element of the list. If we find the longest common prefix of these two, we have found the longest common prefix of the whole list.
The rest of the calculation steps through the two strings one position at a time and compares the characters at that position. If they are the same, it increments the position and goes around the loop again. If they are different, the loop exits and at that point we know that the two strings have the same characters at each position from 0 to one before the last position checked. So we return the substring of the first string (or the second or any other string in the list) starting at position 0 and ending at one less than the last position checked (Lisp strings, like Python strings and C strings start at position 0): (substring s1 0 i)

Did you ever get this work?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How do I call ediff-regions-wordwise programmatically?
I want to compare two regions of the same buffer (it's the output from test failures).  It looks something like this:
Some header lines
{
  ...expected body
}, but was
{
  ...actual body
}
Some footer lines

I'm trying to write a little function that I can call after copying the test output, but I'm getting hung up on calling ediff-regions-wordwise in the script.  The documentation doesn't list the regions as parameters, only the buffers.  I can pretty easily figure out the starting and ending positions for both regions, but how do I communicate that to ediff-regions-wordwise?  I don't want to have to select them every time since finding them just requires a couple of traversal commands.

https://emacs.stackexchange.com/tags/elisp/info


text:
Custom org agenda, which displays a list of all tasks with todo-state "NEXT" and a tag from the org-tag-alist
I have defined several tags in my org-tag-alist. I want to have a list of all entries of which the TODO-State is "NEXT", which match a tag of this list. Ideally I would get a query where I would just have to input the single character corresponding to my tag in the alist, e.g. "h" for "@home", if there is an ("@home" . ?h) entry in the list.
How can I archive this?
I tried to write my own custom agenda, using the org-ql package:
("n" "Next actions by tag"
         (lambda (arg)
           (interactive)
           (setq my-tag (completing-read "Tag: " (mapcar 'car org-tag-alist)))

           (org-ql-block '(and (todo "NEXT")
                              (tags (format "%s" my-tag))
                          )
                        ((org-ql-block-header (format "NEXT tasks, whose tags match: %s" my-tag)))
                        (agenda)
           )))

Because I did not know how to query for it, using just the one char, I queried for the whole tag.
When the function is called I get the error message Wrong number of arguments: org-ql-block, 3, which is surprising, because the org-ql-block works fine with 3 arguments in another custom agenda, which is a special case of the one here. For reference the other custom agenda is this:
("h" "At home"
         ((org-ql-block '(and (todo "NEXT" "TODO" )
                              (tags "@home")
                         )
                        ((org-ql-block-header "Was am PC getan werden muss"))
                        (agenda)
           )))


text:
ibuffer : no filters in effect
I use ibuffer with emacs 30.0.50-2b8ab57b on Windows 11.
It used to work well with this configuration :
(require 'ibuffer)

(setq-default ibuffer-default-sorting-mode 'major-mode)

(setq ibuffer-show-empty-filter-groups nil)

;; Use human readable Size column instead of original one
(define-ibuffer-column size-h
  (:name "Size" :inline t)
  (cond
   ((> (buffer-size) 1000000) (format "%7.1fM" (/ (buffer-size) 1000000.0)))
   ((> (buffer-size) 100000) (format "%7.0fk" (/ (buffer-size) 1000.0)))
   ((> (buffer-size) 1000) (format "%7.1fk" (/ (buffer-size) 1000.0)))
   (t (format "%8d" (buffer-size)))))

;; Modify the default ibuffer-formats
(setq ibuffer-formats
      '((mark modified read-only " "
              (name 40 40 :left :elide)
              " "
              (size-h 9 -1 :right)
              " "
              (mode 16 16 :left :elide)
              " "
              filename-and-process)))
(setq ibuffer-filter-group-name-face 'font-lock-doc-face)

(require 'ibuf-ext)

(setq ibuffer-saved-filter-groups
      (quote (("default"
               ("terminal"  (or
                             (mode . term-mode)
                             (mode . shell-mode)
                             (mode . eshell-mode)))
               ("erc" (predicate string-match "ERC" mode-name))
               ("emacs" (or
                         (name . "^\\*scratch\\*$")
                         (name . "^\\*Messages\\*$")))
               ("gnus" (or
                        (mode . message-mode)
                        (mode . bbdb-mode)
                        (mode . mail-mode)
                        (mode . gnus-group-mode)
                        (mode . gnus-summary-mode)
                        (mode . gnus-article-mode)
                        (name . "^\\.bbdb$")
                        (name . "^\\.newsrc-dribble")
                        (name . "^bbdb\\.el$")
                        (name . "^newsrc\\.eld$")
                        (name . "^newsrc-dribble$")
                        (name . "^bbdb$")
                        (name . "^\\*BBDB\\*$")))
               ("java" (name . "\\.java/?.*$"))
               ("javascript" (name . "\\.js/?.*$"))
               ("python" (name . "\\.py/?.*$"))
               ("xml" (name . "\\.xml/?.*$"))
               ("lua" (name . "\\.lua/?.*$"))
               ("elisp" (name . "\\.el/?.*$"))
               ("tex" (name . "\\.tex/?.*$"))
               ("bib" (name . "\\.bib/?.*$"))
               ("pdf" (name . "\\.pdf/?.*$"))
               ("image" (name . "\\.png/?.*$\\|\\.jpg/?.*$\\|\\.svg/?.*$"))
               ("org" (mode . org-mode))
               ("agenda" (name . "^\\*Org Agenda\\*$"))
               ("bash" (or
                         (predicate string-match "Shell-script" mode-name)
                         (mode . shell-script-mode)
                         (mode . sh-mode)))
               ("pwsh" (mode . powershell-mode))
               ("dired" (mode . dired-mode))
               ("sidebar" (predicate string-match "Dired-sidebar" mode-name))
               ("debug" (name . "^\\*localhost([0-9]+)[^\\*]+\\*$"))
               ("special" (name . "^\\*[^\\*]+\\*$"))))))

(add-hook 'ibuffer-mode-hook
          (lambda ()
            (ibuffer-auto-mode 1)
            (ibuffer-switch-to-saved-filter-groups "default")))

(use-package all-the-icons-ibuffer
  :config
  (setq all-the-icons-ibuffer-icon t
        all-the-icons-ibuffer-color-icon t
        all-the-icons-ibuffer-icon-size 1.0
        all-the-icons-ibuffer-icon-v-adjust 0.0
        all-the-icons-ibuffer-human-readable-size t)
  :hook (ibuffer-mode . all-the-icons-ibuffer-mode))

Since a few weeks, I regularly run into the error "No filters in effect".
The step to reproduce this is for example to open some org files and then
open one elisp file. As soon as the elisp file is opened, ibuffer does not
work any more and returns "No filters in effect".
Then, if I kill the elisp buffer, ibuffer works again well.
This can also happen with some other buffers. To solve the issue, I
have no other choice but to kill buffers until the ones causing this error
disappear.
I googled this error without any much success. Do you have an idea of what is going
wrong with my configuration ?


text:
Problem with ESS when running R: .load.ESSR and .ess.eval errors
I have installed ESS on emacs v27.1. When I enter M-x R , R launches but I get the error message:
load ESSR: Error in load.ESSR("~/.emacs.d/elpa/ess-20230404.912/etc/ESSR/R"): could not find function load.ESSR
The message disappears after a few seconds.
Another problem (which may be related.)
Script file: test.r
square <- function(x) return(x*x)
When I type C-c C-c, I get the error message,
Error in .ess.eval("square <- function(x)\n{ return(x * x)\n}", visibly = TRUE,  : could not find function ".ess.eval"
Thank you

I have figured it out: I forgot to add the line (add-to-list 'load-path "~/.emacs.d/elpa/ess/lisp") in the .emacs file. Thank you for reading this.


text:
Problem in opening files with filenames in Devanagari
I am using Emacs 28.2 on Trisquel 11.
I have installed it using 'guix package manager'. When I am trying to open a file named in Devanagari characters it opens as blank file and the file name on mode bar appears as garbage. (Please see the image.

On the other hand, when I open the same file using the mini buffer, it opens correctly as can be seen in image bellow.

I have also tried adding following in my init file.
(set-language-environment "UTF-8")
(set-default-coding-systems 'utf-8)
(prefer-coding-system 'utf-8)
(set-terminal-coding-system 'utf-8)

Is there any way to solve this problem?

There is also a variable default-file-name-coding-system, try to set it with the actual conding for file name (utf-8 may not always be).


text:
Define org-agenda-files relative to org-directory?
I'm trying to set up my config so that the org-agenda-files are defined in relation to the org-directory.
Right now, I use all of the files in my org-directory as agenda files. In my config is:
(setq org-agenda-files (directory-files-recursively org-directory "\\.org$"))

This works flawlessly for that; however, I'm looking to reduce the number of files included in my agenda to only those in the "agenda" subdirectory within org-directory. I want it to be something like (setq org-agenda-files (org-directory + /agenda/)), but I don't know lisp well enough to figure it out.

(directory-files-recursively  (concat org-directory "/agenda/") ....) will look in the agenda subdirectory of org-directory.


text:
Avoid auto-inserting extra space after manually inserting semicolon
I am using Verilog mode, and after closing the port declarations parenthesis, emacs always inserts a space at the beginning of corresponding line .
To be more clear:
module ffff
(
    uuu,
    bla
 ); // <--- extra space added at the beginning of this line

wire   xxx;
reg    aaa;

endmodule

How can I avoid this annoying behaviour ?

I took a cursory look and I think this is caused by verilog-calculate-indent, but I didn't see any way to control that from the outside: you'd have to modify the code of verilog-calculate-indent. But maybe I missed something: caveat emptor.


text:
Highlighting strings in Org and Markdown mode doesn't work with *bold* or /italic/
I want to highlight strings between double quotation marks in org-mode and markdown-mode, just so they're easier to see, as in LaTeX-mode.  I have the following in my .emacs:
;; Highlight strings delimited by double quotations in Org Mode
;; buffers, please
(defface org-string-face
  (let ((font '(:inherit italic)))
    `((((type tty) (class color))
       (:foreground "green"))
      (((class grayscale) (background light))
       (:foreground "DimGray" ,@font))
      (((class grayscale) (background dark))
       (:foreground "LightGray" ,@font))
      (((class color) (background light))
       (:foreground "RosyBrown"))
      (((class color) (background dark))
       (:foreground "LightSalmon"))
      (t (,@font))))
  "Face used to highlight strings."
  :group 'org-faces)

(font-lock-add-keywords 'org-mode   ;;
            '(("\"[^\"]*\"" . 'org-string-face)) t)
(font-lock-add-keywords 'markdown-mode  ;;
            '(("\"[^\"]*\"" . 'org-string-face)) t)

This works, in other words any characters between " and " as well as the quotation marks will show the desired fortification unless I accent any words within the quotation marks.  So the org-mode and markdown-mode emphasis markings * and / do show their emphasis, but then the entire string is unfontified.  I'm not sure why this doesn't work because the regex above should capture everything (not just [:alnum:]) between quotation marks.  Yes, it works across lines.
Just in case anyone has a different solution, I am writing fiction with multiple languages in dialogue, with English as the primary language and other languages interspersed occasionally, marked with italics.
Edit: let me just add that the above regex works interactively, i.e. interactive regex functions such as Regexp I-search and regexp-builder.


text:
How can I use variables in target file paths for org capture templates?
I use emacs on a few different machines which unfortunately don't have the same file structure, but I want to share my config among them as much as possible. All machines have a ".../org/" folder which is synchronized with syncthing. I want to set up my capture templates to build their target file paths from a variable set per-machine which points to that org folder, instead of manually editing each template's target to be the full path to each file.
I have put this code in my init.el:
(setq lk/org-file-path "~/../../Documents/org/")

(setq org-capture-templates
    '(("t" "tasks / Projects")
     ("tt" "task" entry (file+olp (concat lk/org-file-path "Tasks.org") "Inbox")
      "* TODO %?\n %U\n %a\n %i" :empty-lines 1)
    ...
    ))

Trying to capture with this template gives the error "Invalid file location: nil". But running (concat lk/org-file-path "Tasks.org") in scratch results in "~/../../Documents/org/Tasks.org", and putting that string in place of the concat in the template definition allows the template to successfully run and save my input in the correct file.
How can I work around this?


text:
why does clocking into org mode task in one file require a network connection for different, tramp-connected file?
I have several files listed as org agenda files, one of which is loaded via ssh using tramp. I do all my time tracking in a different file, which is local to my computer. But when I don't have a network connection, tramp gets upset when I try to clock into a task in the local file.  I get:
Tramp: Opening connection nil for remotemachine using plinkx...
Tramp failed to connect.  If this happens repeatedly, try
‘M-x tramp-cleanup-this-connection’
Tramp: Opening connection nil for remotemachine using plinkx...failed

This doesn't seem to make sense. Why can't org handle this situation? How I can tell it to just clock in without re-loading all other agenda files?


text:
Unable to detangle code create by org-babel-tangle
With a single literate program trying to output rust, in a file called simu.org:
* Simu

`simu` is a program to simulate counting up to a certain number.

The program has two main parts:

** Gathering input

We simply get the first parameter, panicking if there is nothing specified.

#+name: gather-input
#+begin_src rust :noweb yes :comments noweb
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
    panic!("No argument provided");
}
<<parse-input>>
#+end_src

This uses the `env` package, so we should add it:

#+name: imports
#+begin_src rust :noweb yes :comments noweb
use std::env;
#+end_src

The input is provided as a string, so we need to parse, and report error if it fails.

#+name: parse-input
#+begin_src rust :noweb yes :comments noweb
let count = args[1].parse::<i32>().unwrap();
#+end_src

** Counting up to the number

The loop is pretty straigforward:

#+name: count
#+begin_src rust :noweb yes :comments noweb
let mut i = 0;
while i < count {
    <<print-current-number>>
    i = i+1;
}
#+end_src

Displaying the counter is a matter of presentation:

#+name: print-current-number
#+begin_src rust :noweb yes :comments noweb
println!("Current number is {}", i);
#+end_src

** Tying things up

#+name: main
#+begin_src rust :tangle main.rs :noweb yes :comments noweb
<<imports>>
fn main() {
    <<gather-input>>
    <<count>>
}
#+end_src

Using org-babel-tangle creates the following file main.rs next to simu.org:
// [[file:simu.org::main][main]]
// [[file:simu.org::imports][imports]]
use std::env;
// imports ends here
fn main() {
    // [[file:simu.org::gather-input][gather-input]]
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("No argument provided");
    }
    // [[file:simu.org::parse-input][parse-input]]
    let count = args[1].parse::<i32>().unwrap();
    // parse-input ends here
    // gather-input ends here
    // [[file:simu.org::count][count]]
    let mut i = 0;
    while i < count {
        // [[file:simu.org::print-current-number][print-current-number]]
        println!("Current number is {}", i);
        // print-current-number ends here
        i = i+1;
    }
    // count ends here
}
// main ends here

The tangled program works. But, if I open a buffer on the generated main.rs, and I edit the content of the generic code, my understanding is that using org-babel-detangle should edit the source simu.org file.
However, I only get the error Not in tangled code.
The documentation is a bit confusing: it mentions that the :comments block header should be set to links. However, using links does not generate any comment in the output main.rs. Since I'm using noweb blocks, I assumed it had to be noweb, but it might a mistake.
What should I change ?

I get the same thing and I think it's a bug. Please report it with M-x org-submit-bug-report.


text:
consult-find - live preview result without close minibuffer?
Emacs 27.1
package consult.
Here my init.el for package "consult":
    (use-package consult
  :bind (
     ;; C-c bindings (mode-specific-map)
         ("C-c M-x" . consult-mode-command)
         ("C-c h" . consult-history)
         ("C-c k" . consult-kmacro)
         ("C-c m" . consult-man)
         ("C-c i" . consult-info)
         ([remap Info-search] . consult-info)
         ;; C-x bindings (ctl-x-map)
         ("C-x M-:" . consult-complex-command)     ;; orig. repeat-complex-command
         ;; Filtering: press "b" -> space = [Buffer], "f" -> Space = [File], "m" -> Space = [Bookmarks] and so on.
     ("C-x b" . consult-buffer)                ;; orig. switch-to-buffer
         ("C-x 4 b" . consult-buffer-other-window) ;; orig. switch-to-buffer-other-window
         ("C-x 5 b" . consult-buffer-other-frame)  ;; orig. switch-to-buffer-other-frame
         ("C-x r b" . consult-bookmark)            ;; orig. bookmark-jump
     ("C-x C-r" . consult-recent-file)         ;; Select from recent files with preview.
         ("C-x p b" . consult-project-buffer)      ;; orig. project-switch-to-buffer
         ;; Custom M-# bindings for fast register access
         ("M-#" . consult-register-load)
         ("M-'" . consult-register-store)          ;; orig. abbrev-prefix-mark (unrelated)
         ("C-M-#" . consult-register)
         ;; Other custom bindings
         ("M-y" . consult-yank-pop)                ;; orig. yank-pop
         ;; M-g bindings (goto-map)
         ("M-g e" . consult-compile-error)
         ("M-g f" . consult-flymake)               ;; Alternative: consult-flycheck
         ("M-g g" . consult-goto-line)             ;; orig. goto-line
         ("M-g o" . consult-outline)               ;; Alternative: consult-org-heading
         ("M-g m" . consult-mark)
         ("M-g k" . consult-global-mark)
         ("M-g i" . consult-imenu)
         ("M-g I" . consult-imenu-multi)
         ;; M-s bindings (search-map)
         ("M-s d" . consult-find)
         ("M-s D" . consult-locate)
         ("M-s g" . consult-grep)
         ("M-s G" . consult-git-grep)
         ("M-s r" . consult-ripgrep)
         ("M-s l" . consult-line)
         ("M-s L" . consult-line-multi)
         ("M-s k" . consult-keep-lines)
         ("M-s u" . consult-focus-lines)
         ;; Isearch integration
         ("M-s e" . consult-isearch-history)
         :map isearch-mode-map
         ("M-e" . consult-isearch-history)         ;; orig. isearch-edit-string
         ("M-s e" . consult-isearch-history)       ;; orig. isearch-edit-string
         ("M-s l" . consult-line)                  ;; needed by consult-line to detect isearch
         ("M-s L" . consult-line-multi)            ;; needed by consult-line to detect isearch
         ;; Minibuffer history
         :map minibuffer-local-map
         ("M-s" . consult-history)                 ;; orig. next-matching-history-element
         ("M-r" . consult-history))                ;; orig. previous-matching-history-element

  ;; Enable automatic preview at point in the *Completions* buffer. This is
  ;; relevant when you use the default completion UI.
  :hook (completion-list-mode . consult-preview-at-point-mode)

  ;; The :init configuration is always executed (Not lazy)
  :init (message "consult - I'm always here at startup")

  ;; Optionally configure the register formatting. This improves the register
  ;; preview for `consult-register', `consult-register-load',
  ;; `consult-register-store' and the Emacs built-ins.
  (setq register-preview-delay 0.5
        register-preview-function #'consult-register-format)

  ;; Optionally tweak the register preview window.
  ;; This adds thin lines, sorting and hides the mode line of the window.
  (advice-add #'register-preview :override #'consult-register-window)

  ;; Use Consult to select xref locations with preview
  (setq xref-show-xrefs-function #'consult-xref
        xref-show-definitions-function #'consult-xref)

  ;; Configure other variables and modes in the :config section,
  ;; after lazily loading the package.
  :config (message "consult - I'm always here after the package is loaded")

  ;; To correct show Recentf-dirs. M-x consult-dir, then press "r" - [Recentf-dirs])
  ;; But not correct work M-x consult-recent-file
  (add-hook 'dired-mode-hook (lambda () (recentf-add-file default-directory)))

  ;; For some commands and buffer sources it is useful to configure the
  ;; :preview-key on a per-command basis using the `consult-customize' macro.
  (consult-customize
   consult-theme :preview-key '(:debounce 0.2 any)
   consult-ripgrep consult-git-grep consult-grep
   consult-bookmark consult-recent-file consult-xref
   consult--source-bookmark consult--source-file-register
   consult--source-recent-file consult--source-project-recent-file
   consult-buffer
   :preview-key '("M-.")
   :preview-key '(:debounce 0.4 any)
   ;; For `consult-line' change the prompt and specify multiple preview
   ;; keybindings. Note that you should bind <S-up> and <S-down> in the
   ;; 'minibuffer-local-completion-map' or 'vertico-map' to the commands which
   ;; select the previous or next candidate.
   consult-line :prompt "Search: "
   :preview-key '("M-."))

  ;; Optionally configure the narrowing key.
  ;; Both < and C-+ work reasonably well.
  ;;(setq consult-narrow-key "<") ;; "C-+"

  ;; Optionally make narrowing help available in the minibuffer.
  ;; You may want to use `embark-prefix-help-command' or which-key instead.
  (define-key consult-narrow-map (vconcat consult-narrow-key "?")
  )

Now I find files:
M-x consult-find
test

Here result:

If I press M-. its open selected file and CLOSE minibuffer.
But I need to preview selected files WITHOUT close minibuffer.


text:
error in melpa installation of ac-rtags
When I install ac-rtags from melpa (M-x list-package) I have this error :
ac-rtags.el:33:11: Warning: Package cl is deprecated
ac-rtags.el:33:2: Error: Eager macro-expansion failure: (wrong-number-of-arguments (3 . 4) 2)

I tried to change my emacs version, but no difference.
In my init.el, concerning MELPA, I just have :
(add-to-list 'package-archives
             '("melpa-stable" . "https://stable.melpa.org/packages/"))

Is it only this package that causes problems? Have you tried to install other packages? What happens if you M-x toggle-debug-on-error? Do you get a backtrace? If so, add it to your question. Have you tried starting with emacs -q and doing the add-to-list above manually in your *scratch* buffer? If that works, your init file is at fault.


text:
having fill-region, or fill-column, work with text-scale-mode
i'd like to be able to programmatically (re-)fill text in a buffer after scaling text with C-x +.
i understand i could add a hook to text-scale-mode-hook, but if i call (frame-width) or (window-width) or (window-body-width) after scaling, it doesn't take the scaling into account and so gives a much higher value than what i would need to set the fill-column to before filling.
it is possible to set the fill column taking scaling into account, or to fill scaled text accurately in another way?
the manual pages on filling and on text-scale don't mention the issue of combining the two things.

Use window-max-chars-per-line instead of window-width or window-body-width? Do you need frame-width at all here?


text:
Is it possible to refile using regexp applied to some property?
If I do M-x org-refile on qux using the first (commented out) version of org-refile-targets, it brings up Foo, as expected. Using the second version, I get "No refile targets", whereas I would like Bar. Is it too far fetched to ask emacs to do that, or there is a way?
init.el:
  (use-package org
    :config
    ;;   (setq org-refile-targets '((nil :tag . "refile"))) ; version 1
        (setq org-refile-targets '((nil :regexp . ".+\n:PROPERTIES:\n:refile:   true\n:END:"))) ; version 2
    )

debug.org:
* Foo                                                                :refile:

* Bar
:PROPERTIES:
:refile:   true
:END:

* Inbox
** qux

No, the regexp matches only the headline, not anything after it. C-h v org-refile-targets says "... - a cons cell (:regexp . "REGEXP") with a regular expression matching
headlines that are refiling targets.... ". AFAIK, you cannot use a property to specify the target headlines: you'd have to do some preprocessing to find all of them and add them to org-refile-targets before you do org-refile.

Here's an implementation of the preprocessing idea from my comment:
#+begin_src elisp
  (defun my/refiling-headline-list ()
    (org-map-entries (lambda () (nth 4 (org-heading-components))) "refile=\"true\"" 'file))

  (defun my/org-refile-with-properties ()
    (interactive)
    (let ((org-refile-targets `((nil :regexp . ,(mapconcat #'identity (my/refiling-headline-list) "\\|")))))
      (org-refile)))
#+end_src

Then instead of M-x org-refile, you do M-x my/org-refile-with-properties.
We let-bind org-refile-targets around a call to org-refile, where we set the variable using the :regexp specification, with a regexp that consists of the headlines of all the sections that have a refile property that is equal to true. We construct that regexp by concatenating all such headlines with a \| alternation operator between the headlines (we have to double the backslash in the string).
The list of headlines with the given property is obtained by calling org-map-entries: it visits each headline in the file that matches the property and applies a function on each one, where in this case the function just returns the text of the headline. org-map-properties, like all mapping functions, returns a list of all the results.
See the doc string of org-map-entries for information about the function and its arguments: C-h f org-map-entries. More information and some examples are available in the section  Using the Mapping API in the Org mode manual. You can also search this site for org-map-entries: there are many examples of its use.
In the example, calling my/refiling-headline-list would return the list ("Bar") since that's the only headline with the property. In general, it would return a list of all such headlines: ("Bar" "Baz" ...). In the latter case, the mapconcat call would return the string "Bar\\|Baz\\|..." with all the headline strings concatenated and separated by an alternation operator.
This implementation only works for the current file: the refile targets have to be in the same file as the item to be refiled; that limitation comes about by the very simple implementation of my/refiling-headline-list which only looks in the current file and by the nil file specification in the let-binding of org-refile-targets in my/org-refile-with-properties. It is quite possible to extend it so that the refile targets from multiple files are made available, but for now, that's left as an exercise for the interested reader.

IT worked. I expected a 3 instead of nth 4... I presume 'file stands for current file. Where would I find this?

See the last paragraph of the (edited) answer for the current-file limitation.  C-h f org-map-entries describes the function and its arguments and the Using the Mapping API in the manual has a more extended description and some examples. In addition, I and others have used it a number of times in answers on Emacs SE, so searching the site for org-map-entries should provide more examples.

Do you mean you expected (nth 3 ...) rather than (nth 4 ...)? org-heading-components returns  a list (level reduced-level todo priority headline tags) so the headline that I want to extract is the fifth element of the returned list. nth starts counting from 0, so (nth 4 ...) returns that fifth element (which is not starring Milla Jovovich or Bruce Willis...)

I tested this further, it won't work unless the heading whose property meets the requirement is unique. For instance in this set up, the refiled entry will come under the first Inbox.
* bar\n** Inbox\n* foo\n** Inbox\n:PROPERTIES:\n:refile:   true\n:END:\n. To discriminate among nodes with identical headings I was thinking about replacing refile: true with refile:[identifier] and prompting the identifier in place of the heading. But I haven't been able to pull it off.

That's the disadvantage of using a general mechanism like regexps to search for a headline: uniqueness in headline names is required in order for the search to find a single result. You could decorate all the entries that my/refiling-headline-list returns in the list with the point of the headline where the property is found (so the return value would be ((<headline> <pos>) ...), i.e. a list of two-element lists) and then use rfloc to zero-in on a specific headline.

I solved the problem in case you haven't noticed it.

Sorry - I didn't notice. Yes, that's basically what I had in mind except for the org-element-* usage which is probably the better way to go.

Based on my last comment, here's the first half of a possible answer. Speculative: the second half would consist in invoking org-refile using RFLOC.
#+begin_src elisp
(defun my/get-refile-value-begin ()
  ;; (interactive)
  (let ((tree (org-element-parse-buffer 'headline))
        (matches '()))
    (org-element-map tree 'headline
      (lambda (element)
        (when (org-element-property :REFILE element)
          (push (list (org-element-property :REFILE element) (org-element-property :begin element)) matches)))
      nil nil nil)
    matches)) ;; C-x C-e
#end_src

Notice this oddity: :refile is internally stored as :REFILE.
Update: this work for either of foo or bar using the sample buffer.
#+begin_src elisp
(defun my/org-refile ()
  (interactive)
  (let* ((rfloc-pairs (my/get-refile-value-begin))
         (rfloc-values (mapcar #'car rfloc-pairs))
         (the-value (completing-read "Select refile target: " rfloc-values nil t))
         (rfloc-match (assoc the-value rfloc-pairs)))
        (org-refile nil nil (list (car rfloc-match) (buffer-file-name) nil (car (cdr rfloc-match)))))) ;; C-x C-e
#end_src

Buffer:
* bar
** Inbox
:PROPERTIES:
:refile: bar
:END:

* foo
** Inbox
:PROPERTIES:
:refile: foo
:END:

# C-x C-e after:
(my/get-refile-value-begin)
# yields:
# (("foo" 1201) ("bar" 1153))

Envisaged workflow:

org-capture RET key RET new entry
my/org-refile RET foo|bar
Manually rearrange new entry inside the chosen target

I didn't know about the upper-casing of property names, but it is documented in the doc string of org-element-headline-parser. I believe the reason is that all the standard properties that the parser itself adds to the returned parse tree (:begin, :end, :contents-begin etc) are in lower case, so upper-casing user-defined properties makes sure that they don't conflict  with those.


text:
Does there exist an equivalent of md-block for direct inclusion of org-mode file in a webpage?
The md-block library can directly render a markdown file in a browser:
How to Render Markdown on a Web Page With md-block
I'm already aware of the HTML export functionality in org-mode. This question is about rendering org-mode files directly inside a webpage without access to emacs.


text:
How do I properly use evil-set-jump? Doesn't seem to work if I pass a point position
I have my own function that essentially wraps outline-up-heading in Org-mode. It doesn't seem to take into account Evil's jump points, so Evil's C-o takes me to elsewhere. I'm trying to add support for Evil's jump points, but with a dubitable outcome. Evil doesn't have too much in terms of documentation for internal features and use of its functions, so idk if I'm approaching it wrong or it's a bug in Evil.
If I try to be smart and don't always create the jump point, for the case of when the current outline level is already the top—then C-o still doesn't work properly, and takes me e.g. to the previously edited file:
(defun my-outline-up-heading (arg &optional invisible-ok)
  (interactive "p")
  (let ((original-point (point))
        (original-line-number (line-number-at-pos)))
    (outline-up-heading arg invisible-ok)
    (when (not (equal original-line-number (line-number-at-pos)))
      (evil-set-jump original-point))))

However, if I just set the jump point regardless of conditions, then C-o works just fine:
(defun my-outline-up-heading (arg &optional invisible-ok)
  (interactive "p")
  (evil-set-jump)
  (outline-up-heading arg invisible-ok))

In the first variant, the condition triggers, but it looks like evil-set-jump with the argument does nothing. Is there a way to make it work?


text:
use of AltGr key
I’m using Emacs with a Bépo keyboard (which is specialized for the French langage and code). I’ve never had the problem before (either with Linux or Windows) but now on my last install (with WSL: Windows Subsystem for Linux, Ubuntu) the following problem occurs:
Characters like ">" and "{" are only reachable with the AltGr key, for instance "}" is AltGr + x and so M-} which I use to go down one paragraph is now Alt+[AltGr+x]: the problem is emacs doesn’t seem to understand it, it simply considers Alt+x and so I find myself whithin the prompt buffer. On the other hand AltGr+x alone works well as it writes "}" whithin the current buffer.
Actually, for all combinations Alt+[AltGr + key] emacs understands Alt+key.
As a complement, when I use screenkey to check what’s really been typped, AltGr+x shows ISO_Level3_Shift }: does this mean the problem comes from the OS and not emacs?
Thanks.


text:
How to align a region on &?
I thought M-x align-regexp & 1 1 y on the region containing &'s would align all columns, but it does not, so I must be using it wrong. What is the correct way? Reminder: man says white spaces taken care of in interactive mode.
Baseline:
    \begin{tabular}{clccc}
      \toprule %
 $D$ & & $P_u$ & $\sigma_N $ \\
 (in) & & (lbs) & (psi) \\\otoprule %
 5 & test 1 & 285 & 38.00 \\
 & test 2 & 287 & 38.27 \\
 & test 3 & 230 & 30.67 \\\midrule
 10 & test 1 & 430 & 28.67 \\
 & test 2 & 433 & 28.87 \\
 & test 3 & 431 & 28.73 \\\bottomrule
    \end{tabular}

M-x align-regexp &:
    \begin{tabular}{clccc}
      \toprule %
 $D$  & & $P_u$ & $\sigma_N $ \\
 (in) & & (lbs) & (psi) \\\otoprule %
 5    & test 1 & 285 & 38.00 \\
      & test 2 & 287 & 38.27 \\
      & test 3 & 230 & 30.67 \\\midrule
 10   & test 1 & 430 & 28.67 \\
      & test 2 & 433 & 28.87 \\
      & test 3 & 431 & 28.73 \\\bottomrule
    \end{tabular}
  \end{table}

C-h a align-regexp:

align-regexp is an autoloaded interactive byte-compiled Lisp function
in ‘align.el’.
(align-regexp BEG END REGEXP &optional GROUP SPACING REPEAT)
Align the current region using an ad-hoc rule read from the
minibuffer. BEG and END mark the limits of the region.  Interactively,
this function prompts for the regular expression REGEXP to align with.
For example, let’s say you had a list of phone numbers, and wanted to
align them so that the opening parentheses would line up:
Fred (123) 456-7890
Alice (123) 456-7890
Mary-Anne (123) 456-7890
Joe (123) 456-7890

There is no predefined rule to handle this, but interactively, all you
would have to do is to mark the region, call ‘align-regexp’ and enter
"(".
REGEXP must contain at least one parenthesized subexpression,
typically whitespace of the form "\(\s-*\)", but in interactive
use, this is automatically added to the start of your regular
expression after you enter it.  Interactively, you only need to supply
the characters to be lined up, and any preceding whitespace is
replaced.
Non-interactively (or if you specify a prefix argument), you must
enter the full regular expression, including the subexpression.
Interactively, the function also then prompts for which subexpression
parenthesis GROUP (default 1) within REGEXP to modify, the amount of
SPACING (default ‘align-default-spacing’) to use, and whether or not
to REPEAT the rule throughout the line.
See ‘align-rules-list’ for more information about these options.
The non-interactive form of the previous example would look something
like:   (align-regexp (point-min) (point-max) "\(\s-*\)(")
This function is a nothing more than a small wrapper that helps you
construct a rule to pass to ‘align-region’, which does the real work.
Probably introduced at or before Emacs version 26.1.

UPDATE:
Based on the answer I did/got

C-u M-x align-regexp

"complex align using regexp:" \(\s-*\)&

"Parenthesis group to modify (negative to justify):" 1

"Amount of spacing (column if negative):" 1

"Repeat throughout line:" y
  \begin{tabular}{clccc}
    \toprule %
  $D$                          &        & $P_u$ & $\sigma_N $ \\
  (in)                         &        & (lbs) & (psi) \\\otoprule %
  5                            & test 1 & 285   & 38.00 \\
                               & test 2 & 287   & 38.27 \\
                               & test 3 & 230   & 30.67 \\\midrule
  10                           & test 1 & 430   & 28.67 \\
                               & test 2 & 433   & 28.87 \\
                               & test 3 & 431   & 28.73  \\\bottomrule
  \end{tabular}

Note this particular paragraph from the documentation:
Interactively, if you specify a prefix argument, the function
will guide you through entering the full regular expression, and
then prompts for which subexpression parenthesis GROUP (default
1) within REGEXP to modify, the amount of SPACING (default
align-default-spacing) to use, and whether or not to REPEAT the
rule throughout the line.

In particular, notice that it only asks for the user to interactively specify these arguments if the user gives a prefix argument. You need to do C-u M-x align-regexp, and then it asks the additional questions.

I've updated accordingly: it is aligned throughout on &, but there is a big space in column 1.

Do you have other tables in the same document that you are aligning? Remember, this doesn’t know where the tables start and end, so it lines them all up.

Even if I select a region (as I did)? PS: there are a few isolated & in the file that could be corrupting the result because I tried in scratch and it worked.

FWIW, I don't get the big space in column 1.

Since this is a LaTeX file, I assume you are using LaTeX mode (AUCTeX). So you can place the cursor anywhere in the tabular environment and use M-x align-current. Actually, given the starting code (ugly ;), I advise to select first the whole tabular environment and use C-c C-q C-r (which runs the command LaTeX-fill-region).
After these two steps, I end up with :
\begin{tabular}{clccc}
  \toprule %
  $D$  &        & $P_u$ & $\sigma_N $ \\
  (in) &        & (lbs) & (psi)       \\\otoprule %
  5    & test 1 & 285   & 38.00       \\
       & test 2 & 287   & 38.27       \\
       & test 3 & 230   & 30.67       \\\midrule
  10   & test 1 & 430   & 28.67       \\
       & test 2 & 433   & 28.87       \\
       & test 3 & 431   & 28.73       \\\bottomrule
\end{tabular}

What does C-q-r mean? What do I have to type? What function is bound to it?

@NickD Sorry, I meant C-c C-q C-r, which runs the command LaTeX-fill-region. I'll fix my answer.


text:
What function is behind org-agenda matching?
I'd like to identify entries nested under entry foo that don't match under="foo". If I do M-x org-agenda RET m under<>"foo", I get the matches across all files specified in org-agenda-files = overkill. What would be sensible ways to approach this problem?
* foo
** A
:PROPERTIES:
:under:    foo
:END:
** B
:PROPERTIES:
:under:    bar
:END:
** C
:PROPERTIES:
:under:    foo
:END:
* bar
** D
:PROPERTIES:
:under:    bar
:END:

There is a very general method of changing the behavior of a function that depends on a global variable: you let-bind the variable to a different value around the call to the function. In this particular case, you can let-bind org-agenda-files to a list consisting of the current file only and call whatever function the m key in the agenda menu calls. When that function decides what files to apply itself to, it will consult the variable, find the let-bound value and proceed with that - the global value is shadowed by the let-bound value. In fact I used this method in the answer to a different question of yours where I let bound org-refile-targets around a call to org-refile -- that attests to the method's generality and applicability to different circumstances.
In this case, the m key in the org agenda menu calls the function org-tags-view (do C-h f org-agenda to see that). So we can do the following:
(defun my/org-tags-view ()
   (interactive)
   (let ((org-agenda-files (list (buffer-file-name))))
     (org-tags-view)))

Now call it with M-x my/org-tags-view.

EDIT 1: In fact, it's not necessary to use org-tags-view. You can use org-sparse-tree which limits itself to the current buffer: C-c /

EDIT 2: I missed the other half of the question (not an excuse: that's partly the reason that it's a good idea to have one question per question), but it is not difficult to do what you want. Your search m RET under<>"foo" already does most of the job. To finish it, all you have to do is find the foo subtree and narrow the view to the subtree: C-x n s bound to org-narrow-to-subtree. Of course, you can do the narrowing first if you want. Narrowing is not specific to Org mode (although narrowing a subtree definitely is): you can narrow to a region in general. Undoing the narrowing is called widening and is done with M-x widen which is bound to C-x n w.

This locally resets org-agenda-files to buffer-file-name and then invokes org-tags-view which is the function behind the functionality considered: that's insightful, but it solves only ½ of the problem. The other  ½ in the use case: "[only] entries nested under entry foo"

M-x org-sparse-subtree m RET under<>"foo" does most of the job, but org-narrow-to-subtree on foo would have to come first. And the problem is, I don't know how to undo it: clicking on "mouse-2 remove narrowing from buffer" does nothing.

I did the narrowing last and it seemed to work fine: what problem are you having? As for undoing the narrowing,  C-x n w (bound to widen) should do it.

Remider to m/s: undo M-x org-sparse-tree RET m RET topic="foo" with C-c C-c.


text:
Org-mode coloring text in a table cell
Please consider the following example. It is to color coordinate table cell contents.
| Name | Age | Color |
|------+-----+-------|
| John |  25 | red   |
| Mary |  30 | green |
| Tom  |  40 | blue  |

#+TBLFM: $3='(progn (cond ((string= $3 "red") "[:foreground \"red\"]")
                       ((string= $3 "green") "[:foreground \"green\"]")
                       ((string= $3 "blue") "[:foreground \"blue\"]")
                       (t "")))::

It does not seem to work. How can I get it to work?
What's the simplest way to colorize text in an org-mode table cell depending on say a threshold value in the cell? Alternative solutions welcome. It can't be this difficult.
Something along these lines does not seem to work either:
| Column 1 | Column 2 |
|----------+----------|
| foo      |       42 |
| bar      |       69 |
| baz      |     1337 |
|----------+----------|
#+TBLFM: $2='(format "[%s]" (propertize $2 'font-lock-face '(:foreground "red")))

The format of the cell content changes but not the color. WTH??!!
Rather than spending an inordinate amount of time on this seemingly trivial problem, I got the above examples from ChatGPT. None of which work. Hmm.. I now have a collection of such examples all from various queries of ChatGPT to try and none of them work.

Showing code that does not work does not tell what you are looking for. You need to say what you expect to happen. In particular, what does "color coordinate table cell contents" mean? It appears that you want something in the first row to be colored red, something in the second row to be colored green and so on. But it is not clear what that something is supposed to be: every cell in the row? the cell in the third column of the row? something else?

Isn't it obvious what this example ought to do? The table formula (TBLFM) applied to the 3rd column should yield colored text in the respective rows. It's not happening.

Not to me. As I said, showing non-working code without explaining what it is supposed to do is worse than useless: one has to figure out what you want (mostly by guessing at this point) and then figure out how to modify the code to do that; if one guesses wrong about what you want (as I did in your previous question), then I can go down the wrong path for quite a while before realizing that you meant something else. So by all means, include what you tried: but first explain what you want to accomplish as completely and as precisely as possible.

See https://emacs.stackexchange.com/questions/7375/can-i-format-cells-in-an-org-mode-table-differently-depending-on-a-formula and https://emacs.stackexchange.com/questions/66708/how-to-format-cells-of-orgmode-table-with-colors-according-to-its-string.

I'm aware of those threads. The solutions are so dastardly complicated. I wish to give the question another shot. I'm looking for a very simple solution.

"WTH??!!" - automatic fontification of the table and its contents overrides any built-in fontification you do to the string. Try (setq s (propertize "FOO" 'font-lock-face '(foreground :red))) and then M-: (insert s) in various places: outside the table you get a red FOO but inside the table you get a FOO with the org-table face.

I want to apply this to a table formula TBLFM so that I can control which columns and rows get colored. I'm not too enthusiastic about setting global variables I also want to forgo having to enable the setting manually for each cell.

The problem is that no matter what you do with the #+TBLFM line, if somebody comes later and decides to paint over what you so carefully painted, there is nothing you can do. And that's what happens here: after the formulas have been evaluated, Org mode comes along and re-aligns the table (by calling org-table-align) and that . I don't know of any way to do what you ask, not without forking the Org mode code.

Indeed, if you disable font-lock-mode, then the second example, with font-lock-face replaced by face, works fine. Although it is nice that org-table gets fontified, I think it does not justify 'breaking' this quite nice functionality. At first sight, it anyway seems a little strange choice, to make fontification 'have priority over' custom face properties. Maybe I just don't fully understand things, but otherwise, I guess this would make a nice discussion/bug report.


text:
easypg wants to encrypt authinfo.gpg with my expired key
I have a .authinfo.gpg that I've previously encrypted with a private key.  That key has expired so I created a new key for myself.  However, I now can't save edits to authinfo.gpg because it keeps wanting to use the expired key.  How can I tell easypg to use my new key?


text:
Is there a way to escape `|` inside tables?
If I tab this:
| Expression | Meaning |
|---+---|
| /a|b/ | a or b |

I get this:
| Expression | Meaning |        |
|------------+---------+--------|
| /a         | b/      | a or b |
|            |         |        |

Is there a workaround?
https://orgmode.org/manual/Tables.html

It depends on what you are looking for. The answer describes the standard recommendation (see footnote) to have a vertical bar when exporting. There is no way to escape it in the Org mode buffer itself. See this question for some other possibilities.

For me \vert{} works as in:
| Expression  | Meaning |
|-------------+---------|
| /a\vert{}b/ | a or b  |

HTML output:


text:
elpy can't find new python version (upgraded from 3.9 to 3.11)
I've upgraded from python 3.9 to 3.11 on my windows machine (on that I don't have admin rights). I used emacs (elpy) before to manage my python projects. Unfortunately, after the upgrade it seems elpy can't find the new interpreter. It still looks for python 3.9 although the virtualenv rebuild with 3.11
Elpy Configuration

Emacs.............: 28.1
Elpy..............: Not found (Python), 1.35.0 (Emacs Lisp)
Virtualenv........: srv (c:/Users/ca/srv/)
Interactive Python: ipython 8.13.1 (c:/Users/ca/srv/Scripts/ipython.exe)
RPC virtualenv....: rpc-venv (c:/Users/ca/AppData/Roaming/.emacs.d/elpy/rpc-venv)
 Python...........: c:/Windows/py.exe nil (c:/Windows/py.exe)
 Jedi.............: Not found
 Autopep8.........: Not found
 Yapf.............: Not found
 Black............: Not found
Syntax checker....: Not found (flake8)

However, if I activate the virtualenv in the prompt shell I can start python 3.11 correctly.
(srv) C:\Users\ca>ipython
Python 3.11.1 (tags/v3.11.1:a7a450f, Dec  6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.13.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: quit()

Happy to provide any other information (like init.el etc) that might help to resolve the problem


text:
ivy-switch-buffer, Narrow Results
When I C-x b with ivy-switch-buffer, I see that I have a README.md on line 6.
If I enter md, I see that the README.md is now on line 13.
How can that be?
The first results are nonsensical, like helm-mode-magit-show-commit; why would it show that before my README.md file, which I had opened like 1 minute ago?
Is there a way to prioritize recent files here or something?;)


text:
Using Windows git.exe with Magit on WSL2 Hangs on commit
I currenlty run emacs-nox on WSL2. My workflow is as such:
[Gentoo Linux Host] –ssh–> [WSL2 Ubuntu 22.04.2 LTS (Windows VM)] –open–> [emacs] –edit–> /mnt/c/<Path>/<Files>
There is a significant performance increase to using the windows git.exe instead of the one on Ubuntu in wsl as I am working primarily in /mnt/c/<Path>/<Files>
I setup magit-git-executable to use windows git.exe as follows:
(when (string-match "-[Mm]icrosoft" operating-system-release)
  (setq magit-git-executable "/mnt/c/Program Files/Git/cmd/git.exe"))

It works great; however, the only thing I cannot seem to get working is magit-commit
I did manage to get it working without emacs however.
I created a script in wsl to convert the git.exe path argument to a wsl path
/usr/bin/wslemacs:
#!/bin/sh
WSL_PATH=$(wslpath -u "$1")
emacsclient "$WSL_PATH"

I then copied the command that magit-commit runs by grabbing it from M-x list-process in emacs and added -c "core.editor=wsl -e wslemacs".
git.exe --no-pager ... -c "core.editor=wsl -e wslemacs" commit --

When run from cmd.exe on windows it successfully opens COMMIT_EDITMSG in emacs running on wsl just as magit would.
I tried adding this to magit-git-global-arguments but still no luck.
I tried writing some output to a file from my wslemacs script to see if it was even being called when using magit-commit and it doesn't seem to be.
I tried using full paths to wsl and to my wslemacs script and still nothing works.
I was looking into magit-git.el and notice some stuff like magit-cygwin-mount-points that perhaps are hinting that something similar must be handled for wsl? I am really not sure.
What occurs when I try to commit in emacs with magit is it spawns a process to git.exe and it seems to just hang forever.
I tried looking at the with-editor-debug output but nothing jumps out at me. Happy to post if anyone thinks it would be helpful.
The only other thing I notice is that I think with-editor runs a separate emacs server than the one I was able to successfully commit when running git.exe directly from cmd.exe
Any help would be appreciated.
UPDATE I did a bit more digging. looks like this is the value of process-environment in the magit-start-process function in magit-process.el
"ALTERNATE_EDITOR=sh -c 'printf \"\\nWITH-EDITOR: $$ OPEN $0\\037 IN $(pwd)\\n\"; sleep 604800 & sleep=$!; trap \"kill $sleep; exit 0\" USR1; trap \"kill $sleep; exit 1\" USR2; wait $sleep'" "GIT_EDITOR=/usr/bin/emacsclient28 --socket-name=/tmp/emacs1000/server"
"LC_ALL"
"_=/usr/bin/emacs"
"OLDPWD=/mnt/c/TFSApps"
"SSH_TTY=/dev/pts/0"
"MSSQL_CLI_TELEMETRY_OPTOUT=True"
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/dev/kotlinc/bin:/home/dev/.local/bin:/opt/mssql-tools18/bin"
"XDG_DATA_DIRS=/usr/local/share:/usr/share:/var/lib/snapd/desktop"
"SSH_CLIENT=172.24.64.1 1685 2222"
"GIT_EDITOR=wsl -e wslemacs"
"SHLVL=1"
"LPASS_AGENT_TIMEOUT=43200"
"USER=dev"
"LESSOPEN=| /usr/bin/lesspipe %s"
"TERM=dumb"
"LESSCLOSE=/usr/bin/lesspipe %s %s"
"SSH_CONNECTION=172.24.64.1 1685 172.24.66.118 2222"
"LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.webp=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:"
"LANG=C.UTF-8"
"HOME=/home/dev"
"MOTD_SHOWN=pam"
"SCREENDIR=/home/dev/.screen"
"LOGNAME=dev"
"PWD=/mnt/c/TFSApps/Common/ORIFC/ORIFCXX"
"EDITOR=wsl -e wslemacs"
"JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/"
"SHELL=/bin/bash"


text:
Applying scores to Gnus groups as soon as news is fetched
I use Gnus to read Usenet. Sometimes Gnus fetches the news and shows me that there are groups with unread messages, but when I try to go into one of those groups, Gnus fetches more information and realizes that all of the unread articles have been scored down below the threshold of being visible.
This is slightly annoying—and Emacs is more than slightly configurable—so I would like to get Gnus to apply my scores in each group as soon as it has fetched news.
This is my attempt to get that behavior:
(defun enter-all-groups-to-force-scoring ()
  (gnus-message 5 "Scoring...")
  (catch 'done-looping
    (let ((seen-newsgroups '())
          (most-recent-newsgroup nil))
      (while t
        (gnus-group-select-group)
        (setq most-recent-newsgroup gnus-newsgroup-name)
        (gnus-summary-exit)
        (if (seq-contains-p seen-newsgroups most-recent-newsgroup)
          (throw 'done-looping nil)
          (setq seen-newsgroups (cons most-recent-newsgroup seen-newsgroups))))))
  (gnus-message 5 "Scoring... done"))

(add-hook 'gnus-group-prepare-hook 'enter-all-groups-to-force-scoring)
(add-hook 'gnus-after-getting-new-news-hook 'enter-all-groups-to-force-scoring)

This seems to work sometimes—I can watch as groups that had unread articles are reduced to zero unread articles. Other times, though, it seems that scores in a particular group were not applied, and I run into the sequence of events described at the top of this question.
This solution also opens the last newsgroup twice, because I wasn’t sure how else to determine that it’s done looping through the groups!
Is there a better way of accomplishing this bit of configuration?


text:
org-capture, wrong-type-argument, expand-file-name
I often see this problem when I org-capture
What I do is open this quasar-agenda buffer and kill it.
After that, the command works.
Any idea how to troubleshoot this?;)
Debugger entered--Lisp error: (wrong-type-argument stringp nil)
  expand-file-name(nil)
  userlock--check-content-unchanged("~/agenda/quasar-agenda.org")
  userlock--ask-user-about-supersession-threat("~/agenda/quasar-agenda.org")
  #f(compiled-function () #<bytecode -0x71e50740e079a7a>)()
  combine-change-calls-1(117694 117694 #f(compiled-function () #<bytecode -0x71e50740e079a7a>))
  org-paste-subtree(1 "* TODO %?\n[2023-05-07 Sun 09:33]\n[[file:/mnt/b53d6..." for-yank)
  org-capture-place-entry()
  org-capture-place-template(nil)
  org-capture(nil)
  funcall-interactively(org-capture nil)
  call-interactively(org-capture nil nil)
  command-execute(org-capture)

You should at least include your capture template in your question.


text:
How to avoid byte-compiler warnings when putting a defconst into a let?
I want to define a few constants in my emacs init file, based on running some code, like this:
(let* ((var1 ...) (var2 ...)
  ... more code here...
  (defconst env-is-ok (or var1 var2))
  (defconst env-is-v2 ...)
  (defconst env-is-v3 ...)

(if (and env-is-ok env-is-v2) ...do stuff...)

but I get a byte compiler warning on that last line, seemingly because the defconsts are not at top-level.
I think the code is semantically fine, so how do I convince emacs of that? Is there a good way to refactor so it's clearer to the compiler?

https://emacs.stackexchange.com/tags/elisp/info


text:
HTML Export of LaTeX Equations Inside Containers
While still using mathjax as the primary LaTeX renderer for equations, is
there some switch or function available to also place all equations (both inline
and those between \begin and \end) inside a div container, possibly with a
custom CSS class for additional styling?


text:
Code completion candidates displayed in minibuffer
How can I get the completion candidates to be displayed in the minibuffer (see e.g. here https://tuhdo.github.io/static/c-ide/semantic-boost-demo.gif) instead of being displayed at the cursor? The setup in the link uses company and helm. I'd like to keep it if possible.


text:
Reduce false matches of compilations errors
I am running Emacs 28.2.  After I recently upgraded from Emacs 27, I started to get a lot of false matches in the compilation buffer.  (They may have been there before, but I had to remove my customization of compilation-error-regexp-alist to get true errors to be matched.)
When I run a mvn build with M-x compile, lines like these from the logger are matching as errors:
11:17:46.123 [main] INFO c.e.m.SomeClass - Some log message

The 11 and 17 are underlined and a different color.  If I do C-h k <left-click> on that line, the help text indicates that <mouse-2> (translated from <mouse-1> runs compile-goto-error.
Since much of my compile buffer is log statements of this format, this means that click in the compilation buffer frequently brings up a dialog, asking me where the source for the file from this "error" is.
I tried to customize compilation-error-regexp-alist to remove a bunch of options that I don't use, but the error is still there.
Is there a good way to indicate that this format is not an error?  Or to easily figure out which symbol is causing the problem?  I've looked at compilation-error-regexp-alist-alist, and while I can read regex, that's a lot of complicated expressions.
I do have a lot of customizations, but when I started emacs with emacs -Q, the same thing happened.
The problem is definitely in the timestamp: I see the same behavior if my compile command is echo '12:34:56.789'
UPDATE
mvn isn't in the alist-alist, but maven is:
(insert (format "\n%s\n" (assq 'mvn compilation-error-regexp-alist-alist)))
nil
(insert (format "\n%s\n" (assq 'maven compilation-error-regexp-alist-alist)))
(maven ^\(?:\[\(?:ERROR\|\(?1:WARNING\)\|\(?2:INFO\)\)] \)?\(?3:[^
 []\(?:[^
 :]\| [^
/-]\|:[^
 []\)*\):\[\(?4:[[:digit:]]+\),\(?5:[[:digit:]]+\)]  3 4 5 (1 . 2))

Is there magic where compilation-mode reads the command and then only uses a subset of the alists?  If there is, what variables control that.  My actual compile command is mvnFind.sh ... where mvnFind.sh walks up the directory tree until it finds a pom.xml, then invokes mvn from that directory.  This lets me do M-x compile from a Java buffer and not need to open the pom or do directory gymnastics in the command.
Changing compilation-error-regexp-alist to '(maven) did fix the problem, although it does mean that compiling other languages (or probably even the project that uses grade) will lead to unrecognized real errors.

You don't need to examine all of the regexps in compilation-error-regexp-alist-alist, just the one that corresponds to your language. What does (assq 'mvn compilation-error-regexp-alist-alist) return? Best to edit your question and add that. BTW, for me that returns nil and that may be the problem you are running into, but you should take that with a large grain of salt.


text:
Tramp from Linux into a Windows machine and use the language development server from the Windows machine with eglot?
I think everything is in the title.
I use Linux on a day to day basis.
I'm going to occasionally have to edit a C# project that is on a Windows machine. There is a C# development environment installed on the Windows machine. It would make my life easier if I could do everything from my Linux machine. However it would also make my life easier if I could use the C# development server that is installed on the Windows machine.
I would like to

run emacs on Linux
modify the files of the C# project (they are on the Windows machine)
receive feedback from the C# language server that runs on the Windows machine

Is it possible to do that with eglot ?
I added this to my /home/username/.emacs file:
(require 'tramp)
(add-to-list 'tramp-connection-properties
    (list (regexp-quote "/sshx:myusername@mywindowshost:")
        "remote-shell" "git-bash.exe"))

But the connection is closed immediately.
When trying instead:
(require 'tramp)
(add-to-list 'tramp-connection-properties
    (list (regexp-quote "/sshx:myusername@mywindowshost:")
        "remote-shell" "C:\Program Files\Git\git-bash.exe"))

I get the complain that "C:\Program" is not a program. It's because of the space in "Program Files" but I don't see how to fix that, it seems that it's a bug in the "remote-shell" option of tramp, that didn't take into account possible cases with spaces in the remote shell's path.
I tried to symlink "git-bash.exe" in a directory that didn't contain spaces and use that path but then the connection closes immediately.


text:
How can I get Emacs in Windows to interactively communicate with Python matplotlib?
I am using Anaconda Python on Windows 11 and WSL2.
In VS Code (Windows) and Emacs/Eglot (WSL2), the following code runs fine when I run it interactively:
import matplotlib
import matplotlib.pyplot as plt
print(matplotlib.get_backend()) # -> is always QtAgg
plt.ion()

plt.clf()
plt.plot([1,2,3])

plt.clf()
plt.plot([4,5,6])

However, the Python interpreter always hangs on the the first plotting command (or after closing the first plot) when using Emacs/Eglot in Windows 11.
The backend is always QtAgg in every case.
What's different in the way Emacs/Eglot in Windows 11 is communicating with the Python interpreter (and how do I fix it)?


text:
How to save/revert changes to only parts of a buffer?
I'd love a partial save-buffer and/or revert-buffer (if I have one, I think I could easily enough implement the other). Perhaps where I select a region and have only changes within that region get saved.
Basically, something abstractly similar to git (add|reset|checkout|stash) -p (or like Magit's ability to really precisely stage/unstage/discard/stash changes), but for saving from buffer to file rather than from file to version control.
I would find this helpful for the same reasons that I find those things helpful in Git: it would reduce coupling between all the changes I have in-progress and the changes I am ready to promote to the next stage of testing/done-ness. I can be making one change, think of another change along the way, and now I have two changes in-flight in the buffer - once I finish one of those changes, it would be great if I could save the finished change to file on disk while holding back the drafted unfinished changes. This would be great to have at the level of my editor because then it composes with any use-case and tool.
(I would also accept an answer which provides enough of the same workflow wins - for example, if I had to build my own solution, currently the best I can come up with which actually seems doable reasonably quickly is to write a function which creates a temporary buffer with a copy of the current contents, reverts the current buffer, and then pops open a diff between the two buffers, and then I would look at existing Emacs diff and ediff functionality, and however Magit is implemented, for how to add some sort of key bindings to at least apply individual diff hunks from the temp buffer to the original buffer. Even being able to apply diff hunks directly from an editable diff-buffer-with-file diff buffer to the underlying file would be a decent 80+% solution.)

(I have just started closely looking into Ediff, in particular ediff-current-file seems promising, as something that might be very close to what I want.)


text:
Regexp for first consecutive non whitespace ending with @?
I have a mailing list whose lines contain garbage characterized by spaces, like this:

bar qux foo@mail.com

for which I want to extract foo@mail.com. I tried this unsuccessfully:
M-x query-replace-regexp RET \(.+\)\([^ ]+\)@ → \2@

Any suggestion?

To match the longest prefix ending with a space:
^\(.* \)

Note also that [^ ] matches newlines and @, so be careful with that.  To interactively enter a regexp matching neither spaces nor newlines, you can type:
[^SPCC-qC-j]
(n.b. In lisp that's just "[^ \n]").


text:
Is it possible to do soap/wsdl requests as in SoapUI?
Emacs 27.1
To work with wsdl file I use SoapUI 5.7.
Steps:

Load wsdl file to SoapUI.
As result it's show me all methods:

set credentials

Create and run any of method

And it's work just fine.
So the question is:
Is it possible to do same things in Emacs?


text:
Making global marks behave like in VIM
So, currently in Spacemacs, if i put mark on numbers or capital letters, mark is still local to the active buffer.
In VIm, if you mark with said selection of characters, it will become a global mark that can be activated from any buffer. Any ideas how to implement this behaviour without org capture or similiar workarounds?

According to vim help, numbered marks can not be set directly and should be set from the '.viminfo' file. On my Spacemacs, marks on uppercase letters are used correctly as file marks (i.e. global marks). If that is not working for you, then I guess something is broken in your configuration.


text:
Rewrite rule changes order of expression
Let's say I have a rewrite rule
L(a + b) := L(a) + L(b)
when we apply this rule to rewrite L(x+y) the result is
L(y) + L(x)
but I would like it to give
L(x) + L(y),
i.e. to keep the same order of the original expression (if possible).


text:
Wrong syntax highlighting with command substitution in sh-mode [bash]
I am using the Doom framework (3.0.0) for Emacs (28.1) on Windows 10 with MinGW64. At least for all practical purposes to the effect of my work, everything seems to be running smoothly except for the wrong syntax highlighting of command substitution in shell-mode, as you can see in the image attached below.

The defect is in the substring 's/^\([A-Z]\+\ of the sed command, which should be highlighted precisely as the remaining substring up to the closing single quotation mark. This is not a theme-dependent effect.
Any help to preserve inside the scope of command substitution the general highlighting style will be appreciated.


text:
Android emacs keyboard not popping up
I've installed f-droid emacs and i switch to messages buffer, but then the keyboard disappears and i can't get it back up since there is no keyboard icon on the corner.
I have in the Android settings that i want the keyboard to appear in the navigation bar and it usually shows, but sometimes not.
If i click on the file open menu button, i do get the keyboard back to open a new file
I guess the messages buffer is read only, so it removes the keyboard, but that's not exactly right;)


text:
How to properly use :default-directory in Flycheck checker definition?
I'm trying to use a somewhat new property that has been introduced to Flycheck checker definition syntax recently, and I don't think I'm doing it properly. I believe the :default-directory property should be passed a callable that returns the directory to be set, but I don't think it works the way I think it does.
Here's my attempt to create a new checker that works the same way as php-phpcs, but with the property specified:
(use-package! flycheck
  :config
  (flycheck-define-checker php-phpcs-jetpack
    "A PHP style checker using PHP Code Sniffer for Jetpack."
    :command ("phpcs" "--report=checkstyle"
              "-q"
              (option "--standard=" flycheck-phpcs-standard concat)
              (eval
               (-when-let* ((fname buffer-file-name)
                            (ext (file-name-extension fname)))
                 (concat "--extensions=" ext)))

              (eval (when (buffer-file-name)
                      (concat "--stdin-path=" (buffer-file-name))))
              "-")
    :standard-input t
    :error-parser flycheck-parse-checkstyle
    :default-directory (lambda () "/home/zinigor/workspace/jetpack/")
    :error-filter
    (lambda (errors)
      (flycheck-sanitize-errors
       (flycheck-remove-error-file-names "STDIN" errors)))
    :modes (php-mode php+-mode)
    :predicate flycheck-buffer-nonempty-p))

Am I using the lambda definition correctly? My main idea is to first try forcing the checker to always use a predefined directory, and then I'll expand the idea when it works for me.


text:
dvipng puts page numbers at the end of png files produced when displaying latex fragments in org-mode
I can produce latex and dvi files from latex fragments in org files. I have dvipng chosen as the way to produce an image file.  Unfortunately, it seems like dvipng puts the page number at the end of the file name (so produces file1.png from file.dvi), therefore emacs can not find the appropriate png file to display.  It is looking for file.png.  Suggestions?

You can do dvipng file.dvi -o file.png. What is the value of the image converter in the dvipng section of the variable org-preview-latex-process-alist? That's where this problem is taken care of. Find the value of the variable and add it  to your question.


text:
indentation and syntax highlighting stops working randomly
Every now and when emacs indentation and syntax highlighting stops working. This seems to affect all modes that I'm using (primarily org-mode,ess-mode and emacs-lisp-mode), and manifests itself in changes in the text not being displayed properly, such as when adding emphases in org-mode (bold, italic underline), writing comments on a newline (text is written in the normal face), adding headers/sections in org-mode (indentation and highlighting is not considered) or writing strings in ess-mode/emacs-lisp-mode. In all these situations, text is just displayed in the default face.
If I reload the file I'm working on (or restart org-mode), syntax highlighting and indentation will be applied to the text sections that didn't have it before, but text I write from that point onwards is still not properly formated (just as before, indentation and syntax highlighting is ignored). Similarly calling font-lock-update updates the syntax highlighting of already existing text, but does not correct org-mode indentation or correctly displays text I'm writing from that point onwards.
This happens to me rarely, maybe a once every couple months (and I'm using emacs almost all day every day), but when it does, I have to restart emacs, after which things work perfectly again (restarting is still a hassle tho). There are no error messages, so I don't know what is causing this phenomenon. I also can't think of a way to debug this. Any ideas how I can find out what's going on?

The strange thing is that the two (indentation and syntax highlighting) are independent of each other AFAIK, so having both of them go at the same time is ... strange. One thing that you can do when that happens is to check the minor modes of the buffer with C-h m. The minor modes appear on the first line of the *Help* buffer. They should include Font-lock in particular. The other thing that you can do is to check the bindings with C-h c or C-h k for whatever key(s) you use for indentation when things are working and then repeat when things are broken and compare the two. Good luck!


text:
Adding numbers to sub-lists?
So when you have a numbered list in Org Mode, it looks like this:

But I want my numbered lists to look like this:

With the sub-sections having the parent section's number as well. Is there any way I can do this? Any extension or anything like that?


text:
How to pass a variable to a LaTeX code block?
I'd like to set a variable to be expanded in several LaTeX code blocks. For the sake of simplicity, there is only one in this case, foo. :header-args :var is ignored: I presume because LaTeX  does not support interactive evaluation? The best I could come up with is verbose. Is there a workaround, for example by using LuaTeX?
foo.org:
#+name: x-val
#+begin_src emacs-lisp :var val=1 :exports none
val
#+end_src

#+RESULTS: x-val
: 1

#+name: foo
#+begin_src latex :noweb yes :tangle foo.tex
\documentclass{article}
\begin{document}
x = <<x-val()>>
\end{document}
#+end_src

foo.tex
\documentclass{article}
\begin{document}
x = 1
\end{document}

The first and second code blocks are evaluated with C-c C-c and C-u M-x org-babel-tangle, respectively.
UPDATE:
I tried this:
#+PROPERTY: header-args:latex :var val=1

#+name: foo
#+begin_src latex :noweb yes :tangle foo.tex
\documentclass{article}
\begin{document}
x = val
\end{document}
#+end_src

And I get this:
\documentclass{article}
\begin{document}
x = val
\end{document}

init.el (in full) contains config.el (in full) contains:
(org-babel-do-load-languages '(org-babel-load-languages '((latex . t) (python . t))))

This works:
#+name: foo
#+begin_src latex :noweb yes :tangle foo.tex :var val=1
\documentclass{article}
\begin{document}
x = val
\end{document}
#+end_src

and so does this:
#+PROPERTY: header-args:latex :var val=1

#+name: foo
#+begin_src latex :noweb yes :tangle foo.tex
\documentclass{article}
\begin{document}
x = val
\end{document}
#+end_src

You have misspelled the property: there should be no colons before or after its name: header-args, not :header-args (that's a frequent source of confusion: see this question) or you have added the PROPERTY and not activated it by pressing C-c C-c on it or closed and reopened the file (another frequent source of confusion).

This doesn't work for me, I get x=val. Updated the post to reflect it.

Which doesn't work? The first one or the second one? Or both?

OK, the property one then: did you hit C-c C-c on the #+PROPERTY line after adding it to the buffer and before tangling? Or save the file, kill the buffer and reopen the file before tangling?

The pictures show C-c C-c on the #+PROPERTY, and I also tried the self contained version. Neither works.

Both work here. Try starting with emacs -q and  as minimal an init file as possible. Maybe some package or some setting  is interfering.

I noticed an Error upon launching Emacs ("Error (usepackage) org/:init:..."), and I made the following change to the config file (1) :
$ cat ~/.emacs.d/config.el | grep -n5 'org-babel-do' | tail -n5
226-   'org-babel-load-languages
227-   '((emacs-lisp . t) ;; *the change*
228-     (latex . t)
229-     (python . t)))
230-  )

(1) which begs for either of adding, rather than setting, new languages to load, or better yet lazy loading.
And this is satisfactory:
$ touch foo.tex; truncate -s 0 foo.tex
$ emacs +1 foo.org --eval "(org-babel-tangle)"
$ cat foo.tex | grep 'x = '
x = 1

I'm not certain the above change to the configuration is responsible for the error and that in turn is responsible for the seeming satisfactory resolution of the stated problem, so I'll wait for more evidence before accepting this answer.

That's most probably the culprit.

I actually cannot reproduce the problem: doing emacs -q -l init.el foobar.org with init.el just containing the org-babel-do-load-languages to set python and latex only, I still can tangle the block or evaluate it and the val replacement happens. I think I jumped the gun here.


text:
mu4e-update process after wake up computer
every morning I turn on my MacBook Pro and Emacs always ask me this question:

I have to press 'n' 7 times in this case to escape and get control back. what causes it? and how can I avoid this type of question?


text:
Header arguments in Org mode properties: how to activate them locally?
I do C-c C-c on the property ("local set up refrehsed") and C-u M-x org-babel-tangle on the code block:
* foo

#+PROPERTY: header-args:latex :var val=1

#+name: foo
#+begin_src latex :noweb yes :tangle ../tex/foo.tex
\documentclass{article}
\begin{document}
x = val
\end{document}
#+end_src

I get this as expected.
\documentclass{article}
\begin{document}
x = 1
\end{document}

I append to the code block this and redo the same commands:
* qux
#+PROPERTY: header-args:latex :var y=1

I get this:
\documentclass{article}
\begin{document}
x = val
\end{document}

In other words, the property of the sibling node has "polluted" the local setup. How can I prevent that?
Man:
https://orgmode.org/manual/Using-Header-Arguments.html

Properties specified with a #+PROPERTY keyword are global to the file, no matter where they are defined: the last one wins. So when you added a second one for the key header-args:latex, it overrode the first one. It does not matter that you did that inside a section qux that is different from the section where the code block is located. For exactly this reason, best practice is to have the keywords up at the top of the file: that reduces the temptation to think of them as limited to a particular section[1].
There are two possibilities: you can use keyword properties and append the value of the second to the value of the first. You do that by appending a + to the name of the property:
#+PROPERTY: header-args:latex :var val=1
#+PROPERTY: header-args:latex+ :var y=1

That way, every latex source block will get both variable settings. A useful method to check is to use org-babel-get-src-block-info as described in my answer to this question.
Alternatively, you can use a property drawer in a section. That limits the property to that section (and subsections if inheritance is turned on):
* foo
:PROPERTIES:
:header-args:latex: :var val=1
:END:

#+begin_src latex :tangle /tmp/foobar.tex
  something
  x = val
  z = y
#+end_src

#+RESULTS:
#+begin_export latex
something
x = 1
z = y
#+end_export

* bar
:PROPERTIES:
:header-args:latex: :var y=1
:END:

#+begin_src latex :tangle /tmp/foobar.tex
  something
  x = val
  z = y
#+end_src

#+RESULTS:
#+begin_export latex
something
x = val
z = 1
#+end_export

Now the identical code blocks in the two sections are evaluated (and tangled) differently because each section has its own property drawer which is private to the section.
BTW, if you find the colons confusing, you are not alone. You might find my answer to a question on SO helpful.
The canonical reference for all of this is Using header arguments in the Org mode manual.

[1] Not every keyword works like the #+PROPERTY keyword. E.g. #+TITLE keywords seem to accumulate: having more that one in the file seems to produce a title that is the concatenation of all the values found in the file (I found this experimentally hence the "seems" qualification - I don't know of an "official" declaration to that effect). There is an old
and deprecated keyword, #+CATEGORY, which is specific to a section - that is used in the agenda and that's the only one I know which is section-specific. (BTW, there are also so-called affiliated keywords that are different beasts altogether: they are affiliated to a particular element - examples are a figure caption or an attribute of a table.)

Did you get this working?


text:
emacs-w3m Buffer Navigation Tree
I need to go several URLs' back, because if I just hit B, which takes me to the last URL I visited in this buffer, I get right back to where I started, because it's a redirect;)
So, how can I manage to get further up the buffer navigation tree?;)
, or maybe it's buffer navigation chain, cause I don't think w3m stores the history as a tree.
I have a w3m-history, but this seems like a global history, not a buffer history.


text:
Display Pillow image object in Babel Org Mode directly without saving into a file?
I wonder if there is any way for Babel in Org Mode to display images (from libraries like Pillow or matplotlib) "directly" without saving them into a file:
#+begin_src python
from PIL import Image
filename = 'sample-image.png'

img = Image.open(filename)

return img
#+end_src

However, the result is only:
#+RESULTS:
: <PIL.PngImagePlugin.PngImageFile image mode=RGB size=3000x1622 at 0x7F65C7170E10>

Org mode documentation has a few examples how to show images saved into a file, but I wonder if it's possible to return them from a running code directly?


text:
Keypress is not registered sometimes
I'm using evil mode and I've bound C-g to switch to normal state:
:bind
(:map evil-insert-state-map
      ("C-g" . evil-normal-state))

(:map evil-visual-state-map
      ("C-g" . evil-exit-visual-state))

But sometimes when I type quickly and press C-g, say, to exit visual state, nothing happens. I tried to debug this behaviour - it's all okay with commands, Emacs just doesn't register keypress event
Running view-lossage command (C-h l) shows that C-g hasn't been pressed
It's also all okay with my keyboard - I don't observe this behaviour in Vim (which feels less sluggish in general though)
It looks like it has something to do with how Emacs processes key events
Any help is appreciated as now I don't have ideas on how to further debug this problem or even how to google for solution

It looks like setting gc-cons-threshold variable to a high value (1 Gb) helps  - I've installed gcmh package to manage GC


text:
How can I run WSL commands from Emacs running on Windows?
There are tons of articles on how to install GNU Emacs on WSL(2) and how to work within WSL2. However, I have Emacs installed on Windows1 and would like to access the file system and commands within WSL from my Windows' Emacs installation and not bother with another installation in WSL.
I can access the filesystem via M-x dired \\wsl.localhost\\<Distribution>\\, but I'm not able to actually connect my (e)shell with WSL and run, for example, uname. Is that possible, maybe via TRAMP or similar?
TL;DR: How can I run commands within WSL from my Windows Emacs installation?
1: GNU Emacs 28.2 (build 2, x86_64-w64-mingw32) of 2022-09-13, in case an answer is depending on the version

Addendum: seems like the file access is flaky. Emacs just crashed when I tried to access the WSL files for the third time :(


text:
Append text to unfolded org-mode lines only
Sample org file:
* H1
** H1.1
*** H1.1.1
** H1.2
*** H1.2.1
** H1.3
*** H1.3.1
** H1.4
*** H1.1.1

I want to append some text to lines
** H1.2
** H1.3

First, cycle visibility of the file to show only the H1.x headlines, and not their children. I then eval (setq search-invisible nil)), and select the two headlines above. I do regexp-replace $ with foo, expecting foo to be appended to only the two lines mentioned. What actually happends is that foo is appended to all lines in the selected range, regardless of whether they are folded.
If instead I do regexp-replace H with foo, then H is replaced with foo only in the unfolded lines, which is what I want, just with a different search value ($).
Why is the regexp-replace using a $ seemingly ignoring the value of search-invisible?