Buffer menu to select a set of filenames in Emacs

2019-05-29 02:58发布

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?

标签: emacs elisp
3条回答
女痞
2楼-- · 2019-05-29 03:30

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.

查看更多
Explosion°爆炸
3楼-- · 2019-05-29 03:46

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.

查看更多
手持菜刀,她持情操
4楼-- · 2019-05-29 03:54
  • 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.)

查看更多
登录 后发表回答