Skip to content

Commit

Permalink
ivy-completion-in-region: correctly calculate the length of replaceme…
Browse files Browse the repository at this point in the history
…nt for file category
  • Loading branch information
kiennq committed Jul 6, 2024
1 parent 2a25a6f commit 4f906b7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
8 changes: 7 additions & 1 deletion ivy-test.el
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,11 @@ Since `execute-kbd-macro' doesn't pick up a let-bound `default-directory'.")
#("test/"
0 2 (face completions-common-part)
2 3 (face (completions-first-difference))))))
(should (= 2
(ivy-completion-common-length
#("test/"
0 2 (face completions-common-part)
2 3 (face completions-first-difference)))))
(should (= 5
(ivy-completion-common-length
#("Math/E"
Expand All @@ -1020,7 +1025,8 @@ Since `execute-kbd-macro' doesn't pick up a let-bound `default-directory'.")
(should (= 3
(ivy-completion-common-length
#("vec"
0 3 (face (completions-common-part)))))))
0 3 (face (completions-common-part))))))
)

(ert-deftest ivy--sort-function ()
"Test `ivy--sort-function' behavior."
Expand Down
23 changes: 16 additions & 7 deletions ivy.el
Original file line number Diff line number Diff line change
Expand Up @@ -2649,12 +2649,19 @@ The first non-matching part is propertized:
(i (1- (length str))))
(catch 'done
(while (>= i 0)
(when (equal (get-text-property i 'face str)
'(completions-first-difference))
(throw 'done i))
(pcase (get-text-property i 'face str)
(`completions-first-difference (throw 'done i))
((and (pred listp) (pred (member 'completions-first-difference)))
(throw 'done i)))
(cl-decf i))
(throw 'done (length str)))))

(defun ivy--completion-prefix-offset (str md)
"Return the offset of the completion prefix in STR with its metadata MD."
(pcase (cdr (assoc 'category md))
('file (length (file-name-directory str)))
(_ 0)))

(defun ivy-completion-in-region (start end collection &optional predicate)
"An Ivy function suitable for `completion-in-region-function'.
The function completes the text between START and END using COLLECTION.
Expand All @@ -2680,14 +2687,16 @@ See `completion-in-region' for further information."
(when (eq collection 'crm--collection-fn)
(setq comps (delete-dups comps)))
(let* ((len (ivy-completion-common-length (car comps)))
(prefix-offset (ivy--completion-prefix-offset str md))
(target-str (substring str prefix-offset))
(initial (cond ((= len 0)
"")
((let ((str-len (length str)))
((let ((str-len (length target-str)))
(when (> len str-len)
(setq len str-len)
str)))
(setq len str-len)))
target-str)
(t
(substring str (- len))))))
(substring target-str (- len))))))
(delete-region (- end len) end)
(setq ivy-completion-beg (- end len))
(setq ivy-completion-end ivy-completion-beg)
Expand Down

0 comments on commit 4f906b7

Please sign in to comment.