Search code examples
emacsautocompletecode-completion

Is there a way to automatically add a whitespace upon completion in company-mode?


I use company-mode a lot on natural language completion with the local dictionary. I am wondering if there is a way to automatically add a whitespace upon completion.

For example, currently when I type abili and select the first candidate ability, my insert point is right after y|. Is there a way that the company-mode can add a space so my insert point is after y |?

I could not find any related information on this but this issue mentioned a space is added after completion in the Eshell mode. Apparently this is exactly what I want.

The issue mentioned the function completion-at-point. Is there a way that I can change or have a function that I can override the current completion mechanism?

Thanks! I’d really appreciate any suggestions.


Solution

  • You could add a hook to company-after-completion-hook that would be called after completion with any of your company backends, eg.

    (defun my-company-after-completion-hook (&rest _ignored)
      ;; this would be called with the completion candidate, so you could
      ;; modify it to insert spaces based on the candidate
      (just-one-space))
    
    ;; or setq-local in a mode hook, eg. for text-mode/org-mode or wherever you are
    ;; completing with dictionary words 
    (setq company-after-completion-hook #'my-company-after-completion-hook)
    

    If you only wanted to add space after completing with a specific backend you could see if the backend already implements a post-completion action, otherwise you could probably advise it.