text:
org-capture: prompt for a target file
Starting from the existing customization associated with key j, is there a way to view and modify the target file? In other words,

by default, captured notes would go to */journal/inbox.org,
optionally, input a different path, say */journal/pc.org.

Could you suggest ways to do that?
~/.emacs:
 '(org-capture-templates
   (quote
    (
     ("j" "Journal" entry
      (file+olp+datetree "~/Documents/write/notes/journal/inbox.org")
      "* %?
Entered on %U
  %i
  %a")
     )
    )
   )

Manual:

Handling links
Capture

One way is to write a custom function and use it as target: (function function-finding-location). But this would get complicated.

Another way is to use a variable as file and then use a wrapper around org-capture to set that variable to the desired file first:
(defvar my-org-capture-filename nil
  "File name for org capture template.")

(setq org-capture-templates
      '(("j" "journal" entry (file+olp+datetree my-org-capture-filename)
         "* %?
Entered on %U
  %i
  %a")))

(defun my-org-capture ()
  "Read file name to capture to."
  (interactive)
  (setq my-org-capture-filename
        (read-file-name "Capture to: " "~/Documents/write/notes/journal"
                        nil t "inbox.org"))
  (call-interactively #'org-capture))

Then use M-x my-org-capture

You could create a template for each file and use ji, jp etc. as  key to capture. To make the group work add ("j" "journal") in the template:
(setq org-capture-templates
      '(("j" "journal")
        ("ji" "inbox.org" entry
         (file+olp+datetree "~/Documents/write/notes/journal/inbox.org")
         "* %?
Entered on %U
  %i
  %a")
        ("jp" "pc.org" entry
         (file+olp+datetree "~/Documents/write/notes/journal/pc.org")
         "* %?
Entered on %U
  %i
  %a")))

I think there are several problems with the second solution: the read-file-name call should have the full pathname for "inbox.org" (and if that pathname starts with ~, it should probably be wrapped in an expand-file-name). I still can't get it to work ("Invalid capture target specification") but even if I got it to work, having to use a different function for this template (or having all templates go through this function and answering the question every time) would be a killer for me. I much prefer the third solution: it's closer to the spirit of how I think org-capture should be used.

The "invalid capture target specification" errors I was getting were my fault: I had switched to an older version to test something and forgot to switch back.

@NickD expand-file-name is already done inside read-file-name respectively read-file-name-default. Adapted the function call to use initial instead of default-filename to not have to use the full path.

First sol works like a charm. Got rid of %i %a, since linking to the file:header from where the capture was called not always warranted. If it is, I use M-x org-store-link.

A simple trick that works for me is to use buffer-file-name as the filename target. Applied to your example that would be:
(setq org-capture-templates
      '(("j" "Journal" entry (file+olp+datetree buffer-file-name)
         "* %?
Entered on %U
  %i
  %a")))

In the case of such a template, my workflow is to switch first to the target orgfile, and then to invoke the template.


text:
What are the key bindings relevant to week-genda view?
Reminder: one enters the week-agenda view by typing C-c a a. Only serendipitously did I find out that ! toggles "deadline inclusion". How would I find the description of similar key bindings from within Emacs, pertinent to this view?

The same way you do in most buffers:
C-hm to call describe-mode
The vast majority of modes will list their keymap as part of that help.
In cases where that doesn't show you what you wanted to see, you can call the more general describe-bindings via C-hb to list all active bindings for the buffer.  This includes the global map, and translation maps, so it's quite verbose.
In both cases you can use page navigation commands to skip between keymaps: C-x] and C-x[ for forward-page and backward-page respectively (and C-xnp to narrow-to-page).

source: Stack Exchange

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

sort: votes


text:
File tags prevent autocomplete of global tags
I amended .emacs as shown below. Then M-x load-file ~/.emacs. What I want to do in test.org is add MEntal tags to each of the two entries, for example Read and Reminder, respectively. Using the column view I type 'e' in the tags column of the first entry, then 'R'. I expect 'Read' to autocomplete, instead I get '[No match]'. Is there something wrong with the global tag hierarchy defined in .emacs?
~/.emacs:
(setq org-tag-alist '(
              (:startgrouptag)
                      ("ACTivities")
                      (:grouptags)
                      ("MEntal")
                      ("PHysical")
                      ("TRansact")
                      (:endgrouptag)
                      (:startgrouptag)
                      ("MEntal")
                      (:grouptags)
                      ("Read")
                      ("Write")
                      ("Reminder")
                      (:endgrouptag)
              )
      )

test.org:
#+TAGS: [ editor : emacs ]

* 2019
** 2019-12 December
*** 2019-12-01 Sunday
**** TODO [#C] [[http://tuhdo.github.io/helm-intro.html][Helm-intro]]                                                                  :emacs:
     - State "TODO"       from              [2019-12-01 Sun 17:31]
**** `C-u C-c C-q` to realign tags                                                                  :emacs:
   Entered on [2019-12-01 Sun 20:29]

I can reproduce this, in two ways: trying to edit the TAGS column in columns view, or using C-q without columns view. It works fine without the explicit #+TAGS entry (which is wrong by the way: the syntax is #+TAGS: tag1 tag2 tag3 .... with no square brackets and no colons AFAIK). At first sight, it looks like a bug to me.

@NickD the syntax of the in file tag specification is borrowed from the manual If I remove the line, autocomplete still ignores the globally defined tags.

Yes, you are right about the syntax. After removing the line, did you save the file, kill the buffer and reopen the file?

No, sorry, I hadn't. Now that I did, autocomplete works.  If add at the beginning, #+TAGS: tag1 tag2, and reload, it does not work. In other words local tag specs interferes. But I should be able to mix global and local tags, though.

You might want to bring it up on the Org mode mailing list.

Thanks, I just did.

This was suggested to me through the org-mode mailing list: replace ‘org-tag-persistent-alist’ instead of org-tag-alist in ~/.emacs. I tried it: autocomplete works for both the local and global tag lists.

Thanks for closing the loop!

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


text:
How to postfix with a string each line of a multiline selection?
Reminder:C-x r t string <RET> replaces rectangle contents with string on each line (string-rectangle). https://www.gnu.org/software/emacs/manual/html_node/emacs/Rectangles.html
Can I use this, or an analogue command, starting from:
{Curiosity
{Killed
{The Cat

to get:
{Curiosity}
{Killed}
{The Cat}

?

I don't use rectangles, but the multiple-cursors library by Magnar Sveen can handle this in a split-second flat.

Rectangles are irrelevant in your example. Maybe, you need to expand it to get to the point. But in your example you can just call query-replace-regexp with $ as search string and } as replacement. The command is normally bound to C-M-%


text:
Exact steps to export to an org table to csv
Sorry if this is trivial. What are the exact step to export the following table:
1) to a buffer
2) to the file specified in properties
For now if I position the cursor inside the M-x org-table-export I get a prompt for a file, not a buffer.

* FRUIT

:PROPERTIES:
:TABLE_EXPORT_FILE: ~/Desktop/tbl
:TABLE_EXPORT_FORMAT: orgtbl-to-csv
:END:

| Name      | Color |
|------------+-------|
| Blueberry  | Blue  |
| Blackberry | Black |

Not quite sure what exactly you are asking, but 1) I think org-table-export exports to a file only, 2) if there is no TABLE_EXPORT_FILE property, it will prompt for a file name, 3) in the above,there is NO such property, because there is an empty line between the headline and the properties drawer, so it is not recognized as a properties drawer. Running  M-x org-lint will flag such errors. If there is still a question, you might want to edit your question and clarify exactly what you are asking.

Another way to phrase my question, is how to make use of the properties?

As I mentioned, you have to fix the syntax error and delete the empty line between the headline (* FRUIT) and the property drawer (:PROPERTIES: ...). As it stands now, the properties are not recognized because of that syntax error.

Based on @NickD's,
* FRUIT
:PROPERTIES:
:TABLE_EXPORT_FILE: ~/Desktop/tbl
:TABLE_EXPORT_FORMAT: orgtbl-to-csv
:END:

| Desc.      | Color |
|------------+-------|
| Blueberry  | Blue  |
| Blackberry | Black |

Position the cursor inside the table and do M-x org-table-export. That will gen the following table in the stated path:
Desc.,Color
Blueberry,Blue
Blackberry,Black

In order to let :TABLE_EXPORT_FILE: work
:PROPERTIES:
:TABLE_EXPORT_FILE: ~/Desktop/tbl
:TABLE_EXPORT_FORMAT: orgtbl-to-csv
:END:

Can be put at the top of the org file


text:
How to get date+interval?
I have a deadline that is 12/12/2019+15d+1m. How would I get it in Emacs? This should be straightforward but have not found it. The right answer is 01/27.
UPDATE:
The question is not about combining two dates shifts. I'm fine with an answer to:

Could you please show me the exact steps to get get 12/12/2019+15d,
  and then 12/27/2019+1m?

What is the exact time, please, of 12/12/2019 in this example -- is it 12:00 a.m. or something other?  And, are you already aware of the functions that turn date/time/days into seconds since AD and visa/versa?

How would I know? If I click on it, it just opens the agenda for that date (like open-at-point, I think):
Thursday   12 December 2019

I could not get the date parser in Org mode to accept two specs (+1m and +15d work separately, but not together), but it seems like a reasonable request and I imagine a fairly simple change in the code. You might want to do an RFE on the Org mode mailing list.

Could you please show me the exact steps to get each to work separately? IOTW, how do I get 12/12/2019+15d, and then 12/27/2019+1m?

Why isn't this question getting an answer?

Because nobody saw your comment: if I comment, you get to see the comment because you "own" the question. But if you want me to see the comment, you have to address your comment to me, using the @NickD construct. I only saw this because you posted it as a new question, linking back to this question.

Thanks for clarifying, @nickD.

See, I saw this comment :-)


text:
How to get date+interval? (revisited)
I have a deadline that is some date in the past(such as 12/26/2019) + interval (e.g. 15d). How would I get it in Emacs? In a previous post under the same title I posted an example with interval = the sum of the two subintervals (15d+1m). Someone answered that would have to be a feature request, but was able to do it with only one interval. Actually, that is all I need, but still don't know how to do it. Would someone be so kind as to give a step by step instruction to do it?
Bottom line: how to get '12/26/2019+15d'?

Given a timestamp of 2019-12-12, you can specify ++15d (note the double plus) to move forward to 2019-12-27, then you can specify ++1m to move forward to 2020-01-27. See the section of the manual entitled The date/time prompt:

With a single plus or minus, the date is always relative to today. With a double plus or minus, it is relative to the default date.

EDIT: Here's a more detailed workflow. The simplest method I know to do what you want is to use the date/time prompt and select your initial date from the calendar: e.g. for a SCHEDULE: date, say C-c C-s and click on 2019-12-12. That makes 2019-12-12 the default date, so you can say C-c C-s again and type ++15d at the date/time prompt: that gets you to 2019-12-27 which is now the new default date. So you can do C-c C-s one more time and say ++1m at the prompt to get you to 2020-01-27. Does that help?
Note that with C-c ., every time you modify the date, the cursor ends up after the date, so if you do it again, you end up with a date range. Just move the cursor back into the date before repeating it and you will not get a second date.

I can do it like this: C-c . Dp S-< as many times as needed to get to 12-26. Then RET. Then C-c . ++15d RET, and I end up with two timestamps, one for 12-26, another for 01/10. I just need the second. It works, but is there a less cumbersome way?

Edited the answer with a more detailed workflow.

Edited again to point out why C-c . gives you a second date.


text:
TCL is adding different tab widths in the program
I am trying to rearrange the columns of below file
input.txt,
Contents of this file:
Name      Location      Purpose
---------------------------------------------
Andy      US            Business1
bob       UK            Business2

output_obtained
Name      Purpose       Location
---------------------------------------------
Andy      Business1     US
bob                     Business2     UK

Expected_output
Name      Purpose       Location
---------------------------------------------
Andy      Business1     US
bob       Business2     UK

TCL file:
set fh [open input.txt r]
set fp [open output.txt w]
while {[gets $fh line]>=0} {
if {[regexp "^-" $line]} {
puts $fp $lin
} else {
puts $fp "[lindex $line 0]\t[lindex $line 2]\t[lindex $line 1]"
}
}
close $fh
close $fp

I cannot understand why the tab is interpreted differently on the last row

What does this have to do with Emacs?

I posted it on the wrong forum. Not sure how do I delete this questions from here


text:
Capture at an arbitrary date
In this example I changed the date for Entered to 12/07/2019 at the capture editing stage. Yet it gets filed under today's date. How can file it under the right date, that is 12/07/2019? Ideally in one step. But if not, the obvious additional steps would be 1/ create a headline for 12/07/2019, and its parents. 2/ org-refile under the hl created in 1/. How to do 1/?

PS: I'm using a variant of the capture proposed here:
(defun my-org-capture ()
  "Read file name to capture to."
  (interactive)
  (setq my-org-capture-filename
        (read-file-name "Capture to: " "~/Documents/write/notes/journal"
                        "inbox.org" t))
  (call-interactively #'org-capture))

The capture template you linked to is the key here:
 ("j" "Journal" entry
      (file+olp+datetree "~/Documents/write/notes/journal/inbox.org")
      "* %?
Entered on %U
  %i
  %a")

The date you are modifying is in the content of the entry: the %U gets replaced with the current timestamp which you are then modifying.
However the 'file+olp+datetree' target defines where the entry will actually go, and in this case the default for a datetree is to add a heading for today's date. That heading is not related to the content of the entry that you are editing.
What you want here is to override the default behavior of datetree. If you always want to be prompted, add the optional :time-prompt property to your capture template. If most of the time the default behavior is what you want, you can leave the template as-is and instead use a C-1 prefix to trigger the prompt.
From the Org Template elements documentation:

 ‘:time-prompt’
      Prompt for a date/time to be used for date/week trees and when
      filling the template.  Without this property, capture uses the
      current date and time.  Even if this property has not been
      set, you can force the same behavior by calling ‘org-capture’
      with a ‘C-1’ prefix argument.

The C-1 C-c j worked, thanks. How about the rest of the question? "1/ create a headline for 12/07/2019, and its parents."


text:
Change theme when OS dark mode changes?
VS Code recently added the ability to switch themes when macOS's dark mode changes. Presumably they use the Electron API, which internally uses the Objective-C API of subscribing to the AppleInterfaceThemeChangedNotification event in NSDistributedNotificationCenter.
It would be nice if Emacs had this same ability. The pseudo-code would be:
(add-event 'os-dark-mode-changed
  (lambda (on)
    (set-theme (if on
                  some-dark-theme
                  some-light-theme))))

(In VS Code, the dark and light themes are configurable.)
Does Emacs have the ability to do something similar?

Maybe you can periodically query the dark mode status.

Then I'd have to poll, whereas macOS already provides an event for this. There was a reddit thread on this solution and it was generally thought of as being bad practice.

I’ve submitted a patch which provides an ns-dark-mode-change-hook which you could use to do this. Hopefully it will be accepted, and then a future version of Emacs will have this feature!

Using emacs-plus this is easy. See the docs, but here is the code in any case.
(defun my/apply-theme (appearance)
  "Load theme, taking current system APPEARANCE into consideration."
  (mapc #'disable-theme custom-enabled-themes)
  (pcase appearance
    ('light (load-theme 'tango t))
    ('dark (load-theme 'tango-dark t))))

(add-hook 'ns-system-appearance-change-functions #'my/apply-theme)

A work-around, more so than an answer: you can change your theme from an external process, by starting your main editor instance in server mode, and using emacsclient. E.g.
(server-start)

And:
emacsclient --eval "(my/dark-mode)" --quiet -no-wait --suppress-output -a true

It turns out that iTerm2 allows you to execute an arbitrary Python script on OS theme changes. You can use this to change iTerm2's own theme, but nothing stops you from adding a cheeky call to emacsclient and controlling Emacs along, with it.
I've combined all of this here: https://gist.github.com/hraban/8eb4ab5c110828a9d1b8c16b4f78193e.
Upside: no polling, no Emacs UI blocking, etc
Downside: iTerm2 must be running.


text:
Symbol's function definition is void: cl-loop
I'm trying to turn off all colored text when using gnu emacs as emacs -nw on linux. This answer gives a snippet of code to use for this purpose:
(cl-loop for face in (face-list) do
     (set-face-attribute face nil :foreground nil :background nil))

However, when I put this in my .emacs file, I get this error:
Symbol's function definition is void: cl-loop

How do I fix this?

cl-loop is from cl-macs.el. Have you tried adding (require 'cl-macs) before using cl-loop?

@Aquaactress cl-macs.el is an internal subpackage of the package cl-lib.el. You should always (require 'cl-lib) or (eval-when-compile (require 'cl-lib)) instead. See (cl) Organization.

That works. Aquaactress or Basil, maybe that should be an answer so I can accept it. Thanks!

@Aquaactress: I don't see that the manual section you point to says that cl-macs.el is "an internal subpackage" or that "you should always...". What it says is that you can just load cl-lib.el to get the macros (and a bunch of other stuff) autoloaded. If you only need a macro for byte-compilation I see no reason why you would necessarily want to load all that's in cl-lib.el. Of course there's nothing wrong with loading cl-lib.el, and yes, it's generally what people do who want some of its functionality.

@Drew I think you meant to reference Basil. I was not the one who referenced that section.

@Aquaactress: Yes, sorry.

@Basil: Sorry, I meant to reply to you, not Aquaactress.

The direct solution is to (require 'cl-lib) somewhere, but this is a trivial enough loop that Emacs comes with a macro specifically for it, without needing cl-lib:
(dolist (face (face-list))
  (set-face-attribute face nil :foreground nil :background nil))


text:
Disable coloring of text in operations in emacs -nw, during operations like searching
I'm using gnu emacs as emacs -nw in a terminal window. Colored text is usually almost completely illegible for me. As recommended in this answer, I have done the following in an attempt to get rid of all coloring:
(dolist (face (face-list))
  (set-face-attribute face nil :foreground nil :background nil))

However, I still get colored text when I do operations like searching. For example, if I do control-S, I get a dark blue prompt that says "I-search," and if the search is failing, then the trailing part of the search string is highlighted in pink.
Also, if I start up emacs without giving a filename, there is a help screen with hyperlinks, which are colored.
Is there some way to get rid of these other types of coloring as well?

try to start your emacs with emacs -q -nw and eval your (dolist (face ...)-expression there is no color for anything left, neither C-s nor  the greeting screen. The problem is probably somewhere in your init.

@jue: When I evaluate that lisp code using M-x eval-region, you're right, all colors immediately go away. However, it doesn't seem to be working properly when it's run initially from my .emacs file. My .emacs file is being evaluated -- I have other code in it that does have the expected effect, e.g., (menu-bar-mode 0), which does what it's supposed to do. I tried deleting everything from the .emacs file except for the code I quoted in the question, and it still doesn't work. I also tried moving other code after that code, and it still gets evaluated.

some packages define colored faces, if those packages are loaded after your dolist, then they introduce colors. You need to ensure that your dolist is evaled after loading of packages.

@jue: I see, thanks. How do I do that?

You need to run your uncolor loop after loading of any package, because packages can introduce new colored faces when they (lazy or auto) load.
To ensure all colors are removed after any loading of a package, you could use the hook after-load-function. Following code will do this:
(defun uncolor-after-load (&rest foo)
  (dolist (face (face-list))
    (set-face-attribute face nil :foreground nil :background nil)))

(add-to-list 'after-load-functions #'uncolor-after-load)

Edit: after-load-functions is a list of functions, so I changed the setq above to an add-to-list, which keeps former entries.


text:
Evil mode send escape before Alt/Meta-command
In vim one can escape normal mode by pressing Alt or Meta then pretty much any key, e.g. Met-j to escape insert mode and move down a line. Holding alt before typing would send an <Esc> key before the command.
I found it was the fastest was of escaping normal mode and has become muscle memory. I have been researching how to do this with evil mode, but haven't figured it out as there is lots of documentation about how to make evil mode quit various emacs states.

This trick is a side effect of how terminal emulators work, key combinations with meta are implemented as sending an escape key followed by the letter (unless your terminal emulator is configured to do something else like inserting an accented letter), if you try this trick in gvim, you'll notice it isn't supported there.
Emacs chose to interpret the escape key followed by a letter as an alternative way of typing the meta modifier, in order to support a greater amount of keybindings. This behavior is pretty much hardcoded and cannot be easily worked around. Instead Evil provides \ in normal state to temporarily switch to Emacs state and C-o in insert state to temporarily switch to normal state.

I used to use it in normal Vim and NeoVim-Qt. The reason I am trying out Emacs is because it apparently so much more configurable. The first thing I try to config I get the answer of its not possible. Hmmm.

Ended up doing the following: ALT+arrows or ALT+: enters normal mode. ALT+: also asks for execute command:
(defun evil-normal-state-then-ex ()
"Run 'evil-normal-state' and 'evil-ex' in sequence."
  (interactive)
  (evil-normal-state)
  (evil-ex))

(define-key evil-insert-state-map (kbd "M-h") 'evil-normal-state)
(define-key evil-insert-state-map (kbd "M-j") 'evil-normal-state)
(define-key evil-insert-state-map (kbd "M-k") 'evil-normal-state)
(define-key evil-insert-state-map (kbd "M-l") 'evil-normal-state)
(define-key evil-insert-state-map (kbd "M-:") 'evil-normal-state-then-ex)

That doesn't move the cursor after switching to normal state though or does it?

Yes it does move the cursor, and M-: will enter into command mode. Often the next thing I wish to do is move or enter a command after leaving insert mode. Unfortunately things like M-w dont work unless I map out pages of every combination or movement commands.

I do not understand why you would prefer to have some binding that would switch to normal-state instead of just staying in insert-state, and in that case you can simply bind the normal-state-commands to the key-combo's in insert-state. However, if you insist on having the inconvenient behavior of also switching to normal state (and move your finger to M instead of ESC), then in response to the answer by @wasamama (and your comment there), I would say that creating a workaround isn't that hard. You could create a binding for every key-combo starting with M in insert mode, to a function which runs the command that is bound in the evil-normal-state-map, e.g.:
(defun my-evil-normal-from-insert ()
  (interactive)
  (let ((normal-key (substring (key-description (this-command-keys)) 2)))
    (evil-normal-state)
    (funcall (alist-get (string-to-char normal-key) (cdr evil-motion-state-map)))))

If you don't want to exit from insert-state, then you could comment out evil-normal-state and have the arguably more convenient behavior.
However, many normal-state bindings (like those of j,k,h,l) are actually defined in the evil-motion-state-map, so if you only require such commands, then you could simply replace the map in the function above.
If you would like to 'remap' all keys after M with commands that can be bound in either the evil-motion-state-map or the evil-normal-state-map
then you could use the following function:
(defun my-evil-normal-from-insert ()
  (interactive)
  (let ((maps (list evil-motion-state-map evil-normal-state-map))
        (normal-key (substring (key-description (this-command-keys)) 2))
        (continue t))
    (while (and maps continue)
      (when-let (command (alist-get (string-to-char normal-key) (cdar maps)))
        ;; (evil-normal-state)
        (funcall command)
        (setq continue nil))
      (setq maps (cdr maps)))))

Then you can define the bindings for the insert-state keys that you need individually, or you could create a loop to bind most/all of them.
Here follows an example for such a loop, where I have not checked if all created bindings make sense:
(let* ((letters "qwertyuiopasdfghjklzxcvbnm")
       (capitals (upcase letters))
       (others "1234567890-=[];',./!@#$%^&*()_+{}|:<>?")
       (c-list (split-string (concat letters capitals others) "")))
  (dolist (l c-list)
    (evil-global-set-key 'insert (kbd (concat "M-" l)) #'my-evil-normal-from-insert)))

You could extend the loop if you would like to bind even more options.
I am almost sure that there must be more elegant ways to achieve this. However, I think this example already shows how 'hackable' Emacs is, by showing how often Emacs can still do things, despite those things 'being hard-coded' not to work in a certain way.

You can install the package evil-escape from MELPA. It does what you need.

From what I understand the package define more state to escape from. The trouble I am having is how to define the the key combo M-???? to be  then ????? when in insert mode.

No, it doesn't. The package is designed to give you an alternative way of exiting insert mode, whereas this is about temporarily suspending insert state.


text:
Why is appropos (C-h a) not finding all terms, e.g. backup doesnt find make-backup-file-name-function
When running C-h a then entering backup, it lists the following matches, but not all of them (e.g. does not find the make-backup-file-name-function)?
Buffer-menu-backup-unmark     M-x ... RET
   Move up and cancel all requested operations on buffer on line
   above.
diff-backup           M-x ... RET
   Diff this file with its backup file or vice versa.
dired-backup-diff         M-x ... RET
   Diff this file with its backup file or vice versa.
dired-flag-backup-files       M-x ... RET
   Flag all backup files (names ending with `~') for deletion.
ediff-backup              M-x ... RET
   Run Ediff on FILE and its backup file.
magit-wip-initial-backup-mode M-x ... RET
   Before saving a buffer for the first time, commit to a wip ref.
package-menu-backup-unmark    M-x ... RET
   Back up one line and clear any marks on that package.

C-h a apropos will show you all the different variations of apropos that you can use ;)

C-h a runs apropos-command, and so will only show you interactive commands, not variables like make-backup-file-name-function. You could use apropos-user-option in combination with a non-nil value of apropos-do-all to search more extensively.
Interactively you can use a prefix argument C-u to tell most 'apropos' commands to use their apropos-do-all behaviour.
Note that M-x apropos will show matching functions, variables, and faces.


text:
Delete from point to beginning of the line
Have read the GNU manuals on erasing, killing, and deleting.
In bash C-u deletes from the cursor to the beginning. I have searched and in much disbelief can't find out what the equivalent is in emacs? Very often in a buffer and in the minibuffer I wish to delete from the cursor to the beginning of the line.

The equivalent is C-SPC C-a C-w

Bash's C-u comes from GNU readline and can be configured via .inputrc. man bash and man readline refer to this key combo as unix-line-discard

There is C-0 C-k or C-u 0 C-k.
See section (info "(emacs) Killing by Lines").

Wow such a long keychord.

Keys are a scarce commodity, so emacs doesn't want to "waste" one unless it's absolutely necessary. If you don't like what's offered, you can add the command(s) needed to do what you want to the key(s) of your choice: see Key Bindings in the Emacs manual.

I think this answer would improve slightly with the removal of the word "possibly" from the first sentence. I'd also put C-0 C-k first, since it seems easier to type to me.

C-0 C-k does not work on macOS Big Sur. Could you replace it with M-0 C-k? Further more, it will be better if you provide the link of your ref.

A possible reference to "backward kill line"

Given all basic buffer operations chords are even longer (I'm looking at C-x k RET for example) this doesn't seem long by Emacs standards at all.

M-0 C-k should do what you want.

This seems to duplicate @marco's earliser answer.

I have C-<backspace> bound to the following function:
(defun phg/kill-to-bol ()
  "Kill from point to beginning of line."
  (interactive)
  (kill-line 0))

Basically just the C-u 0 C-k from the other answer, see kill-line.


text:
Set Consistent line spacing, irrespective of bold or underlines etc
I current have set the current line number face to be bold:
`(line-number-current-line ((,class (:foreground "#4F4F4F" :background "#00CC00" :bold t))))

When I move the cursor between lines, there is a very unpleasant movement of all the text, as the line with the bold text takes up a little more height, so that line gets taller, and then contracts when the cursor moves past it.
This is just a single example of where this issue is popping up. Another example is if any highlighting makes the word bold (e.g. matching parenthesis).
If I change the line spacing, there is just extra space between the lines, and bold text still expands even though there is adequate space.

Do you see the same thing with a different monospace font? If not, it may be because your particular font has taller bold chars (?).

@Drew was right. Instead of using the default font, I downloaded a nice mono space font from Google (Roboto Mono), and that is working fine.


text:
Custom theme only loads changes every second start-up
Using Emacs 26.3.
I made a theme file. If I change the theme, then restart Emacs the change is not applied. I have to close Emacs a second time, and then only on the second start up does the change take effect.
init.el:
(load-theme 'foo t)
(package-install-file (expand-file-name "foo-theme.el" user-emacs-directory))

Within the theme:
  ... other stuff ...
  (custom-theme-set-faces
   'foo
        ;; DEFAULT
        `(default ((,class (:foreground "#FFFFFF" :background "#000000" :distant-foreground "#000000"))))

If I perform the following:

Comment out the default face in foo-theme.el
Save foo-theme.el
Close Emacs.
Open Emacs, open foo-theme.el, I see the change is still there but the face change was not applied to the default face (Emacs looks the same).
Close Emacs.
Open Emacs, and now I see that foo-theme has been applied correctly (default face looks as it should), and the my-theme.el file remains the same.

Why does it not apply correctly on the next start up of Emacs? How to fix it to load the theme correctly (maybe it is caching it somewhere)?

More testing, if I make a change, restart, the change is not applied, then if I undo the change save, restart, then the change is applied, even though it doesnt appear in the file!

Not able to reproduce - theme settings are reloaded every restart This probably points out that the issue is elsewhere.
Here is the mock theme I am using: lisp ;; dummy theme ;; http://emacsfodder.github.io/blog/notes-on-deftheme/ (deftheme foo) (custom-theme-set-faces 'foo '(default ((t (:foreground "#00feff" :background "black")))) '(fringe ((t (:background "#00ff00"))))) (provide-theme 'foo)  In addition, I think that package-install-file might not be necessary. (load-theme 'foo t) should be sufficient (assuming custom-theme-directory is set properly). What version of emacs are

The three lines you quote from your init.el are weird.  Where do they come from?  E.g. you shouldn't re-package-install every time.  And you shouldn't have Elisp files inside user-emacs-directory (you can put them inside a subdirectory of user-emacs-directory on the other hand).

@Stefan Those lines from init.el are from me! foo-theme.el is my own custom theme placed in my .emacs.d (part of my dot emacs git check out). Why not put .el files within ~/.emacs.d, is that not what it is for?

Because .emacs.d/<foo>.el is often used by package <foo> to keep some internal information (like a history of use).  Always put your Elisp files in some subdirectory if you want to use .emacs.d, e.g. ~/.emacs.d/myfiles/<foo>.el.

My crystal ball says:

load-theme loads the theme from ~/.emacs.d/elpa/foo-theme-<version>
then package-install-file takes your ~/.emacs.d/foo-theme.el and installs it (aka copies it and compiles it) into ~/.emacs.d/elpa/foo-theme-<version>.

So the first time you run Emacs after changing ~/.emacs.d/foo-theme you load the "old" file (and copy the new file to the elpa location, so you'll get to see the change on the second invocation).

Your crystal ball was right. I changed the order to package-install-file then load-theme. Thanks!


text:
Value of confirm-kill-processes is ignored
When closing emacs, if I have unsaved buffers its a long process of having to read the questions (at first the logic is 'n' to not save and exit), then it changes to must type yes. Ideally there would be no 2nd question where one has to type out yes or no (it is redundant).
So I am trying to make it exit straight away with no questions (less ideal) with these lines in init.el:
;; Dont ask to save when quitting
(setq confirm-kill-processes nil)

But nothing of the behavior has changed. I still get asked all the same questions. If I read the help on the variable I can confirm its value has been changed to nil:
confirm-kill-processes is a variable defined in ‘files.el’.
Its value is nil
Original value was t

Documentation:
Non-nil if Emacs should confirm killing processes on exit.
If this variable is nil, the value of
‘process-query-on-exit-flag’ is ignored.  Otherwise, if there are
processes with a non-nil ‘process-query-on-exit-flag’, Emacs will
prompt the user before killing them.

You can customize this variable.

This variable was introduced, or its default value was changed, in
version 26.1 of Emacs.

if I have unsaved buffers its a long process of having to read the questions...

Has nothing to do with:

confirm-kill-processes is a variable defined in ‘files.el’.

Non-nil if Emacs should confirm killing processes on exit.

Saving buffers and killing processes are two entirely different things, so naturally setting confirm-kill-processes to nil (or anything else) has no bearing on whether Emacs asks you to save your un-saved work.

I found this works: https://stackoverflow.com/a/6764804/5506400

;;; ============================================================================
;;; QUITTING Emacs

(defun _my-quit-emacs ()
  "When exiting Emacs, offer to save unsaved buffers, but then quit without asking if still wish to quit if there are unsaved buffers."
  (save-some-buffers nil t)
  (kill-emacs))

(defun save-buffers-kill-terminal (&optional arg)
  "Override the existing quit Emacs function via C-x C-c."
  (interactive)
  (_my-quit-emacs))

(defun save-buffers-kill-emacs (&optional arg)
  "Override the existing quit Emacs function via the mouse."
  (interactive)
  (_my-quit-emacs))


text:
Opening a Remote Shell Renames Buffer Open to \*shell\*
here is a simple elisp program for opening a shell in a named buffer:
(defun shell-make (dir buffer-name)
  (let* ((default-directory dir)
         (buffer (get-buffer-create buffer-name)))
  (set-buffer buffer)
  (shell buffer)))

Here is an example of a command that will open in shell in a buffer named shell~
 (defun shell~ () (interactive) (shell-make "~" "shell~"))

It works fine.  M-x shell~  will open a new shell and the buffer name will be shell~.
Now using Tramp to get a local shell named shell-root:
(defun shell-root ()
  (interactive)
  (shell-make "/sudo::/root" "shell-root")`)

That also works.
Now using Tramp to get a remote shell:
(defun shell-remote ()
  (interactive)
  (shell-make "/ssh:user@domain.com:~" "shell-remote"))

This does not work.  The buffer will always be called *shell*.   Even worse, once one shell is named *shell*  all other remote shell calls simply open that buffer, and do not make new shells.
How can this be code be adjusted so that Tramp does not rename the buffer for remote shells to *shell*?

Here are the messages from a failure, shell-root above which opened a buffer named *shell*:
GNU Emacs 26.3 (build 1, x86_64-redhat-linux-gnu, GTK+ Version 3.24.13) of 2019-12-10
Tramp: Opening connection for user@host.com using ssh...
Tramp: Sending command ‘exec ssh -l user  -o ControlMaster=auto -o ControlPath='tramp.%C' -o ControlPersist=no -e none host.com’
Tramp: Waiting for prompts from remote shell...done
Tramp: Found remote shell prompt on ‘host.com’
Tramp: Opening connection for user@host.com using ssh...done
Tramp: Opening connection for user@host.com using ssh...
Tramp: Sending command ‘exec ssh -q -l user  -o ControlMaster=auto -o ControlPath='tramp.%C' -o ControlPersist=no -e none host.com’
Tramp: Waiting for prompts from remote shell...done
Tramp: Found remote shell prompt on ‘host.com’
Tramp: Opening connection for user@host.com using ssh...done

Which Emacs version do you use? I've tried Emacs 26.3, and all three commands shell~, shell-root and shell-remote work as expected. Note, that there is a typo in your definition of shell-root.

also using 26.3.  I think there is a timing race involved.  I thought I saw it work once also.  Anyway, it is consistently not working right now.

Michael, just added to the bottom of the post the *messages* which includes version info, and a screen shot, that resulted from using 'shell-remote'.

Well, the messages from the Messages buffer are not sufficient for debugging. If you want to get it analyzed in more detail, pls send a mail the the tramp-deverl@gnu.org ML. Ahh, and before I forget: does it happen also when you call emacs -Q?

Michael,    I only program emacs once in a while, and had suspected I had programmed the function incorrectly.  it did not do it with emacs -Q.  My bad.  Long long ago I made another function with the same name as one involved here, buried deep in the bowels of .emacs.  Thanks.  I wonder if I should delete this question.  It is not likely to be helpful to someone else.

No reason to delete, people will see the comments. I'm happy there's no Tramp error :-)


text:
How can I unhighlight everything highlighted by `highlight-regexp`?
If I do this:
M-x highlight-regexp \cite{\(.+\)}

then pick a color. Later, if want to unhiglight all previous higlights, I have to do them one by one, e.g.
M-x unhighlight-regexp \cite{\(.+\)}

Is there not a command to un-highlight all?

The docs for unhighlight-regexp suggest using C-u and then M-x unhighlight-regexp to remove all of them.

@amitp: Please consider providing that info as an answer. Comments can be deleted at any time. Thx.

The docs for unhighlight-regexp suggest using C-u and then M-x unhighlight-regexp to remove all of them. (credits: @amitp)


text:
Kills backwards at beginning of line
With the cursor set just before B, how would I bring Bar next to Foo? I tried C-0 C-k, no avail.
     Foo

Bar

Desired:
 FooBar

I must be misunderstanding: just hit DEL?

What if there is a line in between?

Isn't that a different question? Depending on the circumances, you could use different methods. At the very least, you can do C-k to kill Bar and then move to the end of Foo and yank it with C-y.

Or C--C-kDEL (thats Ctrl and then '-')

The question is not clear, including given the exchange in the Comments (and comments can be deleted at any time). Please clarify - specify just what problem you want solved, and what would a solution consist of (i.e., what you want), excluding all other possibilities of what you might mean.

Given the exposed case, the simplest solution will be C-SPC M-b M-f <delete> if delete-active-region is not nil.
If you're looking for something more code-oriented this ad-hoc code should work:
(defun join-words-across-lines()
    "Join words across lines."
    (interactive "*")
    (let ((beg (point)))
        (while (not (re-search-backward "[[:word:]]" nil nil 1)))
        (join-line nil (point) beg)
        (delete-horizontal-space)))

But isn't a perfect solution, just a different quick & dirty  approach from the one exposed first, only for ilustrative purposes.

join-line is an alias for delete-indentation and takes one argument. What Emacs version are you using?

27.0.90.   That's what appears on describe-function
(join-line &optional ARG BEG END)
Join this line to previous and fix up whitespace at join.
If there is a fill prefix, delete it from the beginning of this
line.
With prefix ARG, join the current line to the following line.
When BEG and END are non-nil, join all lines in the region they
define.  Interactively, BEG and END are, respectively, the start
and end of the region if it is active, else nil.  (The region is
ignored if prefix ARG is given.)

Thanks. I guess it won't work with version 26.3 then.

You need some command that deletes all whitespace between two
non-space characters. Here's one:
(defun delete-whitespace ()
  (interactive)
  (let (target (chars "[[:space:]\n]"))
    (skip-chars-backward chars)
    (setq target (point))
    (skip-chars-forward chars)
    (while (> (point) target)
      (delete-backward-char 1))))

I'd rely on what emacs environment describes as a word, or whitespace instead defining my own into the function.


text:
Connect open and close delimiters with a line
I wonder if emacs has something similar to this VSCode extension (Bracket Pair Colorizer 2) which does the following (screenshot below) which I find is a really helpful UI enhancement

[
In the above screenshot, you can see a yellow line that shows the matching parentheses, I know you can get rainbow parentheses but this isn't the same as the screenshot shown.
Does anyone know if this is possible within emacs and if there's a package to enable it? Or how to enable it?

Could something like the highlight-indent-guides package close enough?

Hi, thank you! That's definitely close enough for me.

Fair warning though, it can lag, so turn it off by default and toggle it in on/off with a key binding

Please refer to the guidelines for providing an answer, particularly to the section "Provide context for links". You can make the answer more useful by adding some context. Thanks for considering!


text:
How to call a function in a list and substitute its return value in the same position?
I'm trying to use the following property value in org-publish-project-alist
:html-divs ((preamble "header" "preamble")
            (content "main" (org-export-output-file-name))
            (postamble "footer" "postamble"))

to make the value of the id attribute of the main element the name of the org file. For example,
<main id="index">. However, the actual HTML output is the literal function call: <main id="(org-export-output-file-name)">.
The documentation for org-export-output-file-name says,

Return file name as a string.

Although the specifics of this question are different, the general question has been asked before and answers abound. You can search for backquote or quasiquote here or in the emacs lisp manual. Here is a link that should help.

@NickD thank you, (setq org-html-divs <backquote>((preamble "header" "preamble") (content "main" ,(file-name-base (org-export-output-file-name ".html"))) (postamble "footer" "postamble"))) works perfectly outside of org-publish-project-alist but not as the value of its :html-divs property. So the id value is the filename that contains the preceding, that is <main id="publish-archilutes">, but not the exported html file, for example index.

Sorry, you are right (IIUC which apparently is a big if): I was assuming that org-export-output-file-name would be able to furnish the required name at the time of the setq but it can only do that at the time that org-publish is called and processes the files to be published.

@NickD no problem, this has been helpful! Is the filename available as a variable? I can post a separate question if that's preferred.

No, I think it's constructed during exporting/publishing, so it is not available until that time. I don't think there is a need for a new question. I'll check how :html-divs is used at some point, but the discussion here should allow somebody else to pick up the stick and run with it.


text:
I can't find the flycheck package
I am on MacOS and using Emacs 26.3
When I go to package-install in the minibuffer and type in flycheck, it autocompletes and adds a hyphen. I can't install just flycheck. Also when I go to list-packages, flycheck is missing. I have refreshed packages and I followed the installation instructions on flycheck.org exactly, and I am using melpa. I attached a picture:

M-x package-install doesn't show installed packages, is flycheck already installed? When you have a package installed, the package menu (M-x list-package) will mention the package "installed" or "dependency".

Thanks, I just noticed flycheck was already installed.


text:
Which Lisp objects are byte-compiled?
A compiled program and a source code can be interpreted differently at runtime. The issue is that some Lisp objects should not be modified because of the byte-compilation.

Emacs Lisp manual: 2.7 Equality Predicates
The Emacs Lisp byte compiler may collapse identical literal objects, such as literal strings, into references to the same object, with the effect that the byte-compiled code will compare such objects as eq, while the interpreted version of the same code will not. Therefore, your code should never rely on objects with the same literal contents being either eq or not eq, it should instead use functions that compare object contents such as equal, described below. Similarly, your code should not modify literal objects (e.g., put text properties on literal strings), since doing that might affect other literal objects of the same contents, if the byte compiler collapses them.

This does not imply that all Lisp objects are necessarily byte-compiled but the byte-compilation can change the code somehow.

Emacs Lisp manual: 17 Byte Compilation
Emacs Lisp has a "compiler" that translates functions written in Lisp into a special representation called "byte-code" that can be executed more efficiently. The compiler replaces Lisp function definitions with byte-code. When a byte-code function is called, its definition is evaluated by the "byte-code interpreter".

I think that the compiled code is read only once but may be evaluated several times.
In addition, in general, there are not only primitive objects. In the broader sense, which Lisp objects are byte-compiled? For example, are literal objects all and always byte-compiled?

Let's end with two final observations. 1. The Elisp manual shows that we can modify literal lists bound to variables. 2. Previously, lambda expressions had to be specified as functions '#(lambda ...) in order to be byte-compiled.
Note: From my point of view, a "byte-compiled object" can be a special object created because of the byte-compilation (e.g. a byte-compiled function) or any object that appears only during the byte-compilation (e.g. a constant object).

Hi Fólkvangr, this question is a substantial step towards answering the other question (+1). The general requirement "your code should not modify literal objects" marks those parts of the manual as buggy, where literal lists are modified. Or let us say that those parts work because they are not byte-compiled. Then they leave the reader with bad habits when he later wants to write code to be byte-compiled.

One thing we learn from this: Luckily propertize returns a copy. But, setting a variable to a literal string and then calling put-text-property with that variable as optional arg OBJECT should be avoided. -- Good to know.

If the current elisp manual on master shows buggy example code, please let the Emacs devs know via either M-x report-emacs-bug or email to emacs-devel@gnu.org


text:
Setting html preamble in org-publish
So I am trying to set a html preamble on my org-publish, and I am using the following code:
(setq org-publish-project-alist
      '(("org-notes"
         :base-directory "~/Projects/blog/"
         :base-extendion "org"
         :publishing-directory "~/Public/"
         :recursive t
         :makeindex t
         :html-preamble "This is just a test"
         :publishing-function org-html-publish-to-html)
        ("org-static"
         :base-directory "~/org/"
         :base-extension "css\\|js\\|png\\|jpg\\|gif\\|pdf\\|mp3\\|ogg\\|swf"
         :publishing-directory "~/Public/"
         :recursive t
         :publishing-function org-publish-attachment)
        ("org" :components ("org-notes" "org-static"))))

However, nothing shows up. Can anybody help me with this?

You have two :html-preamble settings: does anything happen if you get rid of the second one?

That was a copy/paste mistake. I just checked it and it was not it.

So I copied your settings (with changes to the paths of course), created a dummy org file foo.org in the blog directory and published the project. I get a foo.html file in the Public directory that contains this: `

This is just a test
...` - so AFAICT it works fine. If you cannot reproduce this, I'd suggest you start with `emacs -q` and possibly a very minimal init file, if you need one to load Org mode (if you are using the Org mode that's built-in to emacs, you should not need *any* init file) and try publishing.
So it seems that the problem was that, because I was making no changes on the posts, org-mode saw no need to recompile it.
To overcome this, just add the force flag to the org-publish function.

This gets me all the time. It would be cool if the caching mechanism could check whether the project in org-publish-project-alist has changed since the last invocation.


text:
Using variables on org-publish-project-alist
I am having some trouble setting my org-publish blog. Basically I have the following config, but when I try to publish I get the following error:
Wrong type argument: stringp, (\, publish-directory-path)

So what this means to me is that, the :publishing-directory property is expecting a string, and I am not giving it a string, even though clearly the variable publish-directory-path is a string.
I have been going crazy with this. Any idea on what is happening?
(defvar publish-directory-path "~/Projects/Public/")

(setq org-publish-project-alist
      '(("org-notes"
     :base-directory "~/Projects/blog/"
     :base-extendion "org"
     :publishing-directory ,publish-directory-path
     :recursive t
     :makeindex t
     :html-postamble nil
     :publishing-function org-html-publish-to-html
     :auto-sitemap t
     :html-link-home "theindex.html"
     :html-link-up "theindex.html"
     :sitemap-filename "theindex.org"
    )
     ("org-static"
     :base-directory "~/org/"
     :base-extension "css\\|js\\|png\\|jpg\\|gif\\|pdf\\|mp3\\|ogg\\|swf"
     :publishing-directory "~/Projects/Public/"
     :recursive t
     :publishing-function org-publish-attachment
     )
     ("org" :components ("org-notes" "org-static"))
))

elisp tag doesn't apply here. Please read Elisp tag info

In order to allow some evaluation while quoting most of the expression, you need the comma construct which you are using but you also need to replace the initial quote ' with a backquote `, usually found to the left of the 1 key on US keyboards, but maybe somewhere else on your keyboard.

This is one of the countless duplicates of threads where people discover how to use backquote.

God dammit I though they were the same. Such a tricky detail

Does this answer your question? How to use ,var-name (defvar) syntax in org-publish-project-alist? Init file is in form of org-mode

I saw that post before posting this one. My problem was that I thought that ' was the same as ` for the purposes of elisp. But clearly that is explained in there. My bad. Thanks a lot I would have been stuck on this one for a while lol :)

Well, you only make this mistake once - but everybody makes this mistake once! Hence the duplicates.


text:
Saving Python matplotlib figures with source-code blocks
So I am trying to create a Data Science workflow using org-mode source-blocks. Basically, I need to emulate the jupyter notebook functionality where you create a plot and it shows the figure.
Now, following this link, you can do this:
#+begin_src python :results file
import matplotlib, numpy
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig=plt.figure(figsize=(4,2))
x=numpy.linspace(-15,15)
plt.plot(numpy.sin(x)/x)
fig.tight_layout()
plt.savefig('images/python-matplot-fig.png')
return 'images/python-matplot-fig.png' # return filename to org-mode
#+end_src

The problem with this is that, you have to save the figure manually and then you have to return the path to the figure (Because org is wrapping that code in a function).
That is super awkward to me, because I don't want to be saving the figure manually nor have that return statement at the end, because I want to export these org files to my blog using orig-publish, and that return statement is not valid code outside of the org source blocks code context.
I then tried to do this:
#+begin_src python  :file example.png :dir images/ :results file
  import numpy as np
  import matplotlib.pyplot as plt
  import seaborn as sns

  sns.set()  # Enable Seaborn theme

  random_points = np.random.randint(0, 10, (100, 2))

  plt.scatter(random_points[:, 0], random_points[:, 1])
  plt.show()
#+end_src

#+RESULTS:
[[file:images/example.png]]

But the problem is that, it does not save any figure at the images/example.png path. What I would want to do would be that org-mode would save that figure on the path I specified in the header, and then allow me to visualize it in the results.
How could I achieve this? Thank you!

To display the image, you need to toggle org-display-inline-images. Have you tried :file images/example.png and skipping the :dir tag altogether? Finally, you may mean :results output. This enables 'scripting mode'

Yes I know you have to toggle the display images. The problem is that it does not save the image. Its like a blank png. Regarding the :dir tag, I have tried using it on the current directory so that is not the problem, and I also tried switching the :results mode to output. The issue here is, how can I make org save the matplotlib images automatically.

hm, when I execute your code block, the png file is being created in the images directory (relative to the directory where the org file exists). Dumb question, but, have you created the images directory?

Yes yes I did. Which block are you running the first or the second? And does that png contain the image or is it just blank?

Oh, ha! Yeah it is empty. I assumed it was the right image because the scatterplot popped up in a python window. That is strange. I've definitely gotten this kinda thing to work with other tools (mermaid).

Yeah I saw examples with other libraries as well. But with Python it does not seem to work.

For this, ob-iypython (https://github.com/gregsexton/ob-ipython) has worked well for me.

Ref your first code snippet, try this way the first line: #+BEGIN_SRC python :results file :exports results - this will do your goals, assuming the folder images exists.

I'm a little late but I just figured out a pretty neat way to do this using :file and without using :var.
As the other anwser already pointed out plt.show() doesn't produce output.
However you can use :results output file instead of :results file (which is the same as :results value file). This means that the data to create the image is taken from stdout instead of the value returned directly by python. Because of this we can use plt.savefig(sys.stdout.buffer) to output the image:
#+BEGIN_SRC python :results output file :file example.png :output-dir images/
  import sys
  import matplotlib.pyplot as plt
  import numpy as np

  x = np.linspace(0, 2 * np.pi, 100)
  y = np.sin(x)
  plt.plot(x, y)
  plt.savefig(sys.stdout.buffer)
#+END_SRC

#+RESULTS:
[[file:images/example.png]]

This is convenient! But it means the session buffer gets spammed with image data. This noticeably slow when working over ssh w/tramp

The basic problem is that plt.show() does not produce anything (other than showing the image as a side-effect and blocking), so there is nothing to save (it actually produces the None object, so that's what you get in the result):
#+begin_src python :results file
  import numpy as np
  import matplotlib.pyplot as plt

  random_points = np.random.randint(0, 10, (100, 2))

  plt.scatter(random_points[:, 0], random_points[:, 1])
  plt.show()
#+end_src

#+RESULTS:
[[file:None]]

The None that you see in the link is the return value of plt.show().
So you have to save the image:
#+begin_src python :results file :var f="images/example.png"
  import numpy as np
  import matplotlib.pyplot as plt

  random_points = np.random.randint(0, 10, (100, 2))

  plt.scatter(random_points[:, 0], random_points[:, 1])
  plt.savefig(f)
#+end_src

#+RESULTS:
[[file:None]]

That still does not work, because savefig() saves the image but still returns None. So we need to change things to return the file name:
#+begin_src python :results file :var f="images/example.png"
  import numpy as np
  import matplotlib.pyplot as plt

  random_points = np.random.randint(0, 10, (100, 2))

  plt.scatter(random_points[:, 0], random_points[:, 1])
  plt.savefig(f)
  return f
#+end_src

#+RESULTS:
[[file:images/example.png]]

Usign a :var f="..." header allows us to define it in one place and use it in the block. But I don't know how to avoid that and use :file/:dir headers instead.

This does not seem to be working for me. It neither creates the figure nor outputs the path to the figure in the result block

You are right: I'm getting something wrong. Let me work on it a bit.

This is still not what you want but it may help a bit.

Thanks for the help! Ok I am starting to understand the problem.. So my problem with doing that is, if I publish that code on a blog, the code is a bit weird right? Maybe I will see if I can use other plotting tool that returns an image. I tried running it without the plt.show(), because the line plt.scatter(random_points[:, 0], random_points[:, 1]) actually returns something but I don't think it works as well

"The code is a bit weird ..." - in what way? I don't understand what you are saying here. Also plt.scatter returns a matplotlib.collections.PathCollection object: I have no idea what you can do with that but it's very unlikely that org-babel will be able to make heads or tails of it.

What I was saying about it being a bit weird is that, clearly there are some lines in there that I am just using because I am working on org (mainly the return f). If I publish that, people that will read it will not understand why I am writing that. Someone recomended me jupyter.el, I think it does what I was I will post back when I test it. Thanks for the help! :)

See http://kotfic.github.io/org-mode-export-of-matplotlib-images-etc.html for a way to use noweb to hide these dependencies. But emacs-jupyter does indeed sound like a better way to go.


text:
How to search with a regexp before point?
I would like to know a function that searches a pattern located before point.
re-search-backward is mentioned in the Elisp manual but I do not understand its purpose. Indeed, I do not understand the explanation given in the manual nor some of the cases found.

re-search-backward regexp &optional limit noerror count
This function searches backward in the current buffer for a string of text that is matched by the regular expression regexp, leaving point at the beginning of the first text found.
This function is analogous to re-search-forward, but they are not simple mirror images. re-search-forward finds the match whose beginning is as close as possible to the starting point. re-search-forward finds the match whose beginning is as close as possible to the starting point. If re-search-backward were a perfect mirror image, it would find the match whose end is as close as possible. However, in fact it finds the match whose beginning is as close as possible (and yet ends before the starting point). The reason for this is that matching a regular expression at a given spot always works from beginning to end, and starts at a specified beginning position.

I did a search but found only unsatisfactory answers.

emacs greedy search-backward-regexp
Why is the order of : and - important in a regexp character class

These threads suggest that there is no standard solution. The use of skip-chars-backward seems to me particularly unsuitable because it is used for the internal workings of Emacs (see syntax.c).
Suppose the current buffer contains only a string of text composed of alphabetic characters (e.g. abc), anywhere before the point. In this case, (re-search-backward "[[:alpha:]]+") moves the point between the last two characters (between b and c) when the position is expected to be at the beginning of the text (before a).

Question needs clarification on the specifics of what doesn't work, what you're expecting and why re-search-backwards doesn't fit your case.  I cannot discern what's the problem, if we're talking about greediness backwards, if you want to search forward from the beginning of buffer to point or something else.

@Fólkvangr, do you mean that the pattern should be immediately before the point or somewhere between the beginning of the buffer and the point? In the first case you cal use re-search-backward and use \= to match point, or looking-back. In the latter case, re-search-backward should work.

It gives you the first match it finds.
In your abc example, c is a match for [[:alpha:]]+, so it stops there. The actual regexp matching is always forwards; it's just the starting position which is moved backwards until a match is found.  If you searched for "\\b[[:alpha:]]+" then abc would be the first match.
Note that what you are (IIUC) expecting would require not merely finding a successful match; but continuing to iteratively perform the pattern match from every earlier starting position in the buffer in turn (within the specified bounds), in order to discover the longest match -- potentially a very expensive operation.  Note that you can't stop at the first non-matching position, because there might be positions before that which once again match through to the required end-point.  Unless the pattern is anchored in some way which provides a guaranteed limit to how far back it could start, you can't know which of the potential start points will provide the longest match1 without checking all of them.
(In your example, we can of course see that any non-alpha character imposes a guaranteed limit for matching the regexp [[:alpha:]]+; but that is a very trivial case, whereas any such behaviour in Emacs would need to be generalised for regexps of arbitrary complexity.)
Searching forwards is usually better than searching backwards, if you can make it work. If you know the bounds of the searchable text (and you generally want to have those regardless), then a forwards search from that start point may be easier to reason about.

1 Not that the normal regexp searches guarantee the longest match in any case, which is why we have C-hig (elisp)POSIX Regexps -- but those also don't behave any differently with respect to the backwards-search start-point issue, and so using posix-search-backward doesn't change the outcome of your example at all.


text:
Roadmap to advanced spacemacs
I have somewhat recently switched from neovim to spacemacs. After switching to the develop branch, taking some time to actually read the dotfile, reading the documentation of some layers, and adding some minor tweaks to some of them, I have gotten curious about learning more about emacs and spacemacs.
I am still a confused spacemacs user. When reading the bibtex layer, for example, I am still unsure whether I should carry out the installation of the org-ref and helm-bibtex packages and how (if at all) this installation should differ for spacemacs.
Anyway, overall, what would you recommend a beginner spacemacs user to read, do, watch, or whatever, in order to get a better grasp of spacemacs? I imagine that something important might be to learn some elisp, and I've taken a peek at the references in this question. Are these also advisable for spacemacs? What would you add?

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

The question is too broad and invites primarily opinion-based answers. This is a question that's better aimed at a discussion forum, such as Reddit. On emacs.SE, and SE generally, we look for specific questions with specific answers, not for discussion, general advice, brainstorming ideas, etc.

The link @Drew provided has some good links to resources and learning paths.  This post also lays out paths: https://emacs.stackexchange.com/questions/47318/how-can-i-start-learning-emacs-lisp


text:
How to stop Emacs from using LaTeX mode key bindings for `*.tex` files?
It seems that Emacs tries to autodetect the type of file and changes some of its behaviors accordingly. I don't want any of this behavior. I just want Emacs to treat every file as if it were some generic text file. The thing that is currently annoying me is that when Emacs thinks I'm editing a LaTeX file, it won't let me type the " character without changing it to tex-style quotes. Is there a line I can put in my .emacs file to simply turn off all of this kind of stuff completely?
From googling, it looks like this is called an "input method," but the only lisp code I can find doesn't seem like it would do what I want. For example, there is a function called set-input-mode, but it doesn't seem to allow control over this. There are also things like toggle-input-method and (setq-default default-input-method ..., but those don't seem like what I'm looking for either.

Do you see the same problem if you start Emacs using emacs -Q (no init file)? If not, then bisect your init file to find the culprit.

@Drew: I do see the same problem if I use -Q. I think this is just generic behavior of emacs. It seems to be triggered by the fact that the filename ends in .tex.

After some more googling, I think I found the answer to my own question. The following code works:
(setq auto-mode-alist ())

The list auto-mode-alist seems to be a hash that has file extensions as keys and major modes as values: https://www.emacswiki.org/emacs/AutoModeAlist

I was just going to suggest that :-)

You should probably accept your answer.


text:
What ASCII character is C-q C-E?
I did a spurious replacement across many files that shows in Emacs as '^E', equivalently the result of C-q C-E. What ASCII character does that correspond to, so I can undo the replacement?

Control characters ^A to ^Z are ASCII 1 to 26; therefore ^E is ASCII 5.
You could also ask Emacs: Type C-x= with point at one of those characters, and it would tell you Char: C-e (5, #o5, #x5)
Note that C-q calls quoted-insert which inserts the next character you type, and the next thing you typed was C-e.


text:
How to display list of previous copies/kills (`M-w` or `C-w`)?
C-n C-y retrieves the n-last call to C-w, I think. Is there a way to show all that were saved?

See Browse Kill-Ring.

Check the value of the kill-ring variable e.g. with C-h v kill-ring RET, or perhaps better, evaluate it in the *scratch* buffer with kill-ring C-j. The doc string of the variable says:

List of killed text sequences.
Since the kill ring is supposed to interact nicely with cut-and-paste
facilities offered by window systems, use of this variable should
interact nicely with interprogram-cut-function and
interprogram-paste-function.  The functions kill-new,
kill-append, and current-kill are supposed to implement this
interaction; you may want to use them instead of manipulating the kill
ring directly.

See also the kill ring section in the Emacs Lisp manual.

The command counsel-yank-pop which is part of the swiper package, gives you an interactive way to browse and insert elements from you kill ring.

I would say what you want is provided by one of theses packages :

Popup-killring  - Browse kill-ring with popup menu.
Browse-kill-ring - Visually navigate kill-ring.

Spacemacs uses consel-yank-pop acessible with SPC-r-y (command already cited by @Heikki) provided by swipper. So you can also look at it.


text:
.+$ fails to match remainder of line
This matches nothing:
    Query replace regexp (default \.org.+  → ): \.org.+$  →

The same without '$' matches incompletely:

I'd like to be able to match \.org and all that follows.

Can't reproduce, either using re-search or re-builder. Please update posting the queries and the text alone as code, as well as other relevant data, as it cloud be file encoding, etc.

\.org.+$ works for me, starting from emacs -Q.
Try starting Emacs using emacs -Q (no init file). Do you see the same thing? If not, bisect your init file to find the culprit.
(Maybe pay attention too to what whitespace you're trying to match. Your question is underspecified.  All we have to go on is your screenshot - we have no idea what whitespace chars you're trying to match, etc.)

Yes, it works starting from emacs -Q.

You can use command comment-region to bisect your init file, commenting-out 1/2, then 3/4, 7/8, 15/16, etc of the file. (With C-u, comment-region UNcomments the region.)

I think weathergrass is causing the problem.


text:
Break key as a shortcut -- what am I doing wrong?
I would like to define a keyboard shortcut in my .emacs file so that the Break (a.k.a. Pause) key does a C-x C-s C-x C-c. As a warmup, I thought I would try something simpler, so as a test I did this, which seemed almost identical to examples I found by googling:
(global-set-key [C-r] 'next-line)

This doesn't actually work. Control-r is still bound to something else.
For my actual intended mapping, I was imagining something like this:
(global-set-key [pause] ('save-buffer 'save-buffer-kill-terminal))

But I haven't attempted this yet because I couldn't even get the simpler example to work.
How does one find out what name Rmacs gives to a key such as the one labeled Pause/Break on my keyboard? Are the square brackets a lisp thing, or are they just interpreted as literal characters? Is this different from using angle brackets or the kbd function?

related: https://unix.stackexchange.com/questions/607011/making-keys-like-break-and-scroll-lock-produce-output-in-a-terminal

You ask several related questions, but this is the main one, I think:

How does one find out what name emacs gives to a key such as the one labeled pause/break on my keyboard?

For Emacs's description of a key, use C-h k.
So C-h k, then hit the Pause key. Emacs probably tells you this:
<pause> is undefined

So you now know that Emacs describes that key as <pause>.
Next, how to tell Lisp about that key?  Function kbd tells you how to write the Lisp form of Emacs's description of a key.  It takes the description as a string argument.
Try M-: (kbd "<pause>").  Emacs tells you this:
[pause]

So [pause] is a Lisp form for that key.  So you could do this:
(global-set-key [pause] 'some-command)

But you could also do just this, without bothering to find the Lisp form [pause], i.e., just letting kbd do that in the code:
(global-set-key (kbd "<pause>") 'some-command)

OK.  You were already thinking of trying something similar, but what you suggested would have failed, giving you an error message like this:
Debugger entered--Lisp error: (invalid-function (quote save-buffer))

C-h f global-set-key tells you that the second argument must be a command. And it tells you:

COMMAND is the command definition to use; usually it is
a symbol naming an interactively-callable function.

You instead would be trying to pass this as the second arg: ('save-buffer 'save-buffer-kill-terminal).  That's a list with two elements.
Lisp functions, including commands, evaluate their arguments, and when an argument is a nonempty list it interprets the first element as a function, which it applies to the other elements (after evaluating each one).
So it would try to interpret your 'save-buffers, which is shorthand for the list (quote save-buffers), as a function - in fact as a function that's a command ("interactively-callable").
But it's just a list, not a function.
What you want is a function, which you can define using defun:
(defun my-break-command ()
  "Save buffer, then quit Emacs."
  (interactive)
  (save-buffer)
  (save-buffers-kill-terminal))

(global-set-key (kbd "<pause>") 'my-break-command)

It's the interactive spec, (interactive) that makes the function into a command, i.e., that makes it "interactively-callable".
Alternatively, you could use an anonymous function, instead of defining a named function such as my-break-command:
(global-set-key (kbd "<pause>")
                (lambda ()
                  (interactive)
                  (save-buffer)
                  (save-buffers-kill-terminal)))

(Generally it's better to use named functions for things like this.)

Now what went wrong with your simpler example:
(global-set-key [C-r] 'next-line)

Start from the beginning.  How does Emacs describe Control+r?  C-h k followed by that tells you:
C-r runs the command isearch-backward...

So it describes that key as just C-r.  Function kbd wants a string argument, so what you want is this:
(global-set-key (kbd "C-r") 'next-line)

You can't use [C-r].  Just what does (kbd "C-r") return?  It returns the ASCII Control-R character.
You could, in fact, use that control character directly, if you had a way to insert it into a string (which is what kbd expects).
You can do that using Controlq followed by Controlr.  (We write that in key descriptions as just C-q C-r.)
Type this: (global-set-key "
followed by ControlqControlr
followed by: " 'next-line)
You'll see this, but the "^R" will actually be a single character (Control-R), not a ^ character followed by an R character:
(global-set-key "^R" 'next-line)

And that works just as well as (global-set-key (kbd "C-r") 'next-line).

UPDATE
I meant to add some info about how you can ask Emacs, to find out this stuff on your own.  Doing that is really one of the best ways to learn Emacs and Emacs Lisp, IMO.
First, the help keys.  They all have prefix key C-h. C-h C-h will get you started. But the main ones are C-h m (tell me about the current mode), C-h k (key help, including mouse actions & menu items), C-h v (variable help), and C-h f (function help).
Second, the manuals. C-h r visits the Emacs manual using the Info interface (Info mode). C-h i visits any manual (choose from a menu of available manuals).
Learn first how to use Info, by (what else?) visiting the Info manual. Use C-h i TAB RET or C-h i m in TAB. It's a tiny manual, and it really helps to learn what it has to say.
When you visit a manual, you're in Info mode. And there's a menu-bar Info menu, to help you out. That menu will also teach you some navigation keys.
In any manual, to look for something use the index(es), by hitting i, typing some text, and hitting TAB to match it against index entries.  You can also use I, to get a virtual index of links to all index matches for some term - very handy.
Another way to look for something is incremental search: C-s. Keep repeating the same search to look for the same thing across the nodes (pages) of a manual.
But don't let search be your first recourse. Why? Because you can waste a lot of time wading through lots of hits for a search pattern. You're essentially searching blindly and sequentially, which for a large manual can be tedious and, well, not very productive.
Your first, second, ... approach should be i: using the index, not search. There might be 80 zillion search hits for some term/text, or their might be none, but with i you get the benefit of an expert (in Emacs and its manuals) having chosen which parts of the manual are most helpful/relevant for that term.
And the term you're looking for might not even be present in the manual, using the same text you provide, but it might have been added as an index entry.
In addition to i, you can use the table of contents of a manual, that is, the menu that's in its Top node, to navigate. Important concepts are typically listed there as main entry points. E.g., in addition to using i keymap you'll find a top-level menu entry Keymaps, and similarly for buffers, windows, and other Emacs thingies. Both i (index) and table of contents (menu at Top) are far more useful that just searching (C-s) for some common term (e.g. key binding).
When is search helpful? When what you're looking for is hard to find - not in the index, for example.
And if you find this to be the case for something you really think should be in the index, please use M-x report-emacs-bug to suggest that enhancement to Emacs developers.
In particular, the index is the place for alternative ways to describe something important. The terms in which you might be thinking of something might not be those used in the manual to talk about it. Maybe the terms you're thinking in should be indexed, to get readers to the relevant parts of the manual.
Remember: Ask Emacs! It's easy to do. Enjoy.

Thanks for the very complete explanation! Turns out that the break key gets caught in every terminal emulator I've tried, but I was able to get this working with the end key.

While simply browsing through hot questions, this is an awesome answer and taught me more about what certain elements mean in Emacs in 5 minutes than I would have discovered on my own in weeks/months.  Now I know why I use ’ or (interactive) instead of using it “just because”. Thanks!


text:
Cannot edit ".gitignore" due to strange errors and read-only switched on
A new error has occurred with a recent upgrade to Emacs 27.1. I'm trying to edit .gitignore and get the following error:
*ERROR*: Unlocking file: Invalid argument, <directory>/.gitignore

To check this is not an error in an initialisation file, I tried with emacs -q .gitignore. However, in this case the file is set to read-only and cannot be edited, and the strange error
File exists, but cannot be read

appears, then the file appears but as read-only. It doesn't seem to be possible to change to non-read only. To surmount this problem I have taken to renaming .gitignore to another file name then moving that using the mv command. The file itself is not read-only:
$ ls -l .gitignore
-rw-r--r--  1 ben  ben  843 Sep  4 07:20 .gitignore

I get the same error with emacs 27.1 on fc32. Also get it for a self-compiled emacs 28.

Furthermore with a compiled version of 26.3 this doesn't occur

I'm seeing the problem in only one directory and not in others where I try to edit .gitignore.

Is this directory on a different type of filesystem than the others? There were changes in emacs-27 to the handling of file-system errors that might be responsible.

@rpluim - no, the file system is the same.

Does setting (setq create-lockfiles nil) in your configuration make the error go away? I ask because it appears to me that Emacs is getting the error when it tries to create or open or read from the lock file. The filename of the lock file will be .#.gitignore; you should investigate why it can't read or create this particular lock file while others work fine.
Chapter 18.3.4 Protection against Simultaneous Editing of the Emacs manual covers how Emacs uses the lock file.

There was a file called .#.gitignore in the directory which was an "unreadable symlink" according to the Unix file utility. Removing that made .gitignore editable.

A similar thing appeared to me (on another file). Here is the solution I found:

Open the file: emacs yourfile.txt
While it's open, delete the lock file: rm .#yourfile.txt
Toggle the read-only flag '%' at the bottom of your buffer if needed
Save it and you are done


text:
Emacs converting spaces to tabs when using X11 primary selection in a terminal window
When I use emacs in a terminal window on linux, I am often getting spaces unexpectedly converted to tabs when I cut and paste using the X11 primary selection. What reproduces the problem for me is the following:
Open a terminal window. (I tested using both lxterminal and aterm.) Start emacs with the -nw option. Type the following text character by character on the keyboard:
1234567 1234567

(If you copy and paste it from the stackexchange question, it won't reproduce the problem.) Triple-click on this line of text to copy it to the X11 primary selection. Open a new terminal window, and in that window do od -a. Click the middle mouse button to paste the text into the terminal. This is echoed by the od command with an ht rather than an sp.
I'm pretty sure this is emacs doing this, because if I use the lightweight editor mg instead, it doesn't happen. I've also tested that this still happens if I hide my .emacs file, so that it's not resulting from any customizations that I've done there.
Can anyone explain how to get rid of this behavior?
Update: Gilles' comment shows that this happens at line 265 of this file https://github.com/emacs-mirror/emacs/blob/master/src/cm.c , which has the following code: if (tabcost < (deltax * tty->Wcm->cc_right)) { . I would like to find a solution for this problem that doesn't involve my having to make my own private fork of emacs. I would be happy to see an answer that would suggest an approach to doing this by submitting a patch to emacs. Perhaps this behavior could be turned off by setting a certain flag in lisp. If that seems like a reasonable approach, then it would be great to see an answer saying so, and maybe pointing to an example of how well-behaved emacs C code would access such a flag. If I was an emacs maintainer, I would just rip all the code out, because I just don't think this is reasonable behavior for a terminal-based application in the year 2020, but possibly some people depend on this behavior and it would cause problems if it were simply removed.

What happens if you yank it into an Emacs buffer instead?

@Drew: It doesn't happen then.

It's hard to see how this is Emacs-related, then. Does setting variable indent-tabs-mode to nil have any effect on it?

Probably another bracketed-paste problem: see https://emacs.stackexchange.com/questions/60442/paste-inserts-extra-characters-because-of-electric-mode/60443#60443 for a previous explanation.

It's due to the interaction between Emacs and the terminal. There's a space in the buffer, but when Emacs is updating the terminal, it prints a tab. Here's a way to see what's going on (on Linux): from a terminal, run lxterminal -e strace -o $(tty) -e read,write emacs -Q -nw then in Emacs type 1234567 and a space. When you type the space (read(6, " ", 1)), Emacs writes a tab (write(6, "\t", 1)). Whether this happens depends on how Emacs repaints the screen, for example it doesn't happen if you switch to another buffer then switch back, or if you scroll away and back.

@db48x I don't see how bracketed paste would make a difference. There's a tab in the clipboard. It's going to be pasted as a tab. Bracketed paste influences what happens if you paste in the terminal, but the choice is whether the application running in the terminal will insert a literal tab or will apply its key binding for tab. Either way it won't be like inserting a space.

A workaround is to use xterm. It converts the tab to a space when copying to the clipboard. (Or more precisely, I think, it converts the tab to a space when the application displays a tab.)

You're probably right; I can reproduce it with the same results from strace.

Incidentally, if you're curious why it outputs a tab instead of a space, it's because on line 265 of cm.c, it determines that the tab is one byte but moving the cursor left by one would take 3 bytes, saving 2 whole bytes.

Also, if you hit space 8 times instead of typing out digits, you'll actually see it use a tab plus a backspace for the 7th character, since that only takes 2 bytes instead of three.

It's important when all you have is a 300-baud modem...

Analysis
There's a space in the buffer, but in certain circumstances, when Emacs needs to print a sequence of spaces, it chooses to print a tab instead because that requires writing fewer characters to the terminal. This is what's happening when you insert the characters one by one. It doesn't happen when Emacs is printing the line all in one go, for example when you paste the whole line, or if you scroll away then back (you need to scroll enough to make the line disappear to be sure), or if you switch to another buffer and then back.
The decision to print a tab happens deep inside the C code, in calccost() in cm.c. I don't fully understand how this works: in this particular case, writing one space or writing one tab would have the same effect, but apparently Emacs prefers to write one tab (I can confirm this with Emacs 26.3 on my machine).
I can't find a way to disable this behavior from Lisp code. It's parametrized by tty->Wcm->cc_tab, tty->Wcm->cm_usetabs and tty->Wcm->cm_tabwidth (which in some places are written TabCost (tty), UseTabs (tty) and TabWidth (tty)). As far as I can tell these are derived only from terminal characteristics and can't be influenced by Lisp code. TabWidth is read from the tw termcap value if present (it isn't on modern Linux, I think it's obsolete), defaulting to 8. UseTabs is true if TabWidth is 8 on modern Unix-like platforms (tabs_safe_p). TabCost is calculated from TabWidth and UseTab so it's no help. So the only way to disable this behavior (without recompiling Emacs) is to convince Emacs that the width of a tab is not 8.
Workaround: use a terminal that doesn't copy tabs
In xterm, unlike the other terminals I tried (lxterminal, gnome-terminal, rxvt), when you copy the line, the clipboard contains a space, not a tab.
Workaround: redisplay
Anything that redraws the screen makes the tab go away, for example M-x redraw-display or C-l (recenter-top-bottom).
This works even for a line like 1<TAB>2 where a tab is present in the buffer and a tab would be actually advantageous for display.
Workaround: tell Emacs that your terminal doesn't support tabs
It's a bit complicated for what it does, and it can have a secondary effect in other applications that have behavior based on the terminal name (for example, loss of colors). But you can change your terminal's description to pretend that its tab width is not 8. Any value other than 8 will make Emacs avoid tabs, but I recommend choosing a large value to avoid confusing other applications.
Create a file with the following content. I'll call it my-terminal-descriptions.terminfo; the name doesn't matter since you only need it once and for all.
xterm-256color-notab|xterm with 256 colors avoiding tabs,
 tw#9999,
 use=xterm-256color,

Run the following command to compile this new terminal description:
tic -x my-terminal-descriptions.terminfo

Run Emacs with TERM set to xterm-256color-notab. For example:
alias emacs='env TERM=xterm-256color-notab emacs'


text:
init file -- How to customize user options?
One of the recommanded solution to customize user options in the init file is customize-save-variable. This command saves some code that initializes custom variables, at each startup of the editor.
(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(package-selected-packages '(sx ivy doom-themes)))
(custom-set-faces
 ;; custom-set-faces was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 )

Thus, it is rather obvious that customize-save-variable should be called interactively by the user. This command should not be invoked in the init file.
However, setq and setq-default can't set every customizable variable (see below).

C-h f customize-set-variable
If VARIABLE has a ‘custom-set’ property, that is used for setting VARIABLE, otherwise ‘set-default’ is used.

An alternative way should be to define all relevant settings (like those found in Customize) in a new theme.
N.B.: Maybe, I'm overreacting to this issue. However, I have the impression of having contradictory instructions to set customizable variables.
See Also

[ISSUE] use-package: Init file vs. Customize
[ISSUE] Another relevant comment

More about the issue
It is inconvenient to modify some settings in the init file because the Custom interface seems unavoidable. It's like mixing two different user interfaces to achieve the same goal, although in practice we must use these interfaces in parallel.
The expected result is to use a single interface in a transparent way. I am really surprised that no solution has been implemented since the issue has been around for a long time (~2002).
Question: How to configure user options without mixing code in the init file?

The question isn't clear to me. Just what are you asking?

“the user can't manually specify its configuration”: what configuration? “It's not always convenient to define a new theme” — what theme are you talking about? “Can we customize user options” — well, yes, that's what customize is for, what inconvenience are you referring to? “Are there any workarounds” — for what? Are you asking from the perspective of a user or of a package author?

Thanks, it's clearer now what you're stating. But I don't see a question…


text:
Preview all LaTeX fragments in org mode?
How can I call org-toggle-latex-fragment on all LaTeX fragments in an Org mode doc? I'm coming from Vim, so my instinct is to put something in the init.el that loops through the document and looks for $ and \[ to call org-toggle-latex-fragment on if the file extension is .org. How can I implement this, and is this generally a good approach?

org-toggle-latex-fragment is obsolete since Org 9.3. Use org-latex-preview.
To preview all latex fragments in the buffer pass C-u twice before calling org-latex-preview. Note that a single C-u before org-latex-preview actually removes all previews. For instance, I set the keybinding C-f5 to org-latex-preview then C-u C-f5 removes all previews and C-u C-u C-f5 preview latex fragments on the whole buffer.
Note: org-toggle-latex-fragment has the same behavior, in case you are using an org-mode version before 9.3.

You might be also interested in org-fragtog.

Automatically toggle org-mode latex fragment previews as the cursor enters and exits them

Is it also possible to set C-f5 to what C-u C-u org-latex-preview does directly? If so, how to do it?

I'm not sure. You can set keybindings to lambda functions and call org-latex-preview in a lambda function (or create a named function). The trick part is passing C-u C-u programmatically. Maybe this question can help.


text:
Any way to remap the meta key with evil?
Function modifiers in Emacs conflicts with many hotkeys I have (for example, conflicts with i3wm). By using evil I could use evil to avoid most of conflict hotkeys.
However, I do still need to use those function modifiers to use, for example, M-x, but it conflicts with other hotkeys. (For Emacs keymap, ESC can be used. But now ESC is used by evil, and is no longer a meta substitute.)
What I want to achieve is in normal mode, ; acts as ctrl, and ' as alt, the meta key.
I tried the following but none of them worked:
(define-key evil-normal-state-map (kbd "'") 'event-apply-meta-modifier)
(define-key evil-normal-state-map (kbd "'") 'meta)

Any ideas how to achieve that?

event-apply-meta-modifier is only to be used in translation keymaps. You
should try
(define-key key-translation-map "'" 'event-apply-meta-modifier)
(define-key key-translation-map ";" 'event-apply-control-modifier)

This will also make it possible to use these keys in the middle of a key
sequence. If you want the keys to only work in normal state, you could use
something like
(defun evil-normal-state-filter (cmd)
  (and (fboundp 'evil-normal-state-p)
       (evil-normal-state-p)
       cmd))
(define-key key-translation-map "'"
  '(menu-item "" event-apply-meta-modifier :filter evil-normal-state-filter))
(define-key key-translation-map ";"
  '(menu-item "" event-apply-control-modifier :filter evil-normal-state-filter))

See info node (elisp) Translation Keymaps and (elisp) Extended Menu Items
for more information.

It works. Thanks!


text:
How to use a specific latex template in org-mode
I would like to create this Latex template in org-mode :
\documentclass[french, 11pt]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage[hidelinks]{hyperref}
\usepackage[ddmmyyyy]{datetime}
\usepackage{microtype}
\usepackage{antiqua}
\author{My Name}
\date{\today}
\renewcommand{\contentsname}{Table des matières}

So I have added this to my .emacs in order to not have any of the default packages, just the one I want, based on what I saw on this tutorial :
(require 'ox-latex)
(with-eval-after-load 'ox-latex
(add-to-list 'org-latex-classes
           '("koma-article"
             "\documentclass[french, 11pt]{scrartcl}
             \usepackage[utf8]{inputenc}
             \usepackage[T1]{fontenc}
             \usepackage{babel}
             \usepackage[hidelinks]{hyperref}
             \usepackage[ddmmyyyy]{datetime}
             \usepackage{microtype}
             \usepackage{antiqua}
             \author{My Name}
             \date{\today}
             \renewcommand{\contentsname}{Table des matières}
             [NO-DEFAULT-PACKAGES]
             [NO-PACKAGES]"
             ("\\section{%s}" . "\\section*{%s}")
             ("\\subsection{%s}" . "\\subsection*{%s}")
             ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
             ("\\paragraph{%s}" . "\\paragraph*{%s}")
             ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))))

So that when I want to create a new document in org-mode I just have to put :
#+TITLE: My Title
#+LaTeX_CLASS: koma-article

However when I try to compile a document I get :Unknown LaTeX class 'koma-article'. I am not sure what I'm doing wrong here. Is there a way to load only these packages without having to specify then in the buffer using #+LATEX_HEADER: \usepackage ?

Are you sure about the code? All backslashes should be escaped, e.g. \\documentclass, \\usepackage. Otherwise you're going to end up with an error in your add-to-list call.

Check the value of org-latex-classes with C-h v org-latex-classes RET. As @Zeta points out, you are probably not adding the entry.

@Zeta Thanks, you're right escaping all the backslashes worked. Sorry, I guess that what happens when you edit your config at 5 a.m ^^'

As mentioned in the comments above, the latex commands need to be escaped. so this should work as expected....
(add-to-list 'org-latex-classes
           '("koma-article"
             "\\documentclass[french, 11pt]{scrartcl}
             \\usepackage[utf8]{inputenc}
             \\usepackage[T1]{fontenc}
             \\usepackage{babel}
             \\usepackage[hidelinks]{hyperref}
             \\usepackage[ddmmyyyy]{datetime}
             \\usepackage{microtype}
             \\usepackage{antiqua}
             \\author{My Name}
             \\date{\\today}
             \\renewcommand{\\contentsname}{Table des matières}
             [NO-DEFAULT-PACKAGES]
             [NO-PACKAGES]"
             ("\\section{%s}" . "\\section*{%s}")
             ("\\subsection{%s}" . "\\subsection*{%s}")
             ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
             ("\\paragraph{%s}" . "\\paragraph*{%s}")
             ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))

According with what you are describing, I would recommend you to escape all the backslashes (all the backslashes that appear between the "koma-article" and  [NO-DEFAULT-PACKAGES]).
Finally, you need to make sure that you have the Koma-Script ‘article’ class installed: https://www.ctan.org/pkg/scrartcl.

Another way is to have an own latex header file, and input it at the very beginning of your file.
   ("mybestreport"
           "\\input{/home/path/to/your/latex/header/header.tex}"
           ("\\chapter{%s}" . "\\chapter*{%s}")
           ("\\section{%s}" . "\\section*{%s}")
           ("\\subsection{%s}" . "\\subsection*{%s}")
           ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
           ("\\fourthsection{%s}" . "\\fourthsection*{%s}")
           ("\\fifthsection{%s}" . "\\fifthsection*{%s}")
           )