Skip to content

Instantly share code, notes, and snippets.

@amygrinn
Last active May 21, 2022 19:02
Show Gist options
  • Save amygrinn/cad98cc625056b0fd05774fa5790cc9e to your computer and use it in GitHub Desktop.
Save amygrinn/cad98cc625056b0fd05774fa5790cc9e to your computer and use it in GitHub Desktop.
Find similar file by replacing path tokens with minibuffer text
(require 'cl-lib)
(setq find-similar-file-separators '("-" "_" "/" "."))
(defvar find-similar-file--cur-file nil)
(defun find-similar-file-zip (separators tokens)
(let ((seps (cl-copy-list separators)))
(mapconcat
(lambda (token) (concat (pop seps) token))
tokens
"")))
(defun find-similar-file-collection (new pred flag)
(let* ((tokens (split-string find-similar-file--cur-file
(rx (eval (append '(or) find-similar-file-separators)))
t))
(separators (split-string find-similar-file--cur-file
(rx (one-or-more (eval (list 'not (append '(or) find-similar-file-separators)))))
t)))
(cond
((eq flag 'metadata) '(metadata (category . file)))
((eq flag 'lambda) (funcall (or pred 'file-exists-p) new))
(t
(if-let ((file (catch 'found-file
(dolist (old tokens)
(let ((file (find-similar-file-zip
separators
(cl-substitute new old tokens :test #'string=))))
(if (file-exists-p file)
(throw 'found-file file)))))))
(list file)
nil)))))
(defun find-similar-file ()
(interactive)
(let ((find-similar-file--cur-file buffer-file-name))
(funcall-interactively
'find-file
(completing-read "File: " 'find-similar-file-collection nil t))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment