What is the fasted way to get the current file-name yank-able (with C-y) - emacs

Sometimes I edit files that have a certain suffix and files with same basename but another suffix. Since the basenames are long and awkward I would like to reuse the existing filename to construct the other name.
What I do currently is:
C-x C-b (This shows me the Buffer List)
C-x o (Now I am in the Buffer List)
M-right M-left (At the beginning of the basename)
C-space M-right ... M-w (Copying the basename)
C-x o (Back where I came from)
...
There must be a more canonical way to do this! (I am not interested in a way that involves the definition of a command proper, I have too many of them already...)
Edit: actually, what I wanted is to do something with that very name, most often create or read a related file. #Trey Jackson's C-x C-v is it!

Strictly speaking this command does what you want, even if you don't want a command:
(defun copy-base-filename-as-kill ()
(interactive)
(let ((filename (buffer-file-name)))
(when filename
(kill-new (file-name-nondirectory (file-name-sans-extension filename))))))
But, if you're really just using this name to do something else... perhaps a better solution is to make doing that something else easier.
Try the command C-x C-v (aka M-x find-alternate-file) if what you want to do is create a new name based on the current name.

I don't think there's anything out of the box that does it, but here's a little elisp function:
(defun copy-buffer-filename ()
(when (buffer-file-name)
(kill-new (file-name-nondirectory (buffer-file-name)))))

Related

How to create a new, unnamed file in emacs?

This is a very simple request: I want to create a new, blank file without giving it a name (yet). I can use the scratch buffer but there's only one. I can C-x C-f and open a new file, but then I have to give it a name and path. If I'm just writing notes to myself or sketching out ideas, I don't want to have to give it a name. How do I create a new, empty, unnamed file?
You can create a new buffer with: C-xb and type in the buffer name and it will create a new buffer with a name that you choose.
If you want to save that buffer, just hit C-x w to create the file with its contents to a desired location.
My recommendation is that you give org-mode a try. It will do what want among a million other things.
Give it a name. Just don't save it.
Not what you wanted to hear, but this is the Emacs way.
Use C-x C-f, giving the (to-be-file-visiting) buffer a name. Edit the text. Do not use C-x C-s to save the buffer to the file (i.e., to disk).
Note that you can first put yourself in a directory whose contents you don't care about, so that if you accidentally do save the buffer there then you can easily find, recognize and toss the file. To change directories, you can use M-x cd. Or just do it by editing the directory part when you first use C-x C-f. Or use C-x d to put yourself in a Dired buffer for the directory.
If you don't want to take the chance of accidentally hitting C-x C-s and thus saving your edits, then use C-x b instead of C-x C-f. You are (even here) prompted for the buffer name. Giving it a new name (not the name of an existing buffer) creates a new buffer. In this case, if you use C-x C-s then Emacs prompts you for the file location to save the buffer in.
Why would you want to use C-x C-f instead of C-x b, if you might not want to save the buffer? Providing a file extension in the file name you give automatically puts the buffer in the proper major mode (typically). Otherwise (for C-x b) you need to put the buffer in the mode you want.
Buffer *scratch* is by default in Lisp-Interaction mode, which is similar to Emacs-Lisp mode (but not the same).
In every other text editor or word processor the intuition is to create a “new file” or a “new buffer”, not to switch to idiosyncratic *scratch* buffer. For example, you write quick notes or thoughts in several different buffers to keep trace of them—later you decide if you throw them away or save them. Or you manipulate a snippet of text or code, but you don't want to change the original buffer, so you just copypaste it to a new temporary buffer.
*scratch* is set to Lisp Interaction mode, but if I want to quickly evaluate some Elisp code, I could eval it running eval-expression (Alt+:) or in Elisp interpreter IELM (Alt+x Enter ielm). Also, if you close *scratch* buffer, it doesn't ask you to save it, so you can accidentally lose all your work. Drew's traditional solution seems too sub-optimal. And I don't buy the argument that “this is how you do it in Emacs”. Emacs is a customizable editor, so you can and should create whatever workflow is comfortable for you.
That's how ErgoEmacs solves it, buy creating a new-empty-buffer command. You can implemented like this:
(defun new-empty-buffer ()
"Opens a new empty buffer."
(interactive)
(switch-to-buffer (generate-new-buffer "untitled"))
(funcall initial-major-mode)
(put 'buffer-offer-save 'permanent-local t)
(setq buffer-offer-save t))
The variable buffer-offer-save resets every time you change a major mode, therefore you need to annotate it with permanent-local. It also prompts only when you exit Emacs. I think it is intuitive for it to also ask, when you close a modified untitled buffer, therefore see my solution on how to upgrade kill-buffer to prompt before closing a modified buffer.
ErgoEmacs revamps the default keybindings completely and has new-empty-buffer bound to Ctrl+N, like in almost all software. Change variable initial-major-mode if you want the new buffer to have another mode on start.
See also:
Emacs: Problems of the Scratch Buffer # Xah Lee
Emacs: New Empty Buffer # Xah Lee
You can try the following snippet, just add it to your .emacs
(defun new-file-tmp()
"Create a new empty file."
(interactive)
(let ((buf (generate-new-buffer "untitled")))
(switch-to-buffer buf)
(put 'buffer-offer-save 'permanent-local t)
(setq buffer-offer-save t)))
(defun tool-bar-local-item-pre (icon def key map after_item &rest props)
"Add an item to the tool bar in map MAP.
ICON names the image, DEF is the key definition and KEY is a symbol
for the fake function key in the menu keymap. Remaining arguments
PROPS are additional items to add to the menu item specification. See
Info node ‘(elisp)Tool Bar’. The item is added after AFTER_ITEM.
ICON is the base name of a file containing the image to use. The
function will first try to use low-color/ICON.xpm if ‘display-color-cells’
is less or equal to 256, then ICON.xpm, then ICON.pbm, and finally
ICON.xbm, using ‘find-image’."
(let* ((image-exp (tool-bar--image-expression icon)))
(define-key-after map (vector key)
`(menu-item ,(symbol-name key) ,def :image ,image-exp ,#props) after_item)
(force-mode-line-update)))
(when (boundp 'tool-bar-map)
(tool-bar-local-item-pre "new" 'new-file-tmp 'new-file-tmp tool-bar-map
'new-file :label "" :help "New untitled File")
(define-key tool-bar-map (vector 'new-file) nil)
;; comment the above line if you want to keep the button for the default behavior
)
(global-set-key (kbd "C-n") 'new-file-tmp)
It defines a new command which creates new empty buffers
Then the code binds it to the top left button of the toolbar, if you are in gui mode, and to the Control-n shortcut.
You can check the post on my site about it.
disclaimer: it's my site
A buffer and a file are not the same thing.
terminology
Regarding buffers,
The text you are editing in Emacs resides in an object called a
buffer. Each time you visit a file, a buffer is used to hold the file's text.
Regarding files,
The operating system stores data permanently in named files, so most
of the text you edit with Emacs comes from a file and is ultimately
stored in a file.
Buffers and files are related through visiting,
Visiting a file means reading its contents into an Emacs buffer so you
can edit them. Emacs makes a new buffer for each file that you visit.
answering the question
Unless I'm mistaken, technically speaking, your question, as written, can't be answered. Pedantically speaking, there's no such thing as (or little practical use for) an unnamed file. A file is a handle for something stored on disk. If you have no handle, then why make a file?
The question can then be interpreted as having two possible meanings1.
1. Making a new buffer (without regard to name)
A new buffer must have a name. An unsaved buffer can be saved to file with a given name using write-file (C-x C-w). You will be prompted for a path/name. Once written, the buffer update to be visiting the file you just wrote.
Since the name of the buffer doesn't matter (until you write it to file), here's a function which creates buffers named *scratch1*, *scratch2*, ... .
(defun create-scratch-buffer ()
"Create a new numbered scratch buffer.
Taken from URL `https://stackoverflow.com/a/21058075/5065796' "
(interactive)
(let ((n 0)
bufname)
(while (progn
(setq bufname (concat "*scratch"
(if (= n 0) "" (int-to-string n))
"*"))
(setq n (1+ n))
(get-buffer bufname)))
(switch-to-buffer (get-buffer-create bufname))
(org-mode)
(if (= n 1) initial-major-mode)))
2. Making a new file (without regard to name)
As hinted at in the new buffer solution, new files can be created with write-file.
When called interactively (M-x make-random-file), this function prompts for a directory. It then writes an empty file named something random like tmp-17388716387615.txt.
(defun make-random-file (dir)
"Make a random file in DIR."
(interactive "DDir: ")
(let* ((filename (concat "tmp-" (int-to-string (random t)) ".txt"))
(filepath (concat dir filename)))
(write-region "" nil filepath nil 'silent nil 'excl)))
As always, if the code above doesn't make sense, look at the documentation for functions and variables with C-h f and C-h v, respectively. And/or read the Introduction to Programming in Emacs Lisp.
1 It was the second meaning which I was searching for solutions to when I found this as the top search engine hit. Apologies if this was a bit obtuse. Figured it was better to share my solutions with y'all than not. :)

Emacs org-mode: textual reference to a file:line

I am using org-mode in Emacs to document my development activities. One of the tasks which I must continuously do by hand is to describe areas of code. Emacs has a very nice Bookmark List: create a bookmark with CTRL-x r m, list them with CTRL-x r l. This is very useful, but is not quite what I need.
Org-mode has the concept of link, and the command org-store-link will record a link to the current position in any file, which can be pasted to the org-file. The problem with this is two-fold:
It is stored as an org-link, and the linked position is not directly visible (just the description).
It is stored in the format file/search, which is not what I want.
I need to have the bookmark in textual form, so that I can copy paste it into org-mode, end edit it if needed, with a simple format like this:
absolute-file-path:line
And this must be obtained from the current point position. The workflow would be as simple as:
Go to the position which I want to record
Call a function: position-to-kill-ring (I would bind this to a keyboard shortcut)
Go to the org-mode buffer.
Yank the position.
Edit if needed (sometimes I need to change absolute paths by relative paths, since my code is in a different location in different machines)
Unfortunately my lisp is non-existent, so I do not know how to do this. Is there a simple solution to my problem?
(defun position-to-kill-ring ()
"Copy to the kill ring a string in the format \"file-name:line-number\"
for the current buffer's file name, and the line number at point."
(interactive)
(kill-new
(format "%s:%d" (buffer-file-name) (save-restriction
(widen) (line-number-at-pos)))))
You want to use the org-create-file-search-functions and org-execute-file-search-functions hooks.
For example, if you need the search you describe for text-mode files, use this:
(add-hook 'org-create-file-search-functions
'(lambda ()
(when (eq major-mode 'text-mode)
(number-to-string (line-number-at-pos)))))
(add-hook 'org-execute-file-search-functions
'(lambda (search-string)
(when (eq major-mode 'text-mode)
(goto-line (string-to-number search-string)))))
Then M-x org-store-link RET will do the right thing (store a line number as the search string) and C-c C-o (i.e. M-x org-open-at-point RET) will open the file and go to this line number.
You can of course check for other modes and/or conditions.
An elisp beginner myself I though of it as a good exercise et voila:
Edit: Rewrote it using the format methode, but I still think not storing it to the kill-ring is less intrusive in my workflow (don't know about you). Also I have added the capability to add column position.
(defvar current-file-reference "" "Global variable to store the current file reference")
(defun store-file-line-and-col ()
"Stores the current file, line and column point is at in a string in format \"file-name:line-number-column-number\". Insert the string using \"insert-file-reference\"."
(interactive)
(setq current-file-reference (format "%s:%d:%d" (buffer-file-name) (line-number-at-pos) (current-column))))
(defun store-file-and-line ()
"Stores the current file and line oint is at in a string in format \"file-name:line-number\". Insert the string using \"insert-file-reference\"."
(interactive)
(setq current-file-reference (format "%s:%d" (buffer-file-name) (line-number-at-pos))))
(defun insert-file-reference ()
"Inserts the value stored for current-file-reference at point."
(interactive)
(if (string= "" current-file-reference)
(message "No current file/line/column set!")
(insert current-file-reference)))
Not tested extensively but working for me. Just hit store-file-and-line or store-file-line-and-col to store current location and insert-file-reference to insert the stored value at point.
BTW, if you want something better than FILE:LINE, you can try to use add-log-current-defun (in add-log.el) which should return the name of the current function.
;; Insert a org link to the function in the next window
(defun insert-org-link-to-func ()
(interactive)
(insert (with-current-buffer (window-buffer (next-window))
(org-make-link-string
(concat "file:" (buffer-file-name)
"::" (number-to-string (line-number-at-pos)))
(which-function)
))))
This func generates link with the function name as the description.
Open two windows, one is the org file and the other is src code.
Then M-x insert-org-link-to-func RET

How can I open a temporary buffer

For very long time I have done: C-x b and then some "unique" name like xbxb. So I use switch-to-buffer with a non-existent buffer. You can imagine what C-x C-b shows me: Lots of such names. xbxb, xbxbxxx .... It really gets annoying after some time (a week or so), since I discover that I have already used all good names.
Is there a more canonical way of opening a new buffer? If I want to run a shell a further time, I say C-u M-x shell. Something along that line would be ideal.
You can use make-temp-name to generate a name for a file or buffer with a random postfix. With that as a base, you can write something like this:
(defun generate-buffer ()
(interactive)
(switch-to-buffer (make-temp-name "scratch")))
where "scratch" can be replaced by whatever prefix you'd like.
make it so:
(defun new-scratch ()
"open up a guaranteed new scratch buffer"
(interactive)
(switch-to-buffer (loop for num from 0
for name = (format "blah-%03i" num)
while (get-buffer name)
finally return name)))
I signed up just to answer this question (because I use this function a lot, so I thought it'd be useful to share it here):
(defun tmpbuf (buf)
"open a buffer,
if it doesn't exist, open a new one"
(interactive "sBuffer name: ")
(switch-to-buffer
(get-buffer-create (concat "*" buf "*"))))
I'm not really sure what you want. You say that "I discover that I have already used all good names", so letting Emacs generate the names isn't going to be any good, but if you are going to specify the name yourself, it doesn't get any more canonical than C-xb name RET.
Otherwise, one of the functions already suggested to let you enter a string and use that with some kind of "tmp buffer" pattern to create a new name would seem sensible.
Or scratch.el might prove useful, if what you actually wanted was a single temp buffer per major mode.
You could almost certainly benefit from binding C-xC-b to ibuffer, and using filters and/or groups to separate out the temporary buffers from the more important ones. That would deal with the list getting cluttered.
You seem oddly resistant to writing a new function? Even if there did turn out to be something built in, there's nothing wrong with using custom functions -- that's generally how you go about customising Emacs to your liking.
(defun yashi/new-scratch-buffer-in-org-mode ()
(interactive)
(switch-to-buffer (generate-new-buffer-name "*temp*"))
(org-mode))
(bind-key "<f7>" 'yashi/new-scratch-buffer-in-org-mode)
I'm using deft for a quick note-taking but sometimes I know I won't need the content but need a buffer in Org mode. For that, it's been serving me well. Hit F7 again will create a buffer with similar name, *temp*<2> in my case, acording to Uniquify.
BTW, here is a command to launch a new buffer with a new deft file, if you are interested. F6 to launch it.
(defun yashi/deft-new-file ()
(interactive)
(let ((deft-filter-regexp nil))
(deft-new-file)))
(bind-key "<f6>" 'yashi/deft-new-file)
I use this to open up a temporary buffer. Good thing? Helps me track which buffers I'd opened, and when.
(defun tmp-buffer()
"Make a temporary buffer and switch to it - Like C-n for Sublime etc"
(interactive)
(switch-to-buffer (get-buffer-create (concat "tmp-" (format-time-string "%m.%dT%H.%M.%S")))))
You are given access to someone else's Emacs and you want to open a new buffer. If you are lucky, this someone has set enable-recursive-minibuffers to t. If not, you can temporarily do M-: to eval this Emacs Lisp expression (don't forget to restore this parameter later):
(setq enable-recursive-minibuffers t)
Now, you open a new buffer:
C-xb prompts for a buffer name
C-uM-: will eval and print the result of the expression to the minibuffer prompt:
(random)
This gives you a random number in the full range of representable integers (including negative ones), which is very unlikely to be already taken. Press Return to conclude to switch to the new buffer.
I was looking for a solution for which I have the freedom to give a name or it randomly generates a name. I merged the andswer of #dotemacs and the answer of R. P. Dillon. I'm a n00b in elisp so it took me some half an hour to resolve some of my stupid mistakes.
(defun mm/generate-temp-buffer (buf)
"A function to generate temprory buffers using either
a random name or given name"
(interactive "sNew temp buffer name: ")
(switch-to-buffer
(get-buffer-create
(concat "*tmp*"
(if (equal buf "")
(make-temp-name "")
buf)
"*")
)))
This is how it works:
you run the function (M-x mm/generate-temp-buffer)
you are asked for a name.
2.1. if you type something it will create a buffer named *tmp*YOUR_STRING*
2.2. if you don't give an input and just press RET, it will create a buffer named something like *tmp*o8f4Mf*
Hopefully this is useful to others and save someone's time.

emacs: interactively search open buffers

Is there a way to search all the open buffers for a particular pattern?
C-s interactively searches current buffer.
Similarly, is there something that searches all the open buffers?
I know I can use "occur", but "Occur" brings a new buffer and changes/messes with the buffer organization.
The built-in multi-occur-in-matching-buffers hasn't been mentioned. I use a modified version of this (because I invariably want to search all buffers, and specifying a buffer name pattern each time is annoying).
(defun my-multi-occur-in-matching-buffers (regexp &optional allbufs)
"Show lines matching REGEXP in all file-visiting buffers.
Given a prefix argument, search in ALL buffers."
(interactive (occur-read-primary-args))
(multi-occur-in-matching-buffers "." regexp allbufs))
(global-set-key (kbd "M-s /") 'my-multi-occur-in-matching-buffers)
To invert the behaviour of the prefix argument so that the default behaviour is to search all buffers, change the call to:
(multi-occur-in-matching-buffers "." regexp (not allbufs))
(and, of course, update the docstring accordingly.)
I've fixed the TODO:
;; I know that string is in my Emacs somewhere!
(require 'cl)
(defcustom search-all-buffers-ignored-files (list (rx-to-string '(and bos (or ".bash_history" "TAGS") eos)))
"Files to ignore when searching buffers via \\[search-all-buffers]."
:type 'editable-list)
(require 'grep)
(defun search-all-buffers (regexp prefix)
"Searches file-visiting buffers for occurence of REGEXP. With
prefix > 1 (i.e., if you type C-u \\[search-all-buffers]),
searches all buffers."
(interactive (list (grep-read-regexp)
current-prefix-arg))
(message "Regexp is %s; prefix is %s" regexp prefix)
(multi-occur
(if (member prefix '(4 (4)))
(buffer-list)
(remove-if
(lambda (b) (some (lambda (rx) (string-match rx (file-name-nondirectory (buffer-file-name b)))) search-all-buffers-ignored-files))
(remove-if-not 'buffer-file-name (buffer-list))))
regexp))
(global-set-key [f7] 'search-all-buffers)
ibuffer might help you. Have a look at this article. I imagine that this might be most interesting for you:
'O' - ibuffer-do-occur
- Do an occur on the selected buffers.
This does a regex search on all the selected buffers and displays the result in an occur window. It is unbelievably useful when browsing through code. It becomes truly awesome when you combine it with the ‘filter’ powers of ibuffer (coming up ahead). Eg: Do C-x C-b, mark all files using (say) Perl major-mode, do occur to find out all places where a certain function is mentioned in these files. Navigate to the point at will through the Occur window.
'M-s a C-s' - ibuffer-do-isearch
- Do an incremental search in the marked buffers.
This is so awesome that you have to try it right this instant. Select two or more buffers, hit the hotkey, search for something that occurs in all these buffers. These two features alone are enough to make me a lifelong fan of IBuffer. Go do it now!
Taking a clue from Leo's comment to Bozhidar:
(defun my-isearch-buffers ()
"isearch multiple buffers."
(interactive)
(multi-isearch-buffers
(delq nil (mapcar (lambda (buf)
(set-buffer buf)
(and (not (equal major-mode 'dired-mode))
(not (string-match "^[ *]" (buffer-name buf)))
buf))
(buffer-list)))))
You might have to tweak the conditions inside the and to filter whatever other kinds of buffers you want to ignore.
Although this is not exactly what you're asking for, I search multiple files using grep (M-X grep) and grep-find (M-X grep-find).
This sort of does what you want, in that when you've come to the end of matches for the string/regexp you're searching for, the next search command will start in a new buffer.
(setq isearch-wrap-function 'isearch-bury-buffer-instead-of-wrap)
(defun isearch-bury-buffer-instead-of-wrap ()
"bury current buffer, try to search in next buffer"
(bury-buffer))
It doesn't switch to a different buffer when the search fails, and when you "back up" the search results by pressing <backspace>, you won't pop back into the previous buffers searched.
In Icicles, C-c ' is command icicle-occur, which can search multiple buffers.
C-u C-c ' searches a set of buffers that you choose. You can choose by dynamically filtering the buffer names with your minibuffer input, then hit C-! to search all of those buffers whose names match. Similarly, C-99 C-c ' searches only the buffers that are visiting files.
Like occur and grep, icicle-occur searches line by line. More generally, instead of using lines as the search contexts you can use any buffer portions at all. C-c ` (backquote instead of quote) is command icicle-search. With a non-negative prefix arg it searches a set of buffers that you choose.
The first thing you do is give it a regexp that defines the search contexts. E.g., if you give it .* then it acts like icicle-occur: each search context is a line. If you give it a regexp that matches only function definitions then those are the search contexts, and so on.
http://www.emacswiki.org/emacs/Icicles_-_Search_Commands%2c_Overview

How to get equivalent of Vim's :Texplore in Emacs?

I know about M-x dire, but would like to customize it. I would like to hit one key (for example F2) and get dire buffer open. When I navigate across the directory hierarchy it shouldn't open new buffers.
And when I finally open the file it also shouldn't open new buffer for it (not strictly necessary, but strongly preferred).
Of course this behavior can be global, i.e. for all dire buffers/invocations.
Check out dired-single, which pretty much does what you want (except that last bit, where it reuses the dired buffer for the newly visted file).
Caveat Lector: I wrote it, so I'm biased towards its usefulness.
Some alternatives - EmacsWiki: DiredReuseDirectoryBuffer, and this short snippet from an awkwardly-formatted blog-entry.
caveat: haven't tried them, myself.
I know this is very old but All you have to do is press 'a' on a dir or file to get this functionality. It's already there.
Here's what I finally used:
(require 'dired)
(global-set-key [(f2)] 'my-dired)
(defun my-dired ()
(interactive)
(dired (file-name-directory (buffer-file-name))))
(defadvice dired-advertised-find-file (around dired-subst-directory activate)
"Replace current buffer if file is a directory."
(interactive)
(let ((orig (current-buffer)) (filename (dired-get-filename :no-error-if-not-filep t)))
ad-do-it
(when (not (eq (current-buffer) orig)) (kill-buffer orig))))