in Emacs, how to enable automatic hiding of dired details? - emacs

I use a library called dired-details and dired-details+ to simplify dired's display, such that a line like this:
-rw-r--r--# 1 peter staff 22571 Apr 15 16:05 foo.txt
displays like this:
foo.txt
However, I have another function, which places all directories at the top of the list:
(defun mydired-sort ()
"Sort dired listings with directories first."
(save-excursion
(let (buffer-read-only)
(forward-line 2) ;; beyond dir. header
(sort-regexp-fields t "^.*$" "[ ]*." (point) (point-max)))
(set-buffer-modified-p nil)))
(defadvice dired-readin
(after dired-after-updating-hook first () activate)
"Sort dired listings with directories first before adding marks."
(mydired-sort))
and this second function interferes with dired-details, such that when I C-x d to open a dired buffer, the initial display shows the full extraneous details. Only by pressing g to revert-buffer to refresh the display do the directory details become hidden.
How do I enable hiding of dired details by default in all dired displays?

First, if you use Emacs 24.4 or later (or a developement version past 24.3), then you no longer need either dired-details.el or dired-details+.el. Starting with Emacs 24.4, Dired listing details are hidden by default. dired-hide-details-mode is the relevant mode.
If you use dired+.el (Dired+) then you can more easily take advantage of this new behavior -- it gives you all of the features offered by dired-details+.el. Use ( anytime to toggle this hiding. You can use Dired+ option
diredp-hide-details-initially-flag to change the default/initial state. See also option diredp-hide-details-propagate-flag.
If you use an Emacs version that is prior to Emacs 24.4 (so you need dired-details[+].el) then try loading dired-details+.el (which will load dired-details.el) after you have evaluated your code above. If that does not help, then try also adding this to your defadvice body, just after (mydired-sort): (dired-details-hide). If that does not work then we will need to look a bit further.
If you can upgrade your Emacs version then you will soon be able to use Emacs 24.4 (it is in pretest now), in which case you should be able to just load dired+.el and set option diredp-hide-details-initially-flag to non-nil.
Wrt sorting directories first: Are you on MS Windows? If so, consider using libraries dired-sort-menu.el and dired-sort-menu+.el. It lets you do that and much more.
UPDATE
The problem is that dired-details caches the list of overlays it uses to hide details. It has already done its job (because of dired-after-readin-hook), before your sorting is done, and that changes the buffer without updating the cache info. This will fix the problem (there is probably a more elegant way, but this will do):
(defadvice dired-readin
(after dired-after-updating-hook first () activate)
"Sort dired listings with directories first before adding marks."
(mydired-sort)
(let ((dired-details-internal-overlay-list ())) (dired-details-hide)))

Related

Emacs: what are good tactics for navigating directories and opening files?

Last week, infuriated (again) by having to cope with different IDEs for R and Perl, neither of which I like or use enough to get really comfortable in, I decided to try Emacs. This decision was not made without a certain trepidation on my part. My main use is for Perl with cperl and for R with ESS. My environment is Windows 7 Ultimate 64-bit and I am running v23.4.1, which I think is what the ESS package installed on my behalf.
Nearly a week in and so far it has been surprisingly painless, no more involved than any other significant piece of software. I have remapped my ctrl key to caps-lock, changed default folders, messed around with .emacs and made some additions such as auto-install, yasnippet, color-theme, icicles and a few others. Clearly there is some very sophisticated stuff out there. In addition of course certain features of base Emacs are immediately very powerful and useful, such as isearching up and down. On the whole I have been pleasantly surprised and reassured.
One thing that is cruder than I was expecting is the process of finding and opening files. After a cursory read of various tutorials I had this image of quasi-magical file location and filename auto-completion. The main directories in my setup have paths like g:/roaming/code/perl or g:/roaming/code/R/ but I often need to branch into completely different paths like g:/pricedata/support files/sector/project01/ and so on.
Currently I laboriously delete the file path when I need to take a different fork, then use auto-complete to move deeper into that branch of the filesystem. It kinda takes me back to running a bash shell on the Amiga twenty years ago.
What had I expected? Something like (using the above example) typing 'project01' to skip immediately into the folder at the bottom of the path. For some reason I had got the idea in my head that Emacs would preload directories. So maybe this wasn't realistic.
My guess is that my difficulties probably stem from my own lack of familiarity rather than a structural shortcoming in Emacs and leads on to my questions. I can't complain that there is not enough documentation; rather there is abundant information that it is scattered around rather haphazardly. Icicles has a similar problem - if anything there's too much.
1) What is the best tactic for moving around different branches of the file tree when trying to open files in the minibuffer or using some other method? Are there aliases that can be used to shortcut from one place to another or can one specify directories to be preloaded? Do people just cd around a lot? Or am I coming at this from completely the wrong angle and need to adopt a different strategy?
2) With additional setup, can auto-complete be used to find files in (say) the project01 directly above by prefixing with wildcards etc? What should I focus on to become more efficient here? Am I not tapping the power of add-ons like icicles, anything etc?
I realise these questions veer dangerously close the deprecated category of not having clear answers. My defence is that some tips/guidance at this stage before I commit myself to bad habits or a poor long-term solution would be welcome and I suspect the answers will benefit others who might be considering the switch. I am happy to withdraw or rephrase if there are problems.
helm (formerly known as anything) might suit you. You can install it manually, or using a auto-install extension.
For the auto-install way: download it, put in Your load-path, then add to .emacs:
(add-to-list 'load-path "~/.emacs.d/site-lisp/auto-install")
(require 'auto-install)
(setq auto-install-directory "~/.emacs.d/site-lisp/auto-install/")
Then do M-x auto-install-batch anything. After that is done, put in .emacs:
(require 'anything)
(require 'anything-match-plugin)
(require 'anything-config)
(require 'anything-show-completion)
Then do M-x anything for anything.
Also give a try to ECB (stands for Emacs Code Browser). If you're on Linux, you probably have it available in a standard repository.
You could benefit from using ido-mode, which greatly enhances autocompletion nearly everywhere in emacs (especially when finding files or buffers)
(setq ido-enable-flex-matching t
ido-auto-merge-work-directories-length -1
ido-create-new-buffer 'always
ido-use-filename-at-point 'guess
ido-everywhere t
ido-default-buffer-method 'selected-window)
(ido-mode 1)
(put 'ido-exit-minibuffer 'disabled nil)
(when (require 'ido-ubiquitous nil t)
(ido-ubiquitous-mode 1))
While this might help you quickly finding files "not far away", it probably won't help you much finding files in entirely different locations.
If find that one way to begin tackling this problem is using recentf-mode to quickly jump to recent locations (if you have only a small number of usual project directories, this might do the trick). recentf can be coupled with ido using something like this (I'm not sure where I got this snippet from):
(recentf-mode 1)
(setq recentf-max-saved-items 50)
(defun ido-recentf-open ()
"Use `ido-completing-read' to \\[find-file] a recent file"
(interactive)
(if (find-file (ido-completing-read "Find recent file: " recentf-list))
(message "Opening file...")
(message "Aborting")))
(global-set-key (kbd "C-x C-r") 'ido-recentf-open)
With this, you can use C-x C-f (ido-find-file) to look for files near you current location, and C-x C-r (ido-recentf-open) to look for recently opened files (hoping one of them is not too far away from where you want to go).
There are various approaches. File name cache is a built in solution. Opening files from recent files is also very effective, especially if you set the stored files to a high number (e.g. 1000). There are also packages for opening files from anywhere on the file system. And there are meta solutions like anything.el which can show you file completions from multiple sources (history, project files, etc.) in a common interface.
You should investigate the different options to find out which is the most suitable for you.
In addition to IDO and recetf you can use the following methods:
Open the directory recursively.
(defun op-i:dired (rec)
"customized dired: will display directory recursively when called with an argument"
(interactive "P")
(let ((dir (car (find-file-read-args "Dired: " nil)))
(opts (if rec (read-string "options: " "-lhAR") "-lhA")))
(if (file-directory-p dir) (dired dir opts))))
(define-key (current-global-map) (kbd "C-x C-d") 'op-i:dired)
Then you can navigate in the directory buffer as in any other buffer using a (wildcard) search.
Use Emacs registers to point to often used directories. You can initialize them in your .emacs
(set-register ?0 (cons 'file "c:/path/to/my-project0"))
(set-register ?1 (cons 'file "c:/path/to/my-project1"))
Then jump to register using C-x r j
Other people have already mentioned anything, suffice it to say, I believe it solves all your problems. :)
Calling out one specific feature of anything is anything-locate. On *nix systems, this uses the DB created by the locate command to quickly find files. On Windows, I believe it works with "Everything", which should give you near instantaneous search results across all your files. I mean all.
Tom has mentioned file-cache. Anything works with that.
Just as a side note, Dired is an absolute monster once you get used to it. You should read the emacswiki pages related to it. In particular dired-x, which comes with Emacs binds C-x C-j, jumps to current buffer in Dired was a revelation for me. Also dired-find, wdired.
Edit: some details on why C-x C-j is awesome.
When you pop the current buffer in a Dired buffer, you can modify it, i.e. rename, delete, etc. And Emacs is aware of what you've done, and adjusts accordingly.
Other possibilities:
Bookmarks. If you use Bookmark+ then you can also:
Bookmark Dired buffers, which remembers their inserted subdirs, their markings, and their file omissions. You can have a bookmark that opens Dired to a specific set of files that need not be in the same directory or even the same directory tree.
From Dired you can hit a key to create a separate bookmark to each marked file or subdir.
Bookmark files automatically (autofiles).
Tag bookmarks and files (autofile bookmarks) with arbitrary-text tags. (Tags can even be non-text Lisp objects). Use tags to organize, search, etc. different categories of bookmarks.
Bookmark sets of bookmarks or bookmark files or Emacs desktops. Jump to such a bookmark to restore a given project state/context.
Icicles.
Define temporary or persistent sets of files on the fly, even from different directories. Operate on the files in a set in various ways. (Use Emacs filesets, less powerful, the same way.)
Complete against file names from such saved sets during any completion command, not just file-finding.
Act in different ways on candidate files during completion.
Search bookmarked objects or saved sets of files or buffers.
Dired+.
Additional navigation, including i bouncing between a subdirectory listing and the subdirectory's line in the parent listing.
Refs:
http://www.emacswiki.org/cgi-bin/wiki/BookmarkPlus
http://www.emacswiki.org/emacs/Icicles_-_Support_for_Projects
http://www.emacswiki.org/emacs/Icicles_-_File-Name_Input
http://www.emacswiki.org/cgi-bin/wiki/DiredPlus

How to make emacs stay in the current directory

When I start working on a project in emacs, I use M-x cd to get into the project root directory. But every time I use C-x C-f to open a file in one of the subdirectories (like app/model/Store.rb) emacs changes current directory to that of the file. Is there a way to make emacs stay at the root?
How about this? It replaces the regular find-file command with your own which always starts in some "root" directory (customize the find-file-root-dir variable):
(defvar find-file-root-dir "~/"
"Directory from which to start all find-file's")
(defun find-file-in-root ()
"Make find-file always start at some root directory."
(interactive)
(let ((default-directory find-file-root-dir))
(call-interactively 'find-file)))
(global-set-key (kbd "C-x C-f") 'find-file-in-root)
Assuming that you want the working directory of a file to be set to whatever the working directory was before you executed find-file, you could try the following:
(defmacro disallow-cd-in-function (fun)
"Prevent FUN (or any function that FUN calls) from changing directory."
`(defadvice ,fun (around dissallow-cd activate)
(let ((old-dir default-directory) ; Save old directory
(new-buf ad-do-it)) ; Capture new buffer
;; If FUN returns a buffer, operate in that buffer in addition
;; to current one.
(when (bufferp new-buf)
(set-buffer new-buf)
(setq default-directory old-dir))
;; Set default-directory in the current buffer
(setq default-directory old-dir))))
Armed with this macro, go search for operations that set the variable default-directory: M-x find-library files; M-x occur (setq default-directory. After some investigation, you discover that the desired function is called find-file-noselect-1. Also, it looks like set-visited-file-name is also a candidate. So:
(disallow-cd-in-function find-file-noselect-1)
(disallow-cd-in-function set-visited-file-name)
Note
Note that (disallow-cd-in-function find-file) would work just fine, but then if you switched to ido-mode, you'd be opening files with ido-find-file instead of find-file. Both of these functions ultimately use find-file-noselect-1, so hitting that with the macro is a more univeral solution.
Is there a way to make emacs stay at the root?
No, there isn't. C-x C-f always visits starting from the default directory of the buffer you are already vising. The default directory, by default, is the same directory as the file. You can change these (separately for every buffer) using M-x cd.
But that is not what you want. What you should do is C-x b to *scratch* (whose default directory is the same as where you launched Emacs from -- in your words "root"), and then visit a new file. And if you need to do this frequently, just open up a dired in there and work your way thru.
I appreciate I'm not answering your question directly, but I noticed you were more specific in your requirements in one of your comments: "I don't use compile or recompile, I just tend to close files I am not working on, since it takes fewer keystrokes to open a file again".
Have you got ido turned on for buffer switching? If you exclude the directory thing for a moment, switching files or buffers with ido is an identical number of keystrokes (C-x C-f vs C-x b, followed by a few characters in the file name). If you include the directory thing, switching files is more tricky for the precisely the reasons you mention. Sticking with buffers is much easier.
Going a step further, with the help of 'anything.el' it's quite easy to abstract away whether a given file is in a buffer or in a file using the file cache. For example, if you do the following:
(file-cache-add-directory-recursively "/my/ruby/project") ".*\\.rb$")
and run 'anything-for-files' (I have it bound to C-x f) all your open buffers are listed, along with all of the files you've just added to the file cache; isolating a given file usually only takes one or two more characters.
Any file in your project is thus 4 or 5 key presses away, and the directory they are in or whether or not they are in a buffer becomes irrelevant.
Hope that's helpful...
Sorry I haven't worked out the details, but you might be able to add a function to find-file-hook that resets the default directory to whatever you want.

Don't show uninteresting files in Emacs completion window

How do I prevent Emacs from showing me all the files I'm not interested in (such as ~ backup files, .pyc files, or .orig files) when I: C-x C-f TAB ?
It is working in one respect: if I know the file I want to open begins with foo and I type foo TAB then the mini-buffer correctly autocompletes all the way to foo.py. It correctly ignored foo~ and foo.pyc, because both ~ and .pyc are in completion-ignored-extensions. It also correctly lets me open either ignored file if I really want to by typing in all the letters my self.
However, if I just hit TAB to to bring up the completion list buffer then that list includes files with extensions in completion-ignored-extensions, which makes it very difficult to find what I'm looking for.
Clearly the code to ignore uninteresting files is there and working. How do I get the completion list buffer to respect completion-ignored-extensions?
(by-the-by, can I make dired behave similarly?)
This piece of advice filters out files with extensions listed in 'completion-ignored-extensions:
(defadvice completion--file-name-table (after
ignoring-backups-f-n-completion
activate)
"Filter out results when they match `completion-ignored-extensions'."
(let ((res ad-return-value))
(if (and (listp res)
(stringp (car res))
(cdr res)) ; length > 1, don't ignore sole match
(setq ad-return-value
(completion-pcm--filename-try-filter res)))))
Note: This doesn't affect dired.
For the dired issue, add this to your .emacs
(eval-after-load "dired"
'(require 'dired-x))
(add-hook 'dired-mode-hook
(lambda ()
(dired-omit-mode 1)))
Read the documentation for dired-x to get an idea of what's available there.
I would recommend using ido-mode to ignore files; it comes with Emacs by default and adds many other useful enhancements that you'll quickly learn to love. The Ignorance is Bliss section from this Mastering Emacs blog post covers how to ignore files, directories, and buffers:
ido-ignore-buffers Takes a list of buffers to ignore in C-x b
ido-ignore-directories Takes a list of directories to ignore in C-x d and C-x C-f
ido-ignore-files Takes a list of files to ignore in C-x C-f
Icicles does what you expect by default. It always respects completion-ignored-extensions for file-name completion, including for buffer *Completions*. And you can toggle this ignoring on/off at anytime, by hitting C-. in the minibuffer.
In addition, if you use library completion-ignored-build.el by Kevin Ryde, then Icicles automatically takes advantage of that library's dynamic adjustment of ignored file extensions. (Just load completion-ignored-build.el -- do not enable its minor mode or advice.)
I don't know of an answer for completion, I'm afraid. I think this is by design - when you know the name you're looking for, you probably don't want e.g. the backup file. But when you don't know, it's probably better to have a list of all of the files.
However, for dired, you can load the 'dired-x' package on startup (in your .emacs), and this provides dired-omit-mode:
(load "dired-x")
You can use 'M-x customize-variable<RET>dired-omit-files' to set the actual patterns to ignore. Then when you are in dired mode you can use M-O (the letter, not the number) to toggle 'omission' on and off.

Can I change Emacs find-file history?

When I call find-file to open a new file, it generally happens that the file I'm looking for is in one of the directories I've already loaded from.
Ideally, I'd like to scroll through the history using the up/down arrows.
The problem with this is that if I've already loaded 10 files from a directory, I first have to pass through those ten files, all in the same directory, before I see a new directory where my file might be.
In the end, I often just type in the directory again or cut/paste it from an xterm.
in the find-file command, can I change the behavior of the up/down arrows to iterate over directories instead of files.
Alternatively, can I change the file order to match the order of buffers most recently visited instead of when I loaded the file?
My first answer suffered from the behavior that TAB completion no longer worked as expected in 'find-file. But the technique still seems useful (and if you like it, preferable).
However, this solution has the same history behavior, but maintains the TAB completion as expected inside 'find-file.
I'd be interested to know if there were a way to avoid advising find-file, but I couldn't find any introspection that gave me the knowledge that 'find-file was called.
(defadvice find-file (around find-file-set-trigger-variable protect activate)
"bind a variable so that history command can do special behavior for find-file"
(interactive (let (inside-find-file-command) (find-file-read-args "Find file: " nil)))
ad-do-it)
(defadvice next-history-element (around next-history-element-special-behavior-for-find-file protect activate)
"when doing history for find-file, use the buffer-list as history"
(if (boundp 'inside-find-file-command)
(let ((find-file-history (delq nil (mapcar 'buffer-file-name (buffer-list))))
(minibuffer-history-variable 'find-file-history))
ad-do-it)
ad-do-it))
I suggest IDO. You can search in the buffer list or in find-file. When searching in find-file and it has no matches in the current folder it searches through history.
not what you want, but
have you tried (electric-buffer-list) Ctrl-x Ctrl-b?
or (dired)?
This will use the buffer-list's order for the history, which is what you want.
(setq read-file-name-function 'my-read-file-name)
(defun my-read-file-name (prompt dir default-filename mustmatch initial predicate)
(let ((default-directory dir)
(files (directory-files dir))
(history (delq nil (mapcar 'buffer-file-name (buffer-list)))))
(completing-read prompt files predicate mustmatch initial 'history)))
Hmmm... This changes the behavior of find-file's TAB completion because the TAB completes over the history (already opened files), and not over the files available in the directory you're specifying.
Getting both to work at the same time is a bit trickier...
With Icicles you can cycle among candidate file names, and you can sort them in many ways. You can access them in order of last use etc.
http://www.emacswiki.org/emacs/Icicles_-_History_Enhancements
http://www.emacswiki.org/emacs/Icicles_-_Sorting_Candidates
http://www.emacswiki.org/emacs/Icicles_-_File-Name_Input

How do I get list of recent files in GNU Emacs?

When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows)
From Joe Grossberg's blog (no longer available):
But if you're using GNU Emacs 21.2
(the latest version, which includes
this as part of the standard distro),
you can just put the following lines
into your .emacs file
;; recentf stuff
(require 'recentf)
(recentf-mode 1)
(setq recentf-max-menu-items 25)
(global-set-key "\C-x\ \C-r" 'recentf-open-files)
Then, when you launch emacs, hit
CTRL-X CTRL-R. It will show a list of
the recently-opened files in a buffer.
Move the cursor to a line and press
ENTER. That will open the file in
question, and move it to the top of
your recent-file list.
(Note: Emacs records file names.
Therefore, if you move or rename a
file outside of Emacs, it won't
automatically update the list. You'll
have to open the renamed file with the
normal CTRL-X CTRL-F method.)
Jayakrishnan Varnam has a page
including screenshots of how this
package works.
Note: You don't need the (require 'recentf) line.
Even if you don't have recentf turned on, Emacs is saving a list of files entered via the minibuffer in the variable file-name-history. Also, executing (savehist-mode 1) in your .emacs file makes that variable persist across invocations of Emacs.
So here's a little function that displays the files that actually exist from that list (anyone is welcome to use/build on this):
(defun dir-of-recent-files ()
"See the list of recently entered files in a Dired buffer."
(interactive)
(dired (cons
"*Recent Files*"
(seq-filter
'file-exists-p
(delete-dups
(mapcar (lambda (s) (string-trim-right s "/*"))
file-name-history)
))))
)
I find this quite useful and have it bound to one of those little special function keys on my desktop keyboard. (And so I have not seen the point of turning on recentf...)