Skip to content

Instantly share code, notes, and snippets.

@twlz0ne
Last active July 4, 2022 03:43
Show Gist options
  • Save twlz0ne/c4a35263d5bfb9406e32481bc3621218 to your computer and use it in GitHub Desktop.
Save twlz0ne/c4a35263d5bfb9406e32481bc3621218 to your computer and use it in GitHub Desktop.
Return different CANDIDATES depending on the point position #emacs #company #lsp
(defun company-transformer//capf-dabbrev (candidates)
"Return different CANDIDATES depending on the point position.
| point at | company-capf | company-dabbrev |
|:---------|:------------:|:---------------:|
| foo.| | ✅ | ❌ |
| \"foo|\" | ❌ | ✅ |
| foo| | ✅ | ✅ |
Inspired by @yyjjl's [company//sort-by-tabnine](https://emacs-china.org/t/tabnine/9988/40)
Last-Updated 2022-07-04 11:31:28 +0800"
(if-let* ((company-capf-dabbrev-p
(pcase company-backend
(`(company-capf :with company-dabbrev :separate) t)))
(trigger-chars (->> (lsp--server-capabilities)
(lsp:server-capabilities-completion-provider?)
(lsp:completion-options-trigger-characters?))))
(let ((candidates-table (make-hash-table :test #'equal))
(trigger-char-p
(when (not (nth 3 (syntax-ppss)))
(save-excursion
(goto-char (or (car (bounds-of-thing-at-point 'symbol)) (point)))
(and (lsp-completion--looking-back-trigger-characterp trigger-chars) t))))
candidates-1
candidates-2
(print-count 0))
(dolist (candidate candidates)
(when (< print-count 10)
(cl-incf print-count 1))
;; Candidates from capf
(if (get-text-property 0 'lsp-completion-item candidate)
(unless (gethash candidate candidates-table)
(push (string-trim-left candidate) candidates-1))
;; Candidates from dabbrev
(unless trigger-char-p
(push candidate candidates-2)
(puthash candidate t candidates-table))))
(setq candidates-1 (nreverse candidates-1))
(setq candidates-2 (nreverse candidates-2))
(nconc candidates-1 (unless trigger-char-p candidates-2)))
candidates))
;; Usage:
;; (with-eval-after-load 'lsp
;; (with-eval-after-load 'company
;; (add-to-list 'company-transformers #'company-transformer//capf-dabbrev)))
@twlz0ne
Copy link
Author

twlz0ne commented Jul 2, 2022

capf only:
pany-transformer-capf-dabbrev-1

dabbrev only:
pany-transformer-capf-dabbrev-2

capf + dabbrev:
pany-transformer-capf-dabbrev-3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment