0
点赞
收藏
分享

微信扫一扫

【Emacs】利用find命令及ivy-read实现搜索项目文件

夜空一星 2022-03-19 阅读 40
emacs

要点

  • find [搜索路径] [要跳过搜索的东西] -prune -o [其它筛选条件] [要执行的操作]
    find ./ -path "*/.git" -prune -o -type f,d -name "*.*" -print
  • -path后面要接文件路径/路径的模式串
  • path ... -prune是联合使用的, 作用是跳过这些文件
  • -type f,d 表示结果保留普通文件f和目录d
  • -name 模式串 是对指定文件名进行搜索
  • -print 是对find找到的满足条件的文件 实施的动作: 打印文件路径
  • 命令中的双引号在elisp中要进行转义才能用
  • default-directory是该进程的pwd
  • ( locate-dominating-file 起始目录 目标文件 ) : 从起始目录向上级目录的方向查找包含目标文件路径
  • ( shell-command-to-string shell命令) 将shell命令的运行结果以字符串的形式返回
  • ( split-string 待分割串 分隔符 ) 返回切分后形成的字符串**list**
  • ( ivy-read 提示符 候选list ) 获取用户输入或在候选中的一项
  • (find-file 文件路径) 打开文件
  • (file-exists-p 路径) 判断文件路径是否合法

(require 'ivy)

;;;;;;;;;;;;;;;;;;;;;;;;;;原始版本;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun my-find-files()
  (interactive) ;; 站在巨人的肩膀上写程序!
  (let* ((cmd "find ./  -path \"*/.git\" -prune -o -type f,d  -name \"*.*\"  -print ") ;; -type d/f
         (default-directory  (locate-dominating-file "." ".git" ) )
         (output (shell-command-to-string cmd))
         (lines (split-string output "[\n\r]+" )) ;; \n or \r
         )
    (message "cmd: %s" cmd)
;;  (message "output:\n%s" output)
;;  (message "lines:\n%s" lines)   ;; return a list
    (setq selected-line (ivy-read (format "choose the file[%s]: " default-directory ) lines))
    (message ">> %s" selected-line) ;; echo the filename
    (when (and selected-line (file-exists-p selected-line )) ;;Make sure the file exists
      (find-file selected-line) ;; open selected file.
      )
    )
  )
  
;;;;;;;;;;;;;;;;;;;;;;;;;;;;以下均是重构后的版本V2;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun my-find-files-helper(start-dir)
  (interactive)  
  (let* ((cmd "find ./ -type f,d -path \"*/.git\" -prune -o -print  -name \"*.*\"  ") ;; -type d/f
         (default-directory  start-dir )
         (output (shell-command-to-string cmd))
         (lines (split-string output "[\n\r]+" )) ;; \n or \r
         )
    (message "cmd: %s" cmd)
;;  (message "output:\n%s" output)
;;    (message "lines:\n%s" lines)   ;; return a list
    (setq selected-line (ivy-read (format "choose the file[%s]: " default-directory ) lines))
    (message ">> %s" selected-line) ;; echo the filename
    (when (and selected-line (file-exists-p selected-line )) ;;Make sure the file exists
      (find-file selected-line) ;; open selected file.
      )
    )
  )
;;;;;;;;;;;;;; 

(defun my-find-files-in-project()
  (interactive)
  (my-find-files-helper (locate-dominating-file "." ".git" ))
  )
  
;;;;;;;;;;;;;;;;; 
(defun my-find-files-in-level(&optional level)
  (interactive "P") ;; 此处务必区分P和p!! 必须用P才能表示出“空nil”语义;而用p则将未输入对应nil转换为1
  (unless level
    (setq level 0))
  (setq i 0)
  (setq start-dir default-directory )
  (while (< i level)
    (setq start-dir (file-name-directory    (directory-file-name start-dir) ))
    (setq i (+ i 1) )
    )
  (my-find-files-helper start-dir)
  )
举报

相关推荐

0 条评论