swiper
搜索会有三个问题
- 超长行 (存在一些行过分多的字符)
- 大文件 (buffer 的字符数过多或者行数过多)
- 一些mode不能使用
尝试使用 counsel-grep
, counsel-grep-or-swiper
和 isearch
来解决
;; 确保counsel, ivy, swiper已经加载
(defvar my-line-length-threshold 500
"行字符数阈值,超过该值使用counsel-grep.")
(defvar my-line-count-threshold 50000
"缓冲行数阈值,超过该值直接使用counsel-grep.")
(defun buffer-has-long-line-p (&optional threshold)
"检查当前buffer是否存在超过THRESHOLD字符的行."
(let ((threshold (or threshold my-line-length-threshold))
(found nil))
(save-excursion
(goto-char (point-min))
(while (and (not found)
(re-search-forward (format "^.\\{%d\\}" threshold) nil t))
(setq found t)))
found))
(setq my-line-count-threshold 50000) ; 行数阈值
(setq my-line-length-threshold 500) ; 行长度阈值
(setq counsel-grep-swiper-limit 300000) ;字符数阈值
(defun my-smart-grep ()
"智能搜索策略:
1. 缓冲区行数超过50000时使用counsel-grep
2. 存在超过500字符的行时使用counsel-grep
3. 其他情况使用counsel-grep-or-swiper."
(interactive)
(cond
((> (count-lines (point-min) (point-max)) my-line-count-threshold)
(counsel-grep))
((buffer-has-long-line-p)
(counsel-grep))
(t
(counsel-grep-or-swiper))))
;; 绑定到C-s
(global-set-key (kbd "C-s") 'my-smart-grep)
一些mode的无法使用:pdf-view-mode等
(define-key pdf-view-mode-map (kbd "C-s") 'isearch-forward)
(define-key pdf-view-mode-map (kbd "C-r") 'isearch-backward)
这里就直接用isearch
。