Create a new file with a similar name in Emacs with Helm - emacs

I always end up opening an eshell and executing find-file new-file-name, because helm always supplies me with candidates and a million options that don't look like the basic feature that I want: forcing the file to be called what I typed. For example, I want to great an org document called mto.org in a directory with another org file in it.
How can I force helm to create the file with the name I typed, so I can save 10 seconds by avoiding opening up eshell and adding a small, but (hopefully easily) avoidable disruption of my concentration?

You can press C-p and select the line
[?] mto.org
and then just press RET. It will (ask you to) create the file with the name you typed.

Related

How do create a new file that matches an existing file in Emacs Prelude?

In Emacs Prelude, I cannot figure out how to create a new file when a file exists that "matches" the name of the file.
In the example screen capture, I am trying to create a file called spawn.exs in a directory that already contains a file called spawn_basic.exs. When I use C-xC-f to create a new file, emacs is matching spawn.exs to spawn_basic.exs and hitting Enter results in opening spawn_basic.exs instead of creating spawn.exs.
I've tried some workarounds (i.e. using touch to create the file) but I'm looking for a simpler solution that would require only one command. If there is not a command to do this, is there a way to disable the file name matching feature in Prelude? I like most everything else about Prelude compared to vanilla Emacs so I would rather not switch back.
In Prelude, C-x C-f is bound to helm-find-files. It's usually
great, but for this case I don't see a good workaround for bypassing
its match (as you've described).
However, ido-find-file has a similarly friendly completion system,
yet offers a nice solution to bypass the completion. When you type
spawn.exs, open by pressing C-j instead of RET. I think Helm
should do this too (instead of treating them the same), so you might
want to submit a feature request (to match Ido's "verbatim entry").
Ido works well as a find-file replacement, and it's recommended over
Helm for simple cases like this
in Mastering Emacs. So you could
remap it with:
(global-set-key (kbd "C-x C-f") 'ido-find-file)

Buffer menu to select a set of filenames in Emacs

I have a directory "a" with a set of templates, for instance
$ ls a
b bcc cc ccdd
I would like to implement a keyboard shortcut in Emacs that will show a buffer with the template names, similar to dired or buffer-menu and then be able to select a template name by using arrow keys or mouse. Then insert the selected template into the current buffer at point.
How can this be done?
To augment Chris' answer with a little code, here is a small wrapper around ido-insert-file:
(require 'ido)
(defvar so/template-directory "/tmp/templates"
"Directory where template files are stored")
(defun so/insert-template ()
(interactive)
(let ((default-directory so/template-directory))
(ido-insert-file)))
This allows you to run (or bind a key to) so/insert-template no matter what directory you are currently in. Obviously set so/template-directory to your preferred directory.
insert-file, bound to C-x i by default, can insert a file into your buffer at point, but it doesn't give you a nice menu. Both helm and ido enhance this behaviour.
helm does not come with Emacs, but it can be installed via MELPA. When helm-mode is active, insert-file uses Helm's narrowing features. Once you're in the a directory, the up and down keys may be used to select a file, and Enter will insert it.
ido is shipped with Emacs. When ido-mode is active, C-x i is rebound to ido-insert-file. Once you're in the a directory, the left and right keys may be used to select a file, and Enter will insert it.
Both tools are excellent, both can be used in many other situations, and both offer effective filtering and navigation. Try one or both and use whichever you prefer.
Everything #Chris said about Helm and Ido is true also for Icicles, and with better "narrowing" features and on-the-fly sorting in different orders.
There is nothing extra to do --- just load Icicles and turn on Icicle minor mode. Whenever you use standard command insert-file (bound to C-x i) you get the behavior you requested for free. This behavior is in fact available for all completion in Emacs. In Icicle mode, standard commands become menus you can use the arrow keys on, etc.
In addition, your question title asks to be able to "select a set" of files. You can do that easily in Icicles, but not otherwise. IOW, selection is also multi-selection.
(However, I suspect that your question is mistitled, since the text describes something different, and I doubt that you want to insert a set of files. You probably meant that you want to select one file name from a set of file names. Consider retitling the question, if so.)

Bookmark+ using a temporary file, despite having asked for a specific file

After typing C-x r l I get a buffer called *Bookmark List*
In this buffer I see:
Bookmark file:
/tmp/bmkp-temp/19236bkt
If I open help (i.e. press h), I see:
Bookmark file: /tmp/bmkp-temp-19236bkt
Sorted:
Filtering: none
Marked: 0
Omitted: 0
Autosave bookmarks: no
Autosave list display: yes
This is even though I have the following in my .emacs file:
(setq bookmark-file "~/.emacs.d/bookmarks")
(setq bookmark-default-file "~/.emacs.d/bookmarks")
(setq bmkp-default-bookmark-file "~/.emacs.d/bookmarks")
(setq bmkp-last-as-first-bookmark-file nil)
Why is it using a different bookmark file from the one I specified?
I also noticed that when I load Emacs the following happens:
Emptying bookmark file `/tmp/bmkp-temp-23808OMn'...
Saving file /tmp/bmkp-temp-23808OMn...
Wrote /tmp/bmkp-temp-23808OMn
Emptying bookmark file `/tmp/bmkp-temp-23808OMn'...done
...
Helm completion enabled
Emptying bookmark file `/tmp/bmkp-temp-23808bWt'...
Saving file /tmp/bmkp-temp-23808bWt...
Wrote /tmp/bmkp-temp-23808bWt
Emptying bookmark file `/tmp/bmkp-temp-23808bWt'...done
...
Emacs goes on a spree deleting temporary bookmark files. ?
Perhaps you were trying to use "bookmark-file bookmarks"? Or anyways, accidently hit C-x p x?
These are claimed to correspond, at EmacsWiki: Bookmark Plus / Bookmark-File Bookmarks, where they say, "bmkp-set-bookmark-file-bookmark, bound to C-x p x". For my Emacs, this is not true.
By typing C-x p C-h, I can check key-bindings that start with C-x p. I find
C-x p x is bound to bmkp-toggle-autotemp-on-set, and
C-x p y is bound to bmkp-set-bookmark-file-bookmark.
Then, the link should say C-x p y instead.
It looks like something, somewhere (e.g. check your .emacs file) has turned on bmkp-temporary-bookmarking-mode. When that mode is on, any bookmarks you create are for the current session only -- they are not saved to your bookmark file.
And that means that your bookmark-file location settings are ignored. (Note, BTW, that bmkp-default-bookmark-file is a function, not a variable -- it is not something that you set. And you don't need all of those bookmark-file settings; some are redundant: old names from old versions of Emacs bookmarking.)
I don't know why you are getting multiple temporary bookmark-file creations and saves. You didn't provide a complete recipe. You should get only one such. This is all I see in *Messages* in this regard, for instance:
Emptying bookmark file `c:/DOCUME~1/me/LOCALS~1/Temp/bmkp-temp-5348su1'...
Saving file c:/Documents and Settings/me/Local Settings/Temp/bmkp-temp-5348su1...
Wrote c:/Documents and Settings/me/Local Settings/Temp/bmkp-temp-5348su1
Emptying bookmark file `c:/DOCUME~1/me/LOCALS~1/Temp/bmkp-temp-5348su1'...done
It also appears that you have a lot of stuff going on (Helm etc.). When trying to understand or debug a problem, it helps to narrow things down as much as possible. Who can tell what other interactions might be involved here?
All of that said, my advice would be to not start out using the temporary bookmarking mode. I would not suggest you use that until you are quite familiar with Bookmark+. You can use temporary bookmarks without using this mode.
Here is the doc about using temporary bookmarks:
http://www.emacswiki.org/cgi-bin/wiki/BookmarkPlus#toc55
Finally, as Stefan suggested, please follow up by email. It's a lot easier for debugging/discussing things in detail.
Thx -- Drew
Update 2019-04-21:
I think what might have happened is that you quit Emacs with bmkp-temporary-bookmarking-mode enabled. Although Bookmark+ (correctly) does not save the file of temporary bookmarks it was not preventing the recording of bmkp-last-as-first-bookmark-file from being updated to point to the temporary file. In your next Emacs session that temporary file (if it still existed) was loaded because of bmkp-last-as-first-bookmark-file.
That should be OK now. Enabling bmkp-temporary-bookmarking-mode now resets bmkp-last-as-first-bookmark-file to nil, so if you quit with the temp mode still enabled, then when you load your bookmark file in a new session the file that is read is the value of bookmark-default-file. (The value of bookmark-default-file is never changed, except by your
customizations.)
It's quite an old question, but since I had just the same problem and the other answers didn't help me I'll post my solution:
I'm using desktop files from desktop.el and the temporary mode was set there in the desktop file! Removing that setting from all my desktop files fixed the problem.
This might be handy:
find ~ -name .emacs.desktop -print0 | xargs -0 grep -l bmkp-temporary-bookmarking-mode

Emacs filesets: how to run other (elisp, not shell) commands?

There are 5 Elisp commands that can be run on an Emacs fileset, plus the ability to run any shell command. What about all the other Emacs commands? Just to give one example, it would be nice to be able to run M-x occur on a fileset.
I know its possible to mark several files in dired and then run any Emacs command on them (is that true, or am I confused with shell commands?), but it would be very convenient to define a fileset once and then be able to use it like one single file for all kinds of text editing.
Thanks for any advice
The commands that can operate on file sets are specified in the global custom variable "filesets-commands". You can add your own commands to that list. The default value for this variable is:
("Isearch" multi-isearch-files
(filesets-cmd-isearch-getargs))
("Isearch (regexp)" multi-isearch-files-regexp
(filesets-cmd-isearch-getargs))
("Query Replace" perform-replace
(filesets-cmd-query-replace-getargs))
("Query Replace (regexp)" perform-replace
(filesets-cmd-query-replace-regexp-getargs))
("Grep <<selection>>" "grep"
("-n " filesets-get-quoted-selection " " "<<file-name>>"))
("Run Shell Command" filesets-cmd-shell-command
(filesets-cmd-shell-command-getargs)))
The values consist of an association list of names, functions, and an argument list (or a function that returns one) to be run on a filesets' files. So, if you wanted to add a command that does an "occur" command on the file set, you could use the "Isearch" entry as an example to create your own new entry (that you would add to the "filesets-commands" global variable) that would look something like:
("Occur (regexp)" multi-occur-files-regexp
(filesets-cmd-occur-getargs))
You would need to write the "multi-occur-files-regexp" and "filesets-cmd-occur-getargs" functions (you could use the existing "multi-isearch-files-regexp" and "filesets-cmd-isearch-getargs" functions as a basis since they would be similar). The same would apply for any additional Emacs command that you wanted to add to work on file sets.
Dired has several operations on filesets. An example is dired-do-search (bound to A), where you can navigate through search results on several files with M-, just like with tags-search. Similarly, you can query-replace in tagged files (with Q).
The recent posts on irreal.org describe some nice dired features.
With Icicles you can use filesets for anything you might want to do with a set of files and directories. And you can create a fileset from any set of file and directory names in buffer Completions during completion. And you can use substring and regexp matching during completion to get such a set of file names in Completions.
These links might help:
http://www.emacswiki.org/emacs/Icicles_-_Persistent_Completions#Filesets
http://www.emacswiki.org/emacs/Icicles_-_Dired_Enhancements#OpenDiredOnSavedFiles
http://www.emacswiki.org/emacs/Icicles_-_Dired_Enhancements#MarkedFilesAsProject
http://www.emacswiki.org/emacs/Icicles_-_Customization_and_General_Tips#icicle-filesets-as-saved-completion-sets-flag
Dired+ has command diredp-fileset, which opens Dired on an Emacs fileset. You are prompted for the fileset to use.

Using Emacs to recursively find and replace in text files not already open

As a follow-up to this question, it's trying to find out how to do something like this which should be easy, that especially stops me from getting more used to using Emacs and instead starting up the editor I'm already familiar with. I use the example here fairly often in editing multiple files.
In Ultraedit I'd do Alt+s then p to display a dialog box with the options: Find (includes using regular expressions across multiple lines), Replace with, In Files/Types, Directory, Match Case, Match Whole Word Only, List Changed Files and Search Sub Directories. Usually I'll first use the mouse to click-drag select the text that I want to replace.
Using only Emacs itself (on Windows XP), without calling any external utility, how to replace all foo\nbar with bar\nbaz in *.c and *.h files in some folder and all folders beneath it. Maybe Emacs is not the best tool to do this with, but how can it be done easily with a minimal command?
M-x find-name-dired: you will be prompted for a root directory and a filename pattern.
Press t to "toggle mark" for all files found.
Press Q for "Query-Replace in Files...": you will be prompted for query/substitution regexps.
Proceed as with query-replace-regexp: SPACE to replace and move to next match, n to skip a match, etc.
Press C-x s to save buffers. (You can then press y for yes, n for no, or ! for yes for all)
M-x find-name-dired RET
it may take some time for all the files to appear in the list, scroll to bottom (M->) until "find finished" appears to make sure they all have loaded
Press t to "toggle mark" for all files found
Press Q for "Query-Replace in Files...": you will be prompted for query/substitution regexps.
Proceed as with query-replace-regexp: SPACE or y to replace and move to next match, n to skip a match, etc.
Type ! to replace all occurrences in current file without asking, N to skip all possible replacement for rest of the current file. (N is emacs 23+ only)
To do the replacement on all files without further asking, type Y.
Call “ibuffer” (C-x C-b if bound to ibuffer, or M-x ibuffer RET) to list all opened files.
Type * u to mark all unsaved files, type S to save all marked files
* * RET to unmark all marks, or type D to close all marked files
This answer is combined from this answer, from this site, and from my own notes. Using Emacs 23+.
Projectile is really nice:
C-c p r runs the command projectile-replace
The answers provided are great, however I thought I'd add a slightly different approach.
It's a more interactive method, and requires wgrep, rgrep and iedit. Both iedit and wgrep must be installed via MELPA or Marmalade (using M-x package-list-packages)
First run M-x rgrep to find the string you're looking for.
You'll be able to specify file types/pattern and the folder to recurse.
Next you'll need to run wgrep start it with C-s C-p.
Wgrep will let you edit the rgrep results, so set a region on the string to match and start iedit-mode with C-; (depending on your terminal you may need to re-bind this)
All occurrences will be editable at once. C-x C-s to commit wgrep. Then C-x s ! to save the changed files.
The main benefit of this method is that you can use iedit-mode to toggle off certain matches M-;. You can also use the results in rgrep to jump into the files, for example if you have an unexpected match.
I find it very useful for doing source edits and renaming symbols (variables, function names etc.) across a project.
If you don't already know/use iedit mode it's a very handy tool, I strongly recommend you give it a look.
I generally use other tools to perform this task, and it seems like many of the approaches mentioned at EmacsWiki's Find and Replace Across Files entry shell out, but the Findr Package looks very promising.
Stealing part of the source file:
(defun findr-query-replace (from to name dir)
"Do `query-replace-regexp' of FROM with TO, on each file found by findr.
Source of information: 1
For emacs pro users:
Call dired to list files in dir, or call find-dired if you need all subdirectories.
Mark the files you want. You can mark by regex by typing 【% m】.
Type Q to call dired-do-query-replace-regexp.
Type your find regex and replace string. 〔☛ common elisp regex pattern〕
For each occurrence, type y to replace, n to skip. Type 【Ctrl+g】 to abort the whole operation.
Type ! to replace all occurrences in current file without asking, N to skip all possible replacement for rest of the current file. (N is emacs 23 only)
To do the replacement on all files without further asking, type Y. (Emacs 23 only)
Call ibuffer to list all opened files. Type 【* u】 to mark all unsaved files, type S to save all marked files, type D to close them all.
Step-by-Step Guide for Emacs Beginners
Select Target Files
Start emacs by typing “emacs” in the command line interface prompt. (Or, double click the Emacs icon if you are in a Graphics User Interface environment)
Selecting Files in a Directory
First you need to select the files you want to do the replace. Use the graphical menu 〖File ▸ Open Directory〗. Emacs will ask you for a directory path. Type the directory path, then press Enter.
Now, you will be shown the list of files, and now you need to mark the files you want the regex find/replace to work on. You mark a file by moving the cursor to the file you want, then press m. Unmark it by pressing u. (To list subdirectories, move your cursor to the directory and press i. The sub-directory's content will be listed at the bottom.) To mark all files by a regex, type 【% m】, then type your regex pattern. For example, if you want to mark all HTML files, then type 【% m】 then .html$. (You can find a list of the mark commands in the graphical menu “Mark” (this menu appears when you are in the dired mode).)
Selecting Files in a Directory and All Its Sub-Directories
If you want to do find/replace on files inside a directory, including hundreds of subdirectories, here's a method to select all these files.
Call find-dired. (you call a command by pressing 【Alt+x】) Then, type a directory name, ⁖ /Users/mary/myfiles
Note: if you are using emacs on a unix non-graphical text terminal, and if 【Alt+x】 does not work, the equivalent key stroke is 【Esc x】.
Emacs will ask you with the prompt “Run find (with args): ”. If you need to do the replacement on all HTML files, then type -name "*html". If you don't care about what kind of file but simply all files under that dir, then give “-type f”.
Now, mark the files as described above.
Interactive Find/Replace
Now, you are ready to do the interactive find replace. For simplicity, let's say you just want to replace the word “quick” by “super”. Now, call dired-do-query-replace-regexp. It will prompt you for the regex string and the replacement string. Type “quick”, enter, then “super”.
Now, emacs will use your pattern and check the files, and stop and show you whenever a match occurred. When this happens, emacs will prompt you, and you have a choice of making the change or skip the change. To make the change, type y. To skip, type n. If you simply want emacs to go ahead and make all such changes to the current file, type !.
If you want to cancel the whole operation without saving any changes you've made, type 【Ctrl+g】, then exit emacs using the menu 〖File ▸ Exit Emacs〗.
Saving the Changed Files
Now, after you went through the above ordeal, there is one more step you need to do, and that is saving the changed files.
If you are using emacs version 22 or later, then call ibuffer to go into a buffer listing mode, then type 【* u】 to mark all unsaved files, then type S to save them all. (that's shift-s)
If you are using a emacs version 21, then you can do this: call list-buffers, then move the cursor to the file you want to save and type s. It will mark the file for later save action. Type u to unmark. Once you are done, type x to execute the saving of all files marked for save. (in emacs, opened file is called “buffer”. Disregard other things there.)
Alternative to the above options, you can also call save-some-buffers 【Ctrl+x s】. Then emacs will display each unsaved file and ask if you want it saved.
Note: emacs's regex is not the same as Perl or Python's, but similar. For a summary and common patterns, see: Emacs Regex.
Using dired to recurse down a deep directory tree is going to be a bit slow for this task. You might consider using tags-query-replace. This does mean shelling out to create a tags table, but that is often useful anyway, and it's quick.
For open buffers, this is what I do :
(defun px-query-replace-in-open-buffers (arg1 arg2)
"query-replace in all open files"
(interactive "sRegexp:\nsReplace with:")
(mapcar
(lambda (x)
(find-file x)
(save-excursion
(goto-char (point-min))
(query-replace-regexp arg1 arg2)))
(delq
nil
(mapcar
(lambda (x)
(buffer-file-name x))
(buffer-list)))))
M-X Dired, and t to mark all files, and Q to query replace text in all of them.
You can expand a sub directory by using the i command before the query-replace.
They key info I'm adding is that if you give a prefix (control-u) to the i command,
it will prompt you for arg, and -R argument will recursively expand all subdirs
into the dired buffer. So now you can query-search every file in an entire directory.
Another option is to use Icicles search. This is a different kind of incremental search that uses completion of your minibuffer input against search hits. As you modify your current input the set of matching hits is updated in buffer *Completions*.
You can search any number of files, buffers, or bookmarked locations, which you can choose using minibuffer pattern (e.g. regexp) matching.
When you visit a search hit you can replace on demand either the entire hit or just the part of it that matches your current minibuffer input. Replacement on demand means you are not queried about each search hit in turn; you access the hits you want directly, in any order. This approach can be more effective than query-replace if you have a limited number of replacements to make: you skip the exhaustive y/n prompting.
Search is over search contexts that you define -- you are not limited to searching all of the text in the target files (e.g., you can skip comments or particular kinds of program sections). A simple example of a search context is a line, as in grep, but a context can be any pattern-matched block of text you like. Typically you define the search contexts using a regexp, but you can instead use a function. In addition to defining your own, there are predefined Icicles search commands for different kinds of contexts: blocks of text properties or overlay properties, thing-at-point things, etc.
You can also sort the search hits in various sort orders for easier access/navigation.
find-name-dired is OK, but:
All of the files you get match the same, single regexp.
find-dired is more flexible in that regard, but it too is made for using general rules (even if they can be arbitrarily complex). And of course find has its own, complex language.
if you then want to act on only some of the files whose names were collected in the find(-name)-dired buffer, you need to either mark them or delete/omit the lines of those you do not want to act on.
An alternative is to use Dired+ commands that act on (a) the marked files and (b) all marked files (or all files, if none are marked) in the marked subdirectories ... found recursively. This gives you both generality and easy control over file choice. These "here-and-below" commands are all on prefix key M-+ in Dired mode.
For example, M-+ Q is the same as Q --- query-replace, but the target files are all of those marked in the current dir and in any marked subdirs, down, down, down...
Yes, an alternative to using such here-and-below commands is to insert all subdirs and their subdirs, recursively, and then use a top-level command such as Q. But it can often be convenient not to bother with inserted subdirs.
And to do that you anyway need a quick way to insert all such subdirs recursively. Here too, Dired+ can help. M-+ M-i inserts all marked subdirs and their own marked subdirs, recursively. That is, it is like M-i (which inserts the marked subdirs in Dired+), but it acts recursively on subdirs.
(All such "here-and-below" Dired+ commands are on menu Multiple > Marked Here and Below.)
You can also perform Dired operations on an Emacs fileset, which is a saved set of names of files located anywhere. And if you use Icicles then you can open a Dired buffer for just the files in a fileset or other types of saved file lists.
You can also bookmark any Dired buffer, including one that you create using find(-name)-dired. This gives you a quick way to return to such a set (e.g. a project set) later. And if you use Bookmark+ then bookmarking a Dired buffer records (a) its ls switches, (b) which files are marked, (c) which subdirectories are inserted, and (d) which (sub)directories are hidden. All of that is restored when you "jump" to the bookmark. Bookmark+ also lets you bookmark an entire tree of Dired buffers --- jumping to the bookmark restores all of the buffers in the tree.
M-x project-query-replace-regexp RET (make sure your files are saved!).
M-x rgrep RET then query-replace within each buffer. Nice because you can keep track of all occurrences, and because it let's you limit search to certain extensions.
I would like to suggest one more great tool which has not been mentioned yet, namely Helm.
It is a great replacement for many standard Emacs operations involving completion, searching etc. In particular, helm-find-files allows for performing query replace (including regexp) within multiple selected files.
Just open helm-find-files, mark the relevant files with M-SPC and then use F6 or F7 to run query replace or query replace regexp in the selected files.
It's not Emacs, but xxdiff comes with a tool called xx-rename which will do that for multiple strings at a time (e.g. From To from to FROM TO), with interactive prompting, save backups of all the modified files, and produce a short log of changes made with context. That's what I tend to use when I do large/global renamings.