Emacs: How to select word under cursor and append to file - emacs

I want the following behavior:
Append the word under cursor into a file(~/vocabulary.txt, for example)
Better still to bind a key for it.
Could anyone show me how to do it?
Should I put those code into .emacs ?

Try the following function:
(defun my-write-to-file ()
"Save word at point to file"
(interactive)
(write-region (concat (thing-at-point 'word) "\n") nil "~/vocabulary.txt" 'append))
When called, this function will save the word at point (the word the cursor is on or the word right before the cursor) to ~/vocabulary.txt.
You can bind it to a key (C-c w in this case, but you can change it to whatever you like) like this:
(global-set-key (kbd "C-c w") 'my-write-to-file)
To use, simply put the function and the keybinding assignment in your .emacs.

#Elethan wrote you a command that does just what you ask for, and bound it to a key.
It might also help to mention some general commands that you can use for this kind of thing. M-x append-to-file appends the region contents to a file, and M-x write-region prepends.
The manual is your friend for things like this. See nodes Misc File Ops and Accumulating Text.
Be aware too that for the two commands just mentioned, as the manual says about append-to-file (it should say it about both):
You should use append-to-file only with files that are not being
visited in Emacs. Using it on a file that you are editing in Emacs
would change the file behind Emacs’s back, which can lead to losing some
of your editing.
Accumulating Text also tells you about commands for adding text to a buffer, including the case of adding to a buffer for a file that you are visiting (as opposed to what the above quote warns you about for append-to-file). These include commands append-to-buffer and prepend-to-buffer.

Related

emacs > org mode > agenda - always use current buffer

I am using many different org mode files for various projects, and I rev them by adding the date to the filename eg filename-2020-09-17.org. I realize I could use version control but in this case that is not possible, due to needing to share the file with others who are not using VC.
I would like the Agenda to always show just the items for the current file/buffer.
When I save eg the file with filename-2020-09-16.org to filename-2020-09-17.org, then the agenda still shows the old file name unless I remove it from the agenda file list and add the new file.
I realize that I can use C-c a < a but I am lazy and would rather not have to type S-, each time to get the <.
I looked at
Agenda view of the current buffer
And the OP says the solution was simple but he/she/they did not provide the solution - at least I don't see it and I tried the posted code but it no works.
I also found https://www.reddit.com/r/orgmode/comments/bxwovd/agenda_for_current_buffer/ but that did not seem to meet my need.
Specifically I would like to put something in .emacs so that this would apply to all files all the time.
I also looked into a keystroke macro programs but this does not seem ideal.
Any help is appreciated.
Thanks ahead of time.
Here's a simple function to do what you want, but there is no error checking to make sure e.g. that you are invoking it from a buffer that is visiting an Org mode file. The idea is that you set the org-agenda-files list to contain just the file which the buffer is visiting and then you call the regular org-agenda function. Binding the modified function to the C-c a key may or may not be what you want to do, but you can try and decide for yourself:
(defun org-agenda-current-buffer ()
(interactive)
(let ((org-agenda-files (list (buffer-file-name (current-buffer)))))
(org-agenda)))
(define-key global-map (kbd "C-c a") #'org-agenda-current-buffer)

Search selected text and show all occurrence of it in current (all other buffers) in emacs?

So in notepad++ I can select text, hit C-f, then, if I need to look for occurrence of selection in all opened files, i hit M-o and get nice clickable list with navigating to occurrence option. Or if I need list only for current file I point mouse to “Find all in current document” button do a click and get same nice clickable list only for currently active file. So is it possible to do exact thing in emac?
You can implement that functionality with the following lisp function:
(defun occur-selection ()
(interactive)
(when (region-active-p)
(let (deactivate-mark)
(occur (regexp-quote (buffer-substring (region-beginning) (region-end)))))))
If you put that code in your ~/.emacs file together with the follwing line:
(global-set-key [(meta o)] 'occur-selection)
you should be able to select some text, hit M-o and get a list of all occurrences of the selected text displayed in a separate buffer.
User M-g n and M-g p do cycle through the matching lines in the original buffer.
Note, however, that multiple occurrences in a single line are not distinguished.
By default, Emacs has M-x occur which work similar but slightly differently. It allows you to specify a regular expression, all matches of which in the current buffer will be displayed and hyperlinked.
If your focus is more on navigation than on highlighting all matches of a search term, there might be an external alternative that could help you.
Emacs' original philosophy is not built around user interface metaphors such as clicking with a mouse, it comes from a keyboard only background. If you're interested in this approach, you might want to have a look at the Avy package for Emacs. It lets you quickly jump to one of multiple occurrences of a word.
Check out the excellent Emacs Rocks episode "Jumping Around" to see a precursor of Avy (called ace-jump-mode) in action: http://emacsrocks.com/e10.html
You can do the same thing with the helm package.
Emacs will search the word the cursor/"point" is on (you
don't need to highlight it).
To make helm search in all open files/buffers, use:
M-x helm-multi-swoop-all
To make helm search only in file/buffer you're currently in, use:
M-x helm-swoop
Press the ENTER key to drop into the selected file at the
selected line.
To bind these functions to the same key-comboes, you'd need
this in your .emacs:
(global-set-key (kbd "M-o") 'helm-multi-swoop-all)
(global-set-key (kbd "C-f") 'helm-swoop)
NB
Helm is hosted in the MELPA repository.
HTH,
Michael

How to prompt the user for a block of text in elisp?

read-from-minibuffer is a great way to prompt a user for a single line of text. How do I prompt a user for a large block of multi-line text in elisp?
This is what I'm thinking, but I don't know if it's the smoothest approach:
create a temporary buffer (via with-temporary-buffer?)
seed the buffer with some default text
display the buffer
tell the user, "edit the text as you see fit, then hit <some key sequence> to indicate that you are done" (perhaps via header-line-format)
wait for the user to hit the key sequence
collect the buffer text and put it in a variable (via buffer-string)
destroy the temporary buffer and restore the window layout as it was before
do stuff with the text
(defun my-read-mb-lines (prompt some-keyseq)
(let ((keymap (copy-keymap minibuffer-local-map)))
(define-key keymap (kbd "RET") 'newline)
(define-key keymap some-keyseq 'exit-minibuffer)
(read-from-minibuffer prompt nil keymap)))
Calling example:
(my-read-mb-lines "Insert text (C-s to submit): " (kbd "C-s"))
The 'let' block creates a local copy of the minibuffer's default keymap. The next two calls to "define-key" modify the keymap copy. Afterward, "read-from-minibuffer" passes the modified keymap for the minibuffer to use while prompting the user (instead of its default keymap, "minibuffer-local-map").
FWIW, C-j is mapped to "exit-minibuffer" by default and a simplified version can be written:
(defun my-simplified-read-mb-lines (prompt)
(let ((keymap (copy-keymap minibuffer-local-map)))
(define-key keymap (kbd "RET") 'newline)
(read-from-minibuffer prompt nil keymap)))
Calling example:
(my-simplified-read-mb-lines "Insert text (C-j to submit): ")
I suppose it depends on the exact use-case?
There are no shortage of examples of your proposed approach working very nicely (e.g. writing a VCS commit message), so there's certainly nothing wrong with that -- it's tried and true. In addition, if it really is a large (or simply not small) block of text, then I suspect that providing a normal buffer to edit in may provide the nicest experience for the user.
If you're talking about collecting multiple input fields including a multi-line field, then the widget-based approach (as suggested by wvxvw) would enable you to put everything in a single buffer, which might also be desirable.
Or you could use the mail-like approach of using a single buffer for multiple fields, and then parse the results afterwards.
First of all Emacs 23.4 is very old. You should upgrade.
The work-flow you describe is what org-mode uses to edit source blocks.
Org-mode is included in Emacs 24.
See the source of org-edit-special for how it works.
It does a bit more than you need.
Basically, you want to set up a minor-mode for the created buffer that has a
binding to gather the text and restore window configuration.
I've written ges to edit arbitrary blocks in a new buffer using org-mode
machinery, but it's more complex than what you need.

How to disable underscore (_) subscripting in Emacs, TeX input method

On Emacs, while editing a text document of notes for myself (a .txt document, not a .tex document), I am using M-x set-input-method Ret TeX, in order to get easy access to various Unicode characters. So for example, typing \tospace causes a "→" to be inserted into the text, and typing x^2 causes "x2" to be inserted, because the font I am using has support for Unicode codepoints 0x2192 and 0x00B2, respectively.
One of the specially handled characters in the method is for the underscore key, _. However, the font I am using for Emacs does not appear to have support for the codepoints for the various subscript characters, such as subscript zero (codepoint 0x2080), and so when I type _0, I get something rendered as a thin blank in my output. I would prefer to just have the two characters _0 in this case.
I can get _0 by the awkward keystroke sequence _spacedel0, since the space keystroke in the middle of the sequence causes Emacs to abort the TeX input method. But this is awkward.
So, my question: How can I locally customize my Emacs to not remap the _ key at all when I am in the TeX input method? Or how can I create a modified clone (or extension, etc) of the TeX input method that leaves out underscore from its magic?
Things I have tried so far:
I have already done M-xdescribe-key on _; but it is just bound to self-insert-command, like many other text characters. I did see a post-self-insert-hook there, but I have not explored trying to use that to subvert the TeX input method.
Things I have not tried so far:
I have not tried learning anything about the input method architecture or its source code. From my quick purview of the code and methods. it did not seem like something I could quickly jump into.
So here is the solution I just found: Make a personalized copy of the TeX input method, with all of the undesirable entries removed. Then when using M-x set-input-method, select the personalized version instead of TeX.
I would have tried this earlier, but the built-in documentation for set-input-mode and its ilk does not provide sufficient guidance to the actual source for the input-methods for me to find it. It was only after doing another search on SO and finding this: Emacs: Can't activate input method that I was able to get enough information to do this on my own.
Details:
In Emacs, open /usr/share/emacs/22.1/leim/leim-list.el and find the entry for the input method you want to customize. The entry will be something like the following form:
(register-input-method
"TeX" "UTF-8" 'quail-use-package
"\\" "LaTeX-like input method for many characters."
"quail/latin-ltx")
Note the file name prefix referenced in the last element in the form above. Find the corresponding Elisp source file; in this case, it is a relative path to the file quail/latin-ltx.el[.gz]. Open that file in Emacs, and check it out; it should have the entries for the method remappings, both desired and undesired.
Make a user-local copy of that Elisp source file amongst your other Emacs customizations. Open that local copy in Emacs.
In your local copy, find the (quail-define-package ...) form in the file, and change the name of the package; I used FSK-TeX as my new name, like so:
(quail-define-package
"FSK-TeX" "UTF-8" "\\" t ;; <-- The first argument here is the important bit to change.
"LaTeX-like input method for many characters but not as many as you might think.
...)
Go through your local copy, and delete all the S-expressions for mappings that you don't want.
In your .emacs configuration file, register your customized input method, using a form analogous to the one you saw when you looked at leim-list.el in step 1:
(register-input-method
"FSK-TeX" "UTF-8" 'quail-use-package
"\\" "FSK-customized LaTeX-like input method for many characters."
"~/ConfigFiles/Elisp/leim/latin-ltx")
Restart Emacs and test your new input-method; in my case, by doing M-x set-input-method FSK-TeX, typing a_0, and confirming that a_0 shows up in the buffer.
So, there's at least one answer that is less awkward once you have it installed than some of the workarounds listed in the question (and as it turns out, are also officially documented in the Emacs 22 manual as a way to cut off input method processing).
However, I am not really happy with this solution, since I would prefer to inherit future changes to TeX mode, and just have my .emacs remove the undesirable entries on startup.
So I will wait to see if anyone else comes up with a better answer than this.
I did not test this myself, but this seems to be the exact thing you are looking for:
"How to disable underscore subscript in TeX mode in emacs" - source
Two solutions are given in this blogpot:
By the author of the blogpost: (setq font-lock-maximum-decoration nil) (from maximum)
Mentioned as comment:
(eval-after-load "tex-mode" '(fset 'tex-font-lock-subscript 'ignore))
The evil plugin for vim-like modal keybinding allows to map two subsequent presses of the _ key to the insertion of a single _ character:
(set-input-method 'TeX)
(define-key evil-insert-state-local-map (kbd "_ _")
(lambda () (interactive) (insert "_")))
(define-key evil-insert-state-local-map (kbd "^ ^")
(lambda () (interactive) (insert "^")))
When _ and then 1 is pressed, we get ₁ as before, but
when _ and then _ is pressed, we get _.
Analogous for ^.
As already explained in pnkfelix answer, it seems we have to make a personalized copy of the TeX input method. But here comes a lighter way to do that, without any file tweaking. Simply put the following in your .emacs :
(eval-after-load "quail/latin-ltx"
'(let ((pkg (copy-tree (quail-package "TeX"))))
(setcar pkg "MyTeX")
(assq-delete-all ?_ (nth 2 pkg))
(quail-add-package pkg)))
(set-input-method 'TeX)
(register-input-method "MyTeX" "UTF-8" 'quail-use-package "\\")
(set-input-method 'MyTeX)
The important part is the assq-delete-all line in the middle that remove all shortcut entries starting with _. It's a bit of a lisp hack but it seems to work. Since I'm also annoyed by the shortcuts starting with - and ^, I also use the following two lines to disable them :
(assq-delete-all ?- (nth 2 pkg))
(assq-delete-all ?^ (nth 2 pkg))
Note that afterwards you can M-x set-input-method at any time and indicate TeX or MyTeX to switch between the pristine TeX input method or the customized one.

Simple Emacs keybindings

I have two operations that I do all the time in Emacs:
Create a new buffer and paste the clipboard. C-S-n
Close the current buffer. C-S-w
Switch to the last viewed buffer. C-TAB
I feel like a keyboard acrobat when doing the first two operations. I think it would be worth trying some custom key bindings and macros.
A few questions about this customization:
How would I make a macro for #1?
Are these good key bindings? (I know this is a bit subjective, but they might be used by something popular that I don't use.)
Has anyone found a C-TAB macro that will act like Alt+Tab in Linux/Windows? Specifically, I want to have a stack of buffers according to the last viewed timestamp (most recent on top). I want to continue cycling through the stack until I let go of the Ctrl key. When the Ctrl key is released, I want the current buffer to get an updated position on the stack.
Have you tried using vertically or horizontally split windows for this (via C-x 3 or C-x 2)? It seems like it would give you fewer steps - even if you implement something like you're talking about.
I find split windows really speed up copy and pasting operations. I use the arrow keys on my num pad to switch among windows (windmove-left/-right/-up/-down), so it's only one key to press and you go to the window you want.
I guess this is a little different from what you're asking for, but it sounds like it might help speed things along a bit.
C-x left and C-x right cycle through buffers, but you have to hit it multiple times, you can't just keep the key pressed down.
For creating a macro for #1, you just start a macro, hit the keys you usually do to create a new buffer, and stop the macro.
So it would be something like:
C-x ( C-x b NEW RET C-x )
You can then save NEW to a file once you're done pasting, so you can use the macro again to create a new buffer. C-x e to try out the macro. If it works you can save it into your init.el file. This is done with:
M-x name-last-kbd-macro
Then you'll get a prompt to enter the name of your choice. This is only good for the current session. Then you save the named macro to your initialization file. First you open your .emacs or init.el file. Then you place point where you want the macro definition to go, then you type:
M-x insert-kbd-macro
Now you can run your macro using its name via M-x <macroname> . You can bind your macro to keys too (in your .emacs or init.el file):
(global-set-key (kbd "C-c a") '<macroname>)
For example this is how your init.el would look after creating a macro that opens a new buffer called NEW that is not associated with a file and binding this macro to C-c n:
;; Creates a new unassociated buffer called NEW
(fset 'new-buffer "\C-xbNEW\C-m");
;; Shortcut for new-buffer
(global-set-key (kbd "C-c n") 'new-buffer)
You can also throw in the paste, buffer close, and buffer switching operations. I guess you'd have to save the buffer to a file manually.
Some resources
Information about macros on EmacsWiki
Possibly useful: Swap text between buffers
start by invoking start-kbd-macro, finish by with end-kbd-macro. Afterwards you may immediately test the new macro with call-last-kbd-macro. If you're happy with the result you might want to save the macro.
Emacs generally doesn't use C-S keybindings and they are easy to use, so I'd call them good. They might cause problems if you're using the terminal version of Emacs, but I assume that's not the case with you.
I use this simple snippet:
(global-set-key (kbd "<C-tab>") 'bury-buffer)
bury-buffer basically makes the current buffer the last in the buffer-list so you'll be able to cycle buffers in a predictable order.
I wouldn't make a macro for that but write a function like someone else posted on this page. Instead of (cua-paste nil) you could also use (yank). I'm not sure which one's better and why.
I don't like them that much. For things that I use often I'd like to do as little finger acrobatics as possible, so that would mean modifier+key instead of modifier1+modifier2+key.. or use a function key if you don't feel tied to the homerow.
no comment