Distinguishing files with extensions, from hidden

2019-01-15 23:12发布

问题:

I'm having difficulty distinguishing files with extensions, from files without extensions, and hidden files. I'm using (file-name-extension (dired-get-file-for-visit)) in dired-mode, and the type of file extension determines what action to take -- e.g., open in Emacs, or open externally with a particular application.

A hidden file (e.g., .hidden) returns a value of nil instead of "hidden".

A file with no extension (e.g., foo) also returns a value of nil.

Can anyone suggest an alternative method to handle this?

(let* (
    (input-regexp '("odt" "wpd" "docx" "doc" "xls" "pdf" "tif" "bmp" "jpg"))
    (input-filename (dired-get-file-for-visit)) )
  (if (not (regexp-match-p input-regexp (file-name-extension input-filename))))
    (find-file input-filename) )

;; https://github.com/kentaro/auto-save-buffers-enhanced
(defun regexp-match-p (regexps string)
  (catch 'matched
    (dolist (regexp regexps)
      (if (string-match regexp string)
        (throw 'matched t)))))

Here is the debugger (partial):

Debugger entered--Lisp error: (wrong-type-argument stringp nil)
  string-match("odt" nil)
  (if (string-match regexp string) (throw (quote matched) t))
  (while --dolist-tail-- (setq regexp (car --dolist-tail--)) (if (string-match regexp string) (throw (quote matched) t)) (setq --dolist-tail-- (cdr --dolist-tail--)))
  (let ((--dolist-tail-- regexps) regexp) (while --dolist-tail-- (setq regexp (car --dolist-tail--)) (if (string-match regexp string) (throw (quote matched) t)) (setq --dolist-tail-- (cdr --dolist-tail--))))
  (progn (let ((--dolist-tail-- regexps) regexp) (while --dolist-tail-- (setq regexp (car --dolist-tail--)) (if (string-match regexp string) (throw (quote matched) t)) (setq --dolist-tail-- (cdr --dolist-tail--)))))
  (catch (quote matched) (progn (let ((--dolist-tail-- regexps) regexp) (while --dolist-tail-- (setq regexp (car --dolist-tail--)) (if (string-match regexp string) (throw (quote matched) t)) (setq --dolist-tail-- (cdr --dolist-tail--))))))
  regexp-match-p(("odt" "wpd" "docx" "doc" "xls" "pdf" "tif" "bmp" "jpg") nil)
  (not (regexp-match-p input-regexp (file-name-extension input-filename)))
***

回答1:

How about

(let* ((input-regexp '("odt" "wpd" "docx" "doc" "xls" "pdf" "tif" "bmp" "jpg"))
       (input-filename (dired-get-file-for-visit))
       (ext (file-name-extension input-filename)))
  (unless (and ext (regexp-match-p input-regexp ext))
    (find-file input-filename)))

Alternatively, redefine

(defun regexp-match-p (regexps string)
  (and string
       (catch 'matched
         (let ((inhibit-changing-match-data t)) ; small optimization
           (dolist (regexp regexps)
             (when (string-match regexp string)
               (throw 'matched t)))))))