I would like to have natural language completion (
company-ispell for e.g.) but only when editing comments.
How should the company back-end be swapped out when editing commensts?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.Sign up to join this community
Insert below code into
~/.emacs to enable
company-ispell in comment,
(defun my-in-comment-p (pos) "Check whether the code at POS is comment by comparing font face." (let* ((fontfaces (get-text-property pos 'face))) (if (not (listp fontfaces)) (setq fontfaces (list fontfaces))) (delq nil (mapcar #'(lambda (f) ;; learn this trick from flyspell (or (eq f 'font-lock-comment-face) (eq f 'font-lock-comment-delimiter-face))) fontfaces)))) (eval-after-load 'company-ispell '(progn ;; use company-ispell in comment when coding (defadvice company-ispell-available (around company-ispell-available-hack activate) (cond ((and (derived-mode-p 'prog-mode) (or (not (company-in-string-or-comment)) ; respect advice in `company-in-string-or-comment' (not (my-in-comment-p (point))))) ; auto-complete in comment only (setq ad-return-value nil)) (t ad-do-it)))))
This is a modified version of @chen-bin's answer which uses a wrapper function instead of using advice (avoids interfering with other uses). It also generalizes the syntax checking to allow checking for other kinds of syntax.
(defun company-complete-common-use-context () (interactive) (let ((faces-found (face-at-point nil t)) (faces-comment-list '(font-lock-comment-face font-lock-comment-delimiter-face font-lock-doc-face))) (cond ((seq-intersection faces-found faces-comment-list) (let ((company-backends (list 'company-ispell))) (company-complete-common))) (t (company-complete-common)))))
Then bind the key to