Auto-focus a Relevant File in Dired Buffers25 Sep 2014, by Artur Malabarba.
Emacs.SE Lessons post series
The emacs.stackexchange beta has only just started and interesting topics have already begun to pop up. Partially to share snippets I find nifty, and partially to help promote the beta, I’ll be posting here questions and answers I find engaging.
I’m kicking off this series with a question of my own, answered by none other than Sebastian Wiesner. (Did you know he has a blog)? The beta is still private, so you might not be able to visit the links above, but I’ll summ it up here.
For a while now I’ve noticed my dired patterns are somewhat predictable.
- Whenever I visit the directory of one of my papers, I go straight to the “master.tex” file.
- When I open the root of an android project, it’s almost always to visit the the “AndroidManifest.xml”.
- Finally, when I go to a directory where I’m developing an emacs package, 80% of the time I’m headed for the package's main source file.
See the pattern? For all these directories, the first file I visit is very predictable, so I wanted dired to focus that file automatically for me. So I would only need to hit RET—lazyness to the extreme.
Sebastian looks into the
save-place package’s source code, and finds
dired-initial-position-hook, which is run exactly when we
need. Visiting a file whose name we already know is then a trivial
Note I’ve edited his code a bit.
Making dired focus the source file of elisp packages is tad bit tricker because the file’s name is not fixed. The solution I found (still borrowing some of Wiesner’s code) was to look for a file whose name matched the current directory’s name, and if it that doesn’t exist just focus any “.el” file. This works well for me because my directory structure typically looks like “~/Git/paradox/paradox.el”.