Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3247 lines
128 KiB

  1. ;;; company.el --- Modular text completion framework -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2009-2020 Free Software Foundation, Inc.
  3. ;; Author: Nikolaj Schumacher
  4. ;; Maintainer: Dmitry Gutov <dgutov@yandex.ru>
  5. ;; URL: http://company-mode.github.io/
  6. ;; Version: 0.9.13
  7. ;; Keywords: abbrev, convenience, matching
  8. ;; Package-Requires: ((emacs "24.3"))
  9. ;; This file is part of GNU Emacs.
  10. ;; GNU Emacs is free software: you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation, either version 3 of the License, or
  13. ;; (at your option) any later version.
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;; GNU General Public License for more details.
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  20. ;;; Commentary:
  21. ;;
  22. ;; Company is a modular completion framework. Modules for retrieving completion
  23. ;; candidates are called backends, modules for displaying them are frontends.
  24. ;;
  25. ;; Company comes with many backends, e.g. `company-etags'. These are
  26. ;; distributed in separate files and can be used individually.
  27. ;;
  28. ;; Enable `company-mode' in all buffers with M-x global-company-mode. For
  29. ;; further information look at the documentation for `company-mode' (C-h f
  30. ;; company-mode RET).
  31. ;;
  32. ;; If you want to start a specific backend, call it interactively or use
  33. ;; `company-begin-backend'. For example:
  34. ;; M-x company-abbrev will prompt for and insert an abbrev.
  35. ;;
  36. ;; To write your own backend, look at the documentation for `company-backends'.
  37. ;; Here is a simple example completing "foo":
  38. ;;
  39. ;; (defun company-my-backend (command &optional arg &rest ignored)
  40. ;; (interactive (list 'interactive))
  41. ;; (pcase command
  42. ;; (`interactive (company-begin-backend 'company-my-backend))
  43. ;; (`prefix (company-grab-symbol))
  44. ;; (`candidates (list "foobar" "foobaz" "foobarbaz"))
  45. ;; (`meta (format "This value is named %s" arg))))
  46. ;;
  47. ;; Sometimes it is a good idea to mix several backends together, for example to
  48. ;; enrich gtags with dabbrev-code results (to emulate local variables). To do
  49. ;; this, add a list with both backends as an element in `company-backends'.
  50. ;;
  51. ;;; Change Log:
  52. ;;
  53. ;; See NEWS.md in the repository.
  54. ;;; Code:
  55. (require 'cl-lib)
  56. (require 'newcomment)
  57. (require 'pcase)
  58. ;;; Compatibility
  59. (eval-and-compile
  60. ;; Defined in Emacs 24.4
  61. (unless (fboundp 'string-suffix-p)
  62. (defun string-suffix-p (suffix string &optional ignore-case)
  63. "Return non-nil if SUFFIX is a suffix of STRING.
  64. If IGNORE-CASE is non-nil, the comparison is done without paying
  65. attention to case differences."
  66. (let ((start-pos (- (length string) (length suffix))))
  67. (and (>= start-pos 0)
  68. (eq t (compare-strings suffix nil nil
  69. string start-pos nil ignore-case)))))))
  70. (defgroup company nil
  71. "Extensible inline text completion mechanism."
  72. :group 'abbrev
  73. :group 'convenience
  74. :group 'matching)
  75. (defgroup company-faces nil
  76. "Faces used by Company."
  77. :group 'company
  78. :group 'faces)
  79. (defface company-tooltip
  80. '((default :foreground "black")
  81. (((class color) (min-colors 88) (background light))
  82. (:background "cornsilk"))
  83. (((class color) (min-colors 88) (background dark))
  84. (:background "yellow"))
  85. (t
  86. (:background "yellow")))
  87. "Face used for the tooltip.")
  88. (defface company-tooltip-selection
  89. '((((class color) (min-colors 88) (background light))
  90. (:background "light blue"))
  91. (((class color) (min-colors 88) (background dark))
  92. (:background "orange1"))
  93. (t (:background "green")))
  94. "Face used for the selection in the tooltip.")
  95. (defface company-tooltip-search
  96. '((default :inherit highlight))
  97. "Face used for the search string in the tooltip.")
  98. (defface company-tooltip-search-selection
  99. '((default :inherit highlight))
  100. "Face used for the search string inside the selection in the tooltip.")
  101. (defface company-tooltip-mouse
  102. '((default :inherit highlight))
  103. "Face used for the tooltip item under the mouse.")
  104. (defface company-tooltip-common
  105. '((((background light))
  106. :foreground "darkred")
  107. (((background dark))
  108. :foreground "red"))
  109. "Face used for the common completion in the tooltip.")
  110. (defface company-tooltip-common-selection
  111. '((default :inherit company-tooltip-common))
  112. "Face used for the selected common completion in the tooltip.")
  113. (defface company-tooltip-annotation
  114. '((((background light))
  115. :foreground "firebrick4")
  116. (((background dark))
  117. :foreground "red4"))
  118. "Face used for the completion annotation in the tooltip.")
  119. (defface company-tooltip-annotation-selection
  120. '((default :inherit company-tooltip-annotation))
  121. "Face used for the selected completion annotation in the tooltip.")
  122. (defface company-scrollbar-fg
  123. '((((background light))
  124. :background "darkred")
  125. (((background dark))
  126. :background "red"))
  127. "Face used for the tooltip scrollbar thumb.")
  128. (defface company-scrollbar-bg
  129. '((((background light))
  130. :background "wheat")
  131. (((background dark))
  132. :background "gold"))
  133. "Face used for the tooltip scrollbar background.")
  134. (defface company-preview
  135. '((((background light))
  136. :inherit (company-tooltip-selection company-tooltip))
  137. (((background dark))
  138. :background "blue4"
  139. :foreground "wheat"))
  140. "Face used for the completion preview.")
  141. (defface company-preview-common
  142. '((((background light))
  143. :inherit company-tooltip-common-selection)
  144. (((background dark))
  145. :inherit company-preview
  146. :foreground "red"))
  147. "Face used for the common part of the completion preview.")
  148. (defface company-preview-search
  149. '((((background light))
  150. :inherit company-tooltip-common-selection)
  151. (((background dark))
  152. :inherit company-preview
  153. :background "blue1"))
  154. "Face used for the search string in the completion preview.")
  155. (defface company-echo nil
  156. "Face used for completions in the echo area.")
  157. (defface company-echo-common
  158. '((((background dark)) (:foreground "firebrick1"))
  159. (((background light)) (:background "firebrick4")))
  160. "Face used for the common part of completions in the echo area.")
  161. ;; Too lazy to re-add :group to all defcustoms down below.
  162. (setcdr (assoc load-file-name custom-current-group-alist)
  163. 'company)
  164. (defun company-frontends-set (variable value)
  165. ;; Uniquify.
  166. (let ((value (delete-dups (copy-sequence value))))
  167. (and (or (and (memq 'company-pseudo-tooltip-unless-just-one-frontend value)
  168. (memq 'company-pseudo-tooltip-frontend value))
  169. (and (memq 'company-pseudo-tooltip-unless-just-one-frontend-with-delay value)
  170. (memq 'company-pseudo-tooltip-frontend value))
  171. (and (memq 'company-pseudo-tooltip-unless-just-one-frontend-with-delay value)
  172. (memq 'company-pseudo-tooltip-unless-just-one-frontend value)))
  173. (user-error "Pseudo tooltip frontend cannot be used more than once"))
  174. (and (or (and (memq 'company-preview-if-just-one-frontend value)
  175. (memq 'company-preview-frontend value))
  176. (and (memq 'company-preview-if-just-one-frontend value)
  177. (memq 'company-preview-common-frontend value))
  178. (and (memq 'company-preview-frontend value)
  179. (memq 'company-preview-common-frontend value))
  180. )
  181. (user-error "Preview frontend cannot be used twice"))
  182. (and (memq 'company-echo value)
  183. (memq 'company-echo-metadata-frontend value)
  184. (user-error "Echo area cannot be used twice"))
  185. ;; Preview must come last.
  186. (dolist (f '(company-preview-if-just-one-frontend company-preview-frontend company-preview-common-frontend))
  187. (when (cdr (memq f value))
  188. (setq value (append (delq f value) (list f)))))
  189. (set variable value)))
  190. (defcustom company-frontends '(company-pseudo-tooltip-unless-just-one-frontend
  191. company-preview-if-just-one-frontend
  192. company-echo-metadata-frontend)
  193. "The list of active frontends (visualizations).
  194. Each frontend is a function that takes one argument. It is called with
  195. one of the following arguments:
  196. `show': When the visualization should start.
  197. `hide': When the visualization should end.
  198. `update': When the data has been updated.
  199. `pre-command': Before every command that is executed while the
  200. visualization is active.
  201. `post-command': After every command that is executed while the
  202. visualization is active.
  203. The visualized data is stored in `company-prefix', `company-candidates',
  204. `company-common', `company-selection', `company-point' and
  205. `company-search-string'."
  206. :set 'company-frontends-set
  207. :type '(repeat (choice (const :tag "echo" company-echo-frontend)
  208. (const :tag "echo, strip common"
  209. company-echo-strip-common-frontend)
  210. (const :tag "show echo meta-data in echo"
  211. company-echo-metadata-frontend)
  212. (const :tag "pseudo tooltip"
  213. company-pseudo-tooltip-frontend)
  214. (const :tag "pseudo tooltip, multiple only"
  215. company-pseudo-tooltip-unless-just-one-frontend)
  216. (const :tag "pseudo tooltip, multiple only, delayed"
  217. company-pseudo-tooltip-unless-just-one-frontend-with-delay)
  218. (const :tag "preview" company-preview-frontend)
  219. (const :tag "preview, unique only"
  220. company-preview-if-just-one-frontend)
  221. (const :tag "preview, common"
  222. company-preview-common-frontend)
  223. (function :tag "custom function" nil))))
  224. (defcustom company-tooltip-limit 10
  225. "The maximum number of candidates in the tooltip."
  226. :type 'integer)
  227. (defcustom company-tooltip-minimum 6
  228. "The minimum height of the tooltip.
  229. If this many lines are not available, prefer to display the tooltip above."
  230. :type 'integer)
  231. (defcustom company-tooltip-minimum-width 0
  232. "The minimum width of the tooltip's inner area.
  233. This doesn't include the margins and the scroll bar."
  234. :type 'integer
  235. :package-version '(company . "0.8.0"))
  236. (defcustom company-tooltip-maximum-width most-positive-fixnum
  237. "The maximum width of the tooltip's inner area.
  238. This doesn't include the margins and the scroll bar."
  239. :type 'integer
  240. :package-version '(company . "0.9.5"))
  241. (defcustom company-tooltip-margin 1
  242. "Width of margin columns to show around the toolip."
  243. :type 'integer)
  244. (defcustom company-tooltip-offset-display 'scrollbar
  245. "Method using which the tooltip displays scrolling position.
  246. `scrollbar' means draw a scrollbar to the right of the items.
  247. `lines' means wrap items in lines with \"before\" and \"after\" counters."
  248. :type '(choice (const :tag "Scrollbar" scrollbar)
  249. (const :tag "Two lines" lines)))
  250. (defcustom company-tooltip-align-annotations nil
  251. "When non-nil, align annotations to the right tooltip border."
  252. :type 'boolean
  253. :package-version '(company . "0.7.1"))
  254. (defcustom company-tooltip-flip-when-above nil
  255. "Whether to flip the tooltip when it's above the current line."
  256. :type 'boolean
  257. :package-version '(company . "0.8.1"))
  258. (defvar company-safe-backends
  259. '((company-abbrev . "Abbrev")
  260. (company-bbdb . "BBDB")
  261. (company-capf . "completion-at-point-functions")
  262. (company-clang . "Clang")
  263. (company-cmake . "CMake")
  264. (company-css . "CSS")
  265. (company-dabbrev . "dabbrev for plain text")
  266. (company-dabbrev-code . "dabbrev for code")
  267. (company-eclim . "Eclim (an Eclipse interface)")
  268. (company-elisp . "Emacs Lisp")
  269. (company-etags . "etags")
  270. (company-files . "Files")
  271. (company-gtags . "GNU Global")
  272. (company-ispell . "Ispell")
  273. (company-keywords . "Programming language keywords")
  274. (company-nxml . "nxml")
  275. (company-oddmuse . "Oddmuse")
  276. (company-semantic . "Semantic")
  277. (company-tempo . "Tempo templates")
  278. (company-xcode . "Xcode")))
  279. (put 'company-safe-backends 'risky-local-variable t)
  280. (defun company-safe-backends-p (backends)
  281. (and (consp backends)
  282. (not (cl-dolist (backend backends)
  283. (unless (if (consp backend)
  284. (company-safe-backends-p backend)
  285. (assq backend company-safe-backends))
  286. (cl-return t))))))
  287. (defcustom company-backends `(,@(unless (version< "24.3.51" emacs-version)
  288. (list 'company-elisp))
  289. company-bbdb
  290. ,@(unless (version<= "26" emacs-version)
  291. (list 'company-nxml))
  292. ,@(unless (version<= "26" emacs-version)
  293. (list 'company-css))
  294. company-eclim company-semantic company-clang
  295. company-xcode company-cmake
  296. company-capf
  297. company-files
  298. (company-dabbrev-code company-gtags company-etags
  299. company-keywords)
  300. company-oddmuse company-dabbrev)
  301. "The list of active backends (completion engines).
  302. Only one backend is used at a time. The choice depends on the order of
  303. the items in this list, and on the values they return in response to the
  304. `prefix' command (see below). But a backend can also be a \"grouped\"
  305. one (see below).
  306. `company-begin-backend' can be used to start a specific backend,
  307. `company-other-backend' will skip to the next matching backend in the list.
  308. Each backend is a function that takes a variable number of arguments.
  309. The first argument is the command requested from the backend. It is one
  310. of the following:
  311. `prefix': The backend should return the text to be completed. It must be
  312. text immediately before point. Returning nil from this command passes
  313. control to the next backend. The function should return `stop' if it
  314. should complete but cannot (e.g. when in the middle of a symbol).
  315. Instead of a string, the backend may return a cons (PREFIX . LENGTH)
  316. where LENGTH is a number used in place of PREFIX's length when
  317. comparing against `company-minimum-prefix-length'. LENGTH can also
  318. be just t, and in the latter case the test automatically succeeds.
  319. `candidates': The second argument is the prefix to be completed. The
  320. return value should be a list of candidates that match the prefix.
  321. Non-prefix matches are also supported (candidates that don't start with the
  322. prefix, but match it in some backend-defined way). Backends that use this
  323. feature must disable cache (return t to `no-cache') and might also want to
  324. respond to `match'.
  325. Optional commands
  326. =================
  327. `sorted': Return t here to indicate that the candidates are sorted and will
  328. not need to be sorted again.
  329. `duplicates': If non-nil, company will take care of removing duplicates
  330. from the list.
  331. `no-cache': Usually company doesn't ask for candidates again as completion
  332. progresses, unless the backend returns t for this command. The second
  333. argument is the latest prefix.
  334. `ignore-case': Return t here if the backend returns case-insensitive
  335. matches. This value is used to determine the longest common prefix (as
  336. used in `company-complete-common'), and to filter completions when fetching
  337. them from cache.
  338. `meta': The second argument is a completion candidate. Return a (short)
  339. documentation string for it.
  340. `doc-buffer': The second argument is a completion candidate. Return a
  341. buffer with documentation for it. Preferably use `company-doc-buffer'. If
  342. not all buffer contents pertain to this candidate, return a cons of buffer
  343. and window start position.
  344. `location': The second argument is a completion candidate. Return a cons
  345. of buffer and buffer location, or of file and line number where the
  346. completion candidate was defined.
  347. `annotation': The second argument is a completion candidate. Return a
  348. string to be displayed inline with the candidate in the popup. If
  349. duplicates are removed by company, candidates with equal string values will
  350. be kept if they have different annotations. For that to work properly,
  351. backends should store the related information on candidates using text
  352. properties.
  353. `match': The second argument is a completion candidate. Return a positive
  354. integer, the index after the end of text matching `prefix' within the
  355. candidate string. Alternatively, return a list of (CHUNK-START
  356. . CHUNK-END) elements, where CHUNK-START and CHUNK-END are indexes within
  357. the candidate string. The corresponding regions are be used when rendering
  358. the popup. This command only makes sense for backends that provide
  359. non-prefix completion.
  360. `require-match': If this returns t, the user is not allowed to enter
  361. anything not offered as a candidate. Please don't use that value in normal
  362. backends. The default value nil gives the user that choice with
  363. `company-require-match'. Return value `never' overrides that option the
  364. other way around (using that value will indicate that the returned set of
  365. completions is often incomplete, so this behavior will not be useful).
  366. `init': Called once for each buffer. The backend can check for external
  367. programs and files and load any required libraries. Raising an error here
  368. will show up in message log once, and the backend will not be used for
  369. completion.
  370. `post-completion': Called after a completion candidate has been inserted
  371. into the buffer. The second argument is the candidate. Can be used to
  372. modify it, e.g. to expand a snippet.
  373. The backend should return nil for all commands it does not support or
  374. does not know about. It should also be callable interactively and use
  375. `company-begin-backend' to start itself in that case.
  376. Grouped backends
  377. ================
  378. An element of `company-backends' can also be a list of backends. The
  379. completions from backends in such groups are merged, but only from those
  380. backends which return the same `prefix'.
  381. If a backend command takes a candidate as an argument (e.g. `meta'), the
  382. call is dispatched to the backend the candidate came from. In other
  383. cases (except for `duplicates' and `sorted'), the first non-nil value among
  384. all the backends is returned.
  385. The group can also contain keywords. Currently, `:with' and `:separate'
  386. keywords are defined. If the group contains keyword `:with', the backends
  387. listed after this keyword are ignored for the purpose of the `prefix'
  388. command. If the group contains keyword `:separate', the candidates that
  389. come from different backends are sorted separately in the combined list.
  390. Asynchronous backends
  391. =====================
  392. The return value of each command can also be a cons (:async . FETCHER)
  393. where FETCHER is a function of one argument, CALLBACK. When the data
  394. arrives, FETCHER must call CALLBACK and pass it the appropriate return
  395. value, as described above. That call must happen in the same buffer as
  396. where completion was initiated.
  397. True asynchronous operation is only supported for command `candidates', and
  398. only during idle completion. Other commands will block the user interface,
  399. even if the backend uses the asynchronous calling convention."
  400. :type `(repeat
  401. (choice
  402. :tag "backend"
  403. ,@(mapcar (lambda (b) `(const :tag ,(cdr b) ,(car b)))
  404. company-safe-backends)
  405. (symbol :tag "User defined")
  406. (repeat :tag "Merged backends"
  407. (choice :tag "backend"
  408. ,@(mapcar (lambda (b)
  409. `(const :tag ,(cdr b) ,(car b)))
  410. company-safe-backends)
  411. (const :tag "With" :with)
  412. (symbol :tag "User defined"))))))
  413. (put 'company-backends 'safe-local-variable 'company-safe-backends-p)
  414. (defcustom company-transformers nil
  415. "Functions to change the list of candidates received from backends.
  416. Each function gets called with the return value of the previous one.
  417. The first one gets passed the list of candidates, already sorted and
  418. without duplicates."
  419. :type '(choice
  420. (const :tag "None" nil)
  421. (const :tag "Sort by occurrence" (company-sort-by-occurrence))
  422. (const :tag "Sort by backend importance"
  423. (company-sort-by-backend-importance))
  424. (const :tag "Prefer case sensitive prefix"
  425. (company-sort-prefer-same-case-prefix))
  426. (repeat :tag "User defined" (function))))
  427. (defcustom company-completion-started-hook nil
  428. "Hook run when company starts completing.
  429. The hook is called with one argument that is non-nil if the completion was
  430. started manually."
  431. :type 'hook)
  432. (defcustom company-completion-cancelled-hook nil
  433. "Hook run when company cancels completing.
  434. The hook is called with one argument that is non-nil if the completion was
  435. aborted manually."
  436. :type 'hook)
  437. (defcustom company-completion-finished-hook nil
  438. "Hook run when company successfully completes.
  439. The hook is called with the selected candidate as an argument.
  440. If you indend to use it to post-process candidates from a specific
  441. backend, consider using the `post-completion' command instead."
  442. :type 'hook)
  443. (defcustom company-after-completion-hook nil
  444. "Hook run at the end of completion, successful or not.
  445. The hook is called with one argument which is either a string or a symbol."
  446. :type 'hook)
  447. (defcustom company-minimum-prefix-length 3
  448. "The minimum prefix length for idle completion."
  449. :type '(integer :tag "prefix length"))
  450. (defcustom company-abort-manual-when-too-short nil
  451. "If enabled, cancel a manually started completion when the prefix gets
  452. shorter than both `company-minimum-prefix-length' and the length of the
  453. prefix it was started from."
  454. :type 'boolean
  455. :package-version '(company . "0.8.0"))
  456. (defcustom company-require-match 'company-explicit-action-p
  457. "If enabled, disallow non-matching input.
  458. This can be a function do determine if a match is required.
  459. This can be overridden by the backend, if it returns t or `never' to
  460. `require-match'. `company-auto-complete' also takes precedence over this."
  461. :type '(choice (const :tag "Off" nil)
  462. (function :tag "Predicate function")
  463. (const :tag "On, if user interaction took place"
  464. 'company-explicit-action-p)
  465. (const :tag "On" t)))
  466. (defcustom company-auto-complete nil
  467. "Determines when to auto-complete.
  468. If this is enabled, all characters from `company-auto-complete-chars'
  469. trigger insertion of the selected completion candidate.
  470. This can also be a function."
  471. :type '(choice (const :tag "Off" nil)
  472. (function :tag "Predicate function")
  473. (const :tag "On, if user interaction took place"
  474. 'company-explicit-action-p)
  475. (const :tag "On" t)))
  476. (defcustom company-auto-complete-chars '(?\ ?\) ?.)
  477. "Determines which characters trigger auto-completion.
  478. See `company-auto-complete'. If this is a string, each string character
  479. triggers auto-completion. If it is a list of syntax description characters (see
  480. `modify-syntax-entry'), all characters with that syntax auto-complete.
  481. This can also be a function, which is called with the new input and should
  482. return non-nil if company should auto-complete.
  483. A character that is part of a valid candidate never triggers auto-completion."
  484. :type '(choice (string :tag "Characters")
  485. (set :tag "Syntax"
  486. (const :tag "Whitespace" ?\ )
  487. (const :tag "Symbol" ?_)
  488. (const :tag "Opening parentheses" ?\()
  489. (const :tag "Closing parentheses" ?\))
  490. (const :tag "Word constituent" ?w)
  491. (const :tag "Punctuation." ?.)
  492. (const :tag "String quote." ?\")
  493. (const :tag "Paired delimiter." ?$)
  494. (const :tag "Expression quote or prefix operator." ?\')
  495. (const :tag "Comment starter." ?<)
  496. (const :tag "Comment ender." ?>)
  497. (const :tag "Character-quote." ?/)
  498. (const :tag "Generic string fence." ?|)
  499. (const :tag "Generic comment fence." ?!))
  500. (function :tag "Predicate function")))
  501. (defcustom company-idle-delay .5
  502. "The idle delay in seconds until completion starts automatically.
  503. The prefix still has to satisfy `company-minimum-prefix-length' before that
  504. happens. The value of nil means no idle completion."
  505. :type '(choice (const :tag "never (nil)" nil)
  506. (const :tag "immediate (0)" 0)
  507. (function :tag "Predicate function")
  508. (number :tag "seconds")))
  509. (defcustom company-tooltip-idle-delay .5
  510. "The idle delay in seconds until tooltip is shown when using
  511. `company-pseudo-tooltip-unless-just-one-frontend-with-delay'."
  512. :type '(choice (const :tag "never (nil)" nil)
  513. (const :tag "immediate (0)" 0)
  514. (number :tag "seconds")))
  515. (defcustom company-begin-commands '(self-insert-command
  516. org-self-insert-command
  517. orgtbl-self-insert-command
  518. c-scope-operator
  519. c-electric-colon
  520. c-electric-lt-gt
  521. c-electric-slash)
  522. "A list of commands after which idle completion is allowed.
  523. If this is t, it can show completions after any command except a few from a
  524. pre-defined list. See `company-idle-delay'.
  525. Alternatively, any command with a non-nil `company-begin' property is
  526. treated as if it was on this list."
  527. :type '(choice (const :tag "Any command" t)
  528. (const :tag "Self insert command" '(self-insert-command))
  529. (repeat :tag "Commands" function))
  530. :package-version '(company . "0.8.4"))
  531. (defcustom company-continue-commands '(not save-buffer save-some-buffers
  532. save-buffers-kill-terminal
  533. save-buffers-kill-emacs
  534. completion-at-point)
  535. "A list of commands that are allowed during completion.
  536. If this is t, or if `company-begin-commands' is t, any command is allowed.
  537. Otherwise, the value must be a list of symbols. If it starts with `not',
  538. the cdr is the list of commands that abort completion. Otherwise, all
  539. commands except those in that list, or in `company-begin-commands', or
  540. commands in the `company-' namespace, abort completion."
  541. :type '(choice (const :tag "Any command" t)
  542. (cons :tag "Any except"
  543. (const not)
  544. (repeat :tag "Commands" function))
  545. (repeat :tag "Commands" function)))
  546. (defcustom company-show-numbers nil
  547. "If enabled, show quick-access numbers for the first ten candidates."
  548. :type '(choice (const :tag "off" nil)
  549. (const :tag "left" 'left)
  550. (const :tag "on" 't)))
  551. (defcustom company-show-numbers-function #'company--show-numbers
  552. "Function called to get quick-access numbers for the first ten candidates.
  553. The function receives the candidate number (starting from 1) and should
  554. return a string prefixed with one space."
  555. :type 'function)
  556. (defcustom company-selection-wrap-around nil
  557. "If enabled, selecting item before first or after last wraps around."
  558. :type '(choice (const :tag "off" nil)
  559. (const :tag "on" t)))
  560. (defvar company-async-wait 0.03
  561. "Pause between checks to see if the value's been set when turning an
  562. asynchronous call into synchronous.")
  563. (defvar company-async-timeout 2
  564. "Maximum wait time for a value to be set during asynchronous call.")
  565. ;;; mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  566. (defvar company-mode-map (make-sparse-keymap)
  567. "Keymap used by `company-mode'.")
  568. (defvar company-active-map
  569. (let ((keymap (make-sparse-keymap)))
  570. (define-key keymap "\e\e\e" 'company-abort)
  571. (define-key keymap "\C-g" 'company-abort)
  572. (define-key keymap (kbd "M-n") 'company-select-next)
  573. (define-key keymap (kbd "M-p") 'company-select-previous)
  574. (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
  575. (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
  576. (define-key keymap [remap scroll-up-command] 'company-next-page)
  577. (define-key keymap [remap scroll-down-command] 'company-previous-page)
  578. (define-key keymap [down-mouse-1] 'ignore)
  579. (define-key keymap [down-mouse-3] 'ignore)
  580. (define-key keymap [mouse-1] 'company-complete-mouse)
  581. (define-key keymap [mouse-3] 'company-select-mouse)
  582. (define-key keymap [up-mouse-1] 'ignore)
  583. (define-key keymap [up-mouse-3] 'ignore)
  584. (define-key keymap [return] 'company-complete-selection)
  585. (define-key keymap (kbd "RET") 'company-complete-selection)
  586. (define-key keymap [tab] 'company-complete-common)
  587. (define-key keymap (kbd "TAB") 'company-complete-common)
  588. (define-key keymap (kbd "<f1>") 'company-show-doc-buffer)
  589. (define-key keymap (kbd "C-h") 'company-show-doc-buffer)
  590. (define-key keymap "\C-w" 'company-show-location)
  591. (define-key keymap "\C-s" 'company-search-candidates)
  592. (define-key keymap "\C-\M-s" 'company-filter-candidates)
  593. (dotimes (i 10)
  594. (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
  595. keymap)
  596. "Keymap that is enabled during an active completion.")
  597. (defvar company--disabled-backends nil)
  598. (defun company-init-backend (backend)
  599. (and (symbolp backend)
  600. (not (fboundp backend))
  601. (ignore-errors (require backend nil t)))
  602. (cond
  603. ((symbolp backend)
  604. (condition-case err
  605. (progn
  606. (funcall backend 'init)
  607. (put backend 'company-init t))
  608. (error
  609. (put backend 'company-init 'failed)
  610. (unless (memq backend company--disabled-backends)
  611. (message "Company backend '%s' could not be initialized:\n%s"
  612. backend (error-message-string err)))
  613. (cl-pushnew backend company--disabled-backends)
  614. nil)))
  615. ;; No initialization for lambdas.
  616. ((functionp backend) t)
  617. (t ;; Must be a list.
  618. (cl-dolist (b backend)
  619. (unless (keywordp b)
  620. (company-init-backend b))))))
  621. (defun company--maybe-init-backend (backend)
  622. (or (not (symbolp backend))
  623. (eq t (get backend 'company-init))
  624. (unless (get backend 'company-init)
  625. (company-init-backend backend))))
  626. (defcustom company-lighter-base "company"
  627. "Base string to use for the `company-mode' lighter."
  628. :type 'string
  629. :package-version '(company . "0.8.10"))
  630. (defvar company-lighter '(" "
  631. (company-candidates
  632. (:eval
  633. (if (consp company-backend)
  634. (company--group-lighter (nth company-selection
  635. company-candidates)
  636. company-lighter-base)
  637. (symbol-name company-backend)))
  638. company-lighter-base))
  639. "Mode line lighter for Company.
  640. The value of this variable is a mode line template as in
  641. `mode-line-format'.")
  642. (put 'company-lighter 'risky-local-variable t)
  643. ;;;###autoload
  644. (define-minor-mode company-mode
  645. "\"complete anything\"; is an in-buffer completion framework.
  646. Completion starts automatically, depending on the values
  647. `company-idle-delay' and `company-minimum-prefix-length'.
  648. Completion can be controlled with the commands:
  649. `company-complete-common', `company-complete-selection', `company-complete',
  650. `company-select-next', `company-select-previous'. If these commands are
  651. called before `company-idle-delay', completion will also start.
  652. Completions can be searched with `company-search-candidates' or
  653. `company-filter-candidates'. These can be used while completion is
  654. inactive, as well.
  655. The completion data is retrieved using `company-backends' and displayed
  656. using `company-frontends'. If you want to start a specific backend, call
  657. it interactively or use `company-begin-backend'.
  658. By default, the completions list is sorted alphabetically, unless the
  659. backend chooses otherwise, or `company-transformers' changes it later.
  660. regular keymap (`company-mode-map'):
  661. \\{company-mode-map}
  662. keymap during active completions (`company-active-map'):
  663. \\{company-active-map}"
  664. nil company-lighter company-mode-map
  665. (if company-mode
  666. (progn
  667. (add-hook 'pre-command-hook 'company-pre-command nil t)
  668. (add-hook 'post-command-hook 'company-post-command nil t)
  669. (add-hook 'yas-keymap-disable-hook 'company--active-p nil t)
  670. (mapc 'company-init-backend company-backends))
  671. (remove-hook 'pre-command-hook 'company-pre-command t)
  672. (remove-hook 'post-command-hook 'company-post-command t)
  673. (remove-hook 'yas-keymap-disable-hook 'company--active-p t)
  674. (company-cancel)
  675. (kill-local-variable 'company-point)))
  676. (defcustom company-global-modes t
  677. "Modes for which `company-mode' mode is turned on by `global-company-mode'.
  678. If nil, means no modes. If t, then all major modes have it turned on.
  679. If a list, it should be a list of `major-mode' symbol names for which
  680. `company-mode' should be automatically turned on. The sense of the list is
  681. negated if it begins with `not'. For example:
  682. (c-mode c++-mode)
  683. means that `company-mode' is turned on for buffers in C and C++ modes only.
  684. (not message-mode)
  685. means that `company-mode' is always turned on except in `message-mode' buffers."
  686. :type '(choice (const :tag "none" nil)
  687. (const :tag "all" t)
  688. (set :menu-tag "mode specific" :tag "modes"
  689. :value (not)
  690. (const :tag "Except" not)
  691. (repeat :inline t (symbol :tag "mode")))))
  692. ;;;###autoload
  693. (define-globalized-minor-mode global-company-mode company-mode company-mode-on)
  694. (defun company-mode-on ()
  695. (when (and (not (or noninteractive (eq (aref (buffer-name) 0) ?\s)))
  696. (cond ((eq company-global-modes t)
  697. t)
  698. ((eq (car-safe company-global-modes) 'not)
  699. (not (memq major-mode (cdr company-global-modes))))
  700. (t (memq major-mode company-global-modes))))
  701. (company-mode 1)))
  702. (defsubst company-assert-enabled ()
  703. (unless company-mode
  704. (company-uninstall-map)
  705. (user-error "Company not enabled")))
  706. ;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  707. (defvar-local company-my-keymap nil)
  708. (defvar company-emulation-alist '((t . nil)))
  709. (defun company-enable-overriding-keymap (keymap)
  710. (company-uninstall-map)
  711. (setq company-my-keymap keymap))
  712. (defun company-ensure-emulation-alist ()
  713. (unless (eq 'company-emulation-alist (car emulation-mode-map-alists))
  714. (setq emulation-mode-map-alists
  715. (cons 'company-emulation-alist
  716. (delq 'company-emulation-alist emulation-mode-map-alists)))))
  717. (defun company-install-map ()
  718. (unless (or (cdar company-emulation-alist)
  719. (null company-my-keymap))
  720. (setf (cdar company-emulation-alist) company-my-keymap)))
  721. (defun company-uninstall-map ()
  722. (setf (cdar company-emulation-alist) nil))
  723. (defun company--company-command-p (keys)
  724. "Checks if the keys are part of company's overriding keymap"
  725. (or (equal [company-dummy-event] keys)
  726. (commandp (lookup-key company-my-keymap keys))))
  727. ;; Hack:
  728. ;; Emacs calculates the active keymaps before reading the event. That means we
  729. ;; cannot change the keymap from a timer. So we send a bogus command.
  730. ;; XXX: Seems not to be needed anymore in Emacs 24.4
  731. ;; Apparently, starting with emacs-mirror/emacs@99d0d6dc23.
  732. (defun company-ignore ()
  733. (interactive)
  734. (setq this-command last-command))
  735. (global-set-key '[company-dummy-event] 'company-ignore)
  736. (defun company-input-noop ()
  737. (push 'company-dummy-event unread-command-events))
  738. ;; To avoid warnings in Emacs < 26.
  739. (declare-function line-number-display-width "indent.c")
  740. (defun company--posn-col-row (posn)
  741. (let ((col (car (posn-col-row posn)))
  742. ;; `posn-col-row' doesn't work well with lines of different height.
  743. ;; `posn-actual-col-row' doesn't handle multiple-width characters.
  744. (row (cdr (or (posn-actual-col-row posn)
  745. ;; When position is non-visible for some reason.
  746. (posn-col-row posn)))))
  747. (when (and header-line-format (version< emacs-version "24.3.93.3"))
  748. ;; http://debbugs.gnu.org/18384
  749. (cl-decf row))
  750. (when (bound-and-true-p display-line-numbers)
  751. (cl-decf col (+ 2 (line-number-display-width))))
  752. (cons (+ col (window-hscroll)) row)))
  753. (defun company--col-row (&optional pos)
  754. (company--posn-col-row (posn-at-point pos)))
  755. (defun company--row (&optional pos)
  756. (cdr (company--col-row pos)))
  757. ;;; backends ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  758. (defvar-local company-backend nil)
  759. (defun company-grab (regexp &optional expression limit)
  760. (when (looking-back regexp limit)
  761. (or (match-string-no-properties (or expression 0)) "")))
  762. (defun company-grab-line (regexp &optional expression)
  763. "Return a match string for REGEXP if it matches text before point.
  764. If EXPRESSION is non-nil, return the match string for the respective
  765. parenthesized expression in REGEXP.
  766. Matching is limited to the current line."
  767. (let ((inhibit-field-text-motion t))
  768. (company-grab regexp expression (point-at-bol))))
  769. (defun company-grab-symbol ()
  770. "If point is at the end of a symbol, return it.
  771. Otherwise, if point is not inside a symbol, return an empty string."
  772. (if (looking-at "\\_>")
  773. (buffer-substring (point) (save-excursion (skip-syntax-backward "w_")
  774. (point)))
  775. (unless (and (char-after) (memq (char-syntax (char-after)) '(?w ?_)))
  776. "")))
  777. (defun company-grab-word ()
  778. "If point is at the end of a word, return it.
  779. Otherwise, if point is not inside a symbol, return an empty string."
  780. (if (looking-at "\\>")
  781. (buffer-substring (point) (save-excursion (skip-syntax-backward "w")
  782. (point)))
  783. (unless (and (char-after) (eq (char-syntax (char-after)) ?w))
  784. "")))
  785. (defun company-grab-symbol-cons (idle-begin-after-re &optional max-len)
  786. "Return a string SYMBOL or a cons (SYMBOL . t).
  787. SYMBOL is as returned by `company-grab-symbol'. If the text before point
  788. matches IDLE-BEGIN-AFTER-RE, return it wrapped in a cons."
  789. (let ((symbol (company-grab-symbol)))
  790. (when symbol
  791. (save-excursion
  792. (forward-char (- (length symbol)))
  793. (if (looking-back idle-begin-after-re (if max-len
  794. (- (point) max-len)
  795. (line-beginning-position)))
  796. (cons symbol t)
  797. symbol)))))
  798. (defun company-in-string-or-comment ()
  799. "Return non-nil if point is within a string or comment."
  800. (let ((ppss (syntax-ppss)))
  801. (or (car (setq ppss (nthcdr 3 ppss)))
  802. (car (setq ppss (cdr ppss)))
  803. (nth 3 ppss))))
  804. (defun company-call-backend (&rest args)
  805. (company--force-sync #'company-call-backend-raw args company-backend))
  806. (defun company--force-sync (fun args backend)
  807. (let ((value (apply fun args)))
  808. (if (not (eq (car-safe value) :async))
  809. value
  810. (let ((res 'trash)
  811. (start (time-to-seconds)))
  812. (funcall (cdr value)
  813. (lambda (result) (setq res result)))
  814. (while (eq res 'trash)
  815. (if (> (- (time-to-seconds) start) company-async-timeout)
  816. (error "Company: backend %s async timeout with args %s"
  817. backend args)
  818. ;; XXX: Reusing the trick from company--fetch-candidates here
  819. ;; doesn't work well: sit-for isn't a good fit when we want to
  820. ;; ignore pending input (results in too many calls).
  821. ;; FIXME: We should deal with this by standardizing on a kind of
  822. ;; Future object that knows how to sync itself. In most cases (but
  823. ;; not all), by calling accept-process-output, probably.
  824. (sleep-for company-async-wait)))
  825. res))))
  826. (defun company-call-backend-raw (&rest args)
  827. (condition-case-unless-debug err
  828. (if (functionp company-backend)
  829. (apply company-backend args)
  830. (apply #'company--multi-backend-adapter company-backend args))
  831. (user-error (user-error
  832. "Company: backend %s user-error: %s"
  833. company-backend (error-message-string err)))
  834. (error (error "Company: backend %s error \"%s\" with args %s"
  835. company-backend (error-message-string err) args))))
  836. (defun company--multi-backend-adapter (backends command &rest args)
  837. (let ((backends (cl-loop for b in backends
  838. when (or (keywordp b)
  839. (company--maybe-init-backend b))
  840. collect b))
  841. (separate (memq :separate backends)))
  842. (when (eq command 'prefix)
  843. (setq backends (butlast backends (length (member :with backends)))))
  844. (setq backends (cl-delete-if #'keywordp backends))
  845. (pcase command
  846. (`candidates
  847. (company--multi-backend-adapter-candidates backends (car args) separate))
  848. (`sorted separate)
  849. (`duplicates (not separate))
  850. ((or `prefix `ignore-case `no-cache `require-match)
  851. (let (value)
  852. (cl-dolist (backend backends)
  853. (when (setq value (company--force-sync
  854. backend (cons command args) backend))
  855. (cl-return value)))))
  856. (_
  857. (let ((arg (car args)))
  858. (when (> (length arg) 0)
  859. (let ((backend (or (get-text-property 0 'company-backend arg)
  860. (car backends))))
  861. (apply backend command args))))))))
  862. (defun company--multi-backend-adapter-candidates (backends prefix separate)
  863. (let ((pairs (cl-loop for backend in backends
  864. when (equal (company--prefix-str
  865. (let ((company-backend backend))
  866. (company-call-backend 'prefix)))
  867. prefix)
  868. collect (cons (funcall backend 'candidates prefix)
  869. (company--multi-candidates-mapper
  870. backend
  871. separate
  872. ;; Small perf optimization: don't tag the
  873. ;; candidates received from the first
  874. ;; backend in the group.
  875. (not (eq backend (car backends))))))))
  876. (company--merge-async pairs (lambda (values) (apply #'append values)))))
  877. (defun company--multi-candidates-mapper (backend separate tag)
  878. (lambda (candidates)
  879. (when separate
  880. (let ((company-backend backend))
  881. (setq candidates
  882. (company--preprocess-candidates candidates))))
  883. (when tag
  884. (setq candidates
  885. (mapcar
  886. (lambda (str)
  887. (propertize str 'company-backend backend))
  888. candidates)))
  889. candidates))
  890. (defun company--merge-async (pairs merger)
  891. (let ((async (cl-loop for pair in pairs
  892. thereis
  893. (eq :async (car-safe (car pair))))))
  894. (if (not async)
  895. (funcall merger (cl-loop for (val . mapper) in pairs
  896. collect (funcall mapper val)))
  897. (cons
  898. :async
  899. (lambda (callback)
  900. (let* (lst
  901. (pending (mapcar #'car pairs))
  902. (finisher (lambda ()
  903. (unless pending
  904. (funcall callback
  905. (funcall merger
  906. (nreverse lst)))))))
  907. (dolist (pair pairs)
  908. (push nil lst)
  909. (let* ((cell lst)
  910. (val (car pair))
  911. (mapper (cdr pair))
  912. (this-finisher (lambda (res)
  913. (setq pending (delq val pending))
  914. (setcar cell (funcall mapper res))
  915. (funcall finisher))))
  916. (if (not (eq :async (car-safe val)))
  917. (funcall this-finisher val)
  918. (let ((fetcher (cdr val)))
  919. (funcall fetcher this-finisher)))))))))))
  920. (defun company--prefix-str (prefix)
  921. (or (car-safe prefix) prefix))
  922. ;;; completion mechanism ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  923. (defvar-local company-prefix nil)
  924. (defvar-local company-candidates nil)
  925. (defvar-local company-candidates-length nil)
  926. (defvar-local company-candidates-cache nil)
  927. (defvar-local company-candidates-predicate nil)
  928. (defvar-local company-common nil)
  929. (defvar-local company-selection 0)
  930. (defvar-local company-selection-changed nil)
  931. (defvar-local company--manual-action nil
  932. "Non-nil, if manual completion took place.")
  933. (defvar-local company--manual-prefix nil)
  934. (defvar company--auto-completion nil
  935. "Non-nil when current candidate is being inserted automatically.
  936. Controlled by `company-auto-complete'.")
  937. (defvar-local company--point-max nil)
  938. (defvar-local company-point nil)
  939. (defvar company-timer nil)
  940. (defvar company-tooltip-timer nil)
  941. (defsubst company-strip-prefix (str)
  942. (substring str (length company-prefix)))
  943. (defun company--insert-candidate (candidate)
  944. (when (> (length candidate) 0)
  945. (setq candidate (substring-no-properties candidate))
  946. ;; XXX: Return value we check here is subject to change.
  947. (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
  948. (insert (company-strip-prefix candidate))
  949. (unless (equal company-prefix candidate)
  950. (delete-region (- (point) (length company-prefix)) (point))
  951. (insert candidate)))))
  952. (defmacro company-with-candidate-inserted (candidate &rest body)
  953. "Evaluate BODY with CANDIDATE temporarily inserted.
  954. This is a tool for backends that need candidates inserted before they
  955. can retrieve meta-data for them."
  956. (declare (indent 1))
  957. `(let ((inhibit-modification-hooks t)
  958. (inhibit-point-motion-hooks t)
  959. (modified-p (buffer-modified-p)))
  960. (company--insert-candidate ,candidate)
  961. (unwind-protect
  962. (progn ,@body)
  963. (delete-region company-point (point))
  964. (set-buffer-modified-p modified-p))))
  965. (defun company-explicit-action-p ()
  966. "Return whether explicit completion action was taken by the user."
  967. (or company--manual-action
  968. company-selection-changed))
  969. (defun company-reformat (candidate)
  970. ;; company-ispell needs this, because the results are always lower-case
  971. ;; It's mory efficient to fix it only when they are displayed.
  972. ;; FIXME: Adopt the current text's capitalization instead?
  973. (if (eq (company-call-backend 'ignore-case) 'keep-prefix)
  974. (let ((prefix (company--clean-string company-prefix)))
  975. (concat prefix (substring candidate (length prefix))))
  976. candidate))
  977. (defun company--should-complete ()
  978. (and (eq company-idle-delay 'now)
  979. (not (or buffer-read-only
  980. overriding-local-map))
  981. ;; Check if in the middle of entering a key combination.
  982. (or (equal (this-command-keys-vector) [])
  983. (not (keymapp (key-binding (this-command-keys-vector)))))
  984. (not (and transient-mark-mode mark-active))))
  985. (defun company--should-continue ()
  986. (or (eq t company-begin-commands)
  987. (eq t company-continue-commands)
  988. (if (eq 'not (car company-continue-commands))
  989. (not (memq this-command (cdr company-continue-commands)))
  990. (or (memq this-command company-begin-commands)
  991. (memq this-command company-continue-commands)
  992. (and (symbolp this-command)
  993. (string-match-p "\\`company-" (symbol-name this-command)))))))
  994. (defun company-call-frontends (command)
  995. (dolist (frontend company-frontends)
  996. (condition-case-unless-debug err
  997. (funcall frontend command)
  998. (error (error "Company: frontend %s error \"%s\" on command %s"
  999. frontend (error-message-string err) command)))))
  1000. (defun company-set-selection (selection &optional force-update)
  1001. (setq selection
  1002. (if company-selection-wrap-around
  1003. (mod selection company-candidates-length)
  1004. (max 0 (min (1- company-candidates-length) selection))))
  1005. (when (or force-update (not (equal selection company-selection)))
  1006. (setq company-selection selection
  1007. company-selection-changed t)
  1008. (company-call-frontends 'update)))
  1009. (defun company--group-lighter (candidate base)
  1010. (let ((backend (or (get-text-property 0 'company-backend candidate)
  1011. (cl-some (lambda (x) (and (not (keywordp x)) x))
  1012. company-backend))))
  1013. (when (and backend (symbolp backend))
  1014. (let ((name (replace-regexp-in-string "company-\\|-company" ""
  1015. (symbol-name backend))))
  1016. (format "%s-<%s>" base name)))))
  1017. (defun company-update-candidates (candidates)
  1018. (setq company-candidates-length (length candidates))
  1019. (if company-selection-changed
  1020. ;; Try to restore the selection
  1021. (let ((selected (nth company-selection company-candidates)))
  1022. (setq company-selection 0
  1023. company-candidates candidates)
  1024. (when selected
  1025. (catch 'found
  1026. (while candidates
  1027. (let ((candidate (pop candidates)))
  1028. (when (and (string= candidate selected)
  1029. (equal (company-call-backend 'annotation candidate)
  1030. (company-call-backend 'annotation selected)))
  1031. (throw 'found t)))
  1032. (cl-incf company-selection))
  1033. (setq company-selection 0
  1034. company-selection-changed nil))))
  1035. (setq company-selection 0
  1036. company-candidates candidates))
  1037. ;; Calculate common.
  1038. (let ((completion-ignore-case (company-call-backend 'ignore-case)))
  1039. ;; We want to support non-prefix completion, so filtering is the
  1040. ;; responsibility of each respective backend, not ours.
  1041. ;; On the other hand, we don't want to replace non-prefix input in
  1042. ;; `company-complete-common', unless there's only one candidate.
  1043. (setq company-common
  1044. (if (cdr company-candidates)
  1045. (let ((common (try-completion "" company-candidates)))
  1046. (when (string-prefix-p company-prefix common
  1047. completion-ignore-case)
  1048. common))
  1049. (car company-candidates)))))
  1050. (defun company-calculate-candidates (prefix ignore-case)
  1051. (let ((candidates (cdr (assoc prefix company-candidates-cache))))
  1052. (or candidates
  1053. (when company-candidates-cache
  1054. (let ((len (length prefix))
  1055. (completion-ignore-case ignore-case)
  1056. prev)
  1057. (cl-dotimes (i (1+ len))
  1058. (when (setq prev (cdr (assoc (substring prefix 0 (- len i))
  1059. company-candidates-cache)))
  1060. (setq candidates (all-completions prefix prev))
  1061. (cl-return t)))))
  1062. (progn
  1063. ;; No cache match, call the backend.
  1064. (setq candidates (company--preprocess-candidates
  1065. (company--fetch-candidates prefix)))
  1066. ;; Save in cache.
  1067. (push (cons prefix candidates) company-candidates-cache)))
  1068. ;; Only now apply the predicate and transformers.
  1069. (company--postprocess-candidates candidates)))
  1070. (defun company--unique-match-p (candidates prefix ignore-case)
  1071. (and candidates
  1072. (not (cdr candidates))
  1073. (eq t (compare-strings (car candidates) nil nil
  1074. prefix nil nil ignore-case))))
  1075. (defun company--fetch-candidates (prefix)
  1076. (let* ((non-essential (not (company-explicit-action-p)))
  1077. (inhibit-redisplay t)
  1078. (c (if (or company-selection-changed
  1079. ;; FIXME: This is not ideal, but we have not managed to deal
  1080. ;; with these situations in a better way yet.
  1081. (company-require-match-p))
  1082. (company-call-backend 'candidates prefix)
  1083. (company-call-backend-raw 'candidates prefix))))
  1084. (if (not (eq (car c) :async))
  1085. c
  1086. (let ((res 'none))
  1087. (funcall
  1088. (cdr c)
  1089. (lambda (candidates)
  1090. (when (eq res 'none)
  1091. (push 'company-foo unread-command-events))
  1092. (setq res candidates)))
  1093. (if (company--flyspell-workaround-p)
  1094. (while (and (eq res 'none)
  1095. (not (input-pending-p)))
  1096. (sleep-for company-async-wait))
  1097. (while (and (eq res 'none)
  1098. (sit-for 0.5 t))))
  1099. (while (member (car unread-command-events)
  1100. '(company-foo (t . company-foo)))
  1101. (pop unread-command-events))
  1102. (prog1
  1103. (and (consp res) res)
  1104. (setq res 'exited))))))
  1105. (defun company--flyspell-workaround-p ()
  1106. ;; https://debbugs.gnu.org/23980
  1107. (and (bound-and-true-p flyspell-mode)
  1108. (version< emacs-version "27")))
  1109. (defun company--preprocess-candidates (candidates)
  1110. (cl-assert (cl-every #'stringp candidates))
  1111. (unless (company-call-backend 'sorted)
  1112. (setq candidates (sort candidates 'string<)))
  1113. (when (company-call-backend 'duplicates)
  1114. (company--strip-duplicates candidates))
  1115. candidates)
  1116. (defun company--postprocess-candidates (candidates)
  1117. (when (or company-candidates-predicate company-transformers)
  1118. (setq candidates (copy-sequence candidates)))
  1119. (when company-candidates-predicate
  1120. (setq candidates (cl-delete-if-not company-candidates-predicate candidates)))
  1121. (company--transform-candidates candidates))
  1122. (defun company--strip-duplicates (candidates)
  1123. (let ((c2 candidates)
  1124. (annos 'unk))
  1125. (while c2
  1126. (setcdr c2
  1127. (let ((str (pop c2)))
  1128. (while (let ((str2 (car c2)))
  1129. (if (not (equal str str2))
  1130. (progn
  1131. (setq annos 'unk)
  1132. nil)
  1133. (when (eq annos 'unk)
  1134. (setq annos (list (company-call-backend
  1135. 'annotation str))))
  1136. (let ((anno2 (company-call-backend
  1137. 'annotation str2)))
  1138. (if (member anno2 annos)
  1139. t
  1140. (push anno2 annos)
  1141. nil))))
  1142. (pop c2))
  1143. c2)))))
  1144. (defun company--transform-candidates (candidates)
  1145. (let ((c candidates))
  1146. (dolist (tr company-transformers)
  1147. (setq c (funcall tr c)))
  1148. c))
  1149. (defcustom company-occurrence-weight-function
  1150. #'company-occurrence-prefer-closest-above
  1151. "Function to weigh matches in `company-sort-by-occurrence'.
  1152. It's called with three arguments: cursor position, the beginning and the
  1153. end of the match."
  1154. :type '(choice
  1155. (const :tag "First above point, then below point"
  1156. company-occurrence-prefer-closest-above)
  1157. (const :tag "Prefer closest in any direction"
  1158. company-occurrence-prefer-any-closest)))
  1159. (defun company-occurrence-prefer-closest-above (pos match-beg match-end)
  1160. "Give priority to the matches above point, then those below point."
  1161. (if (< match-beg pos)
  1162. (- pos match-end)
  1163. (- match-beg (window-start))))
  1164. (defun company-occurrence-prefer-any-closest (pos _match-beg match-end)
  1165. "Give priority to the matches closest to the point."
  1166. (abs (- pos match-end)))
  1167. (defun company-sort-by-occurrence (candidates)
  1168. "Sort CANDIDATES according to their occurrences.
  1169. Searches for each in the currently visible part of the current buffer and
  1170. prioritizes the matches according to `company-occurrence-weight-function'.
  1171. The rest of the list is appended unchanged.
  1172. Keywords and function definition names are ignored."
  1173. (let* ((w-start (window-start))
  1174. (w-end (window-end))
  1175. (start-point (point))
  1176. occurs
  1177. (noccurs
  1178. (save-excursion
  1179. (cl-delete-if
  1180. (lambda (candidate)
  1181. (when (catch 'done
  1182. (goto-char w-start)
  1183. (while (search-forward candidate w-end t)
  1184. (when (and (not (eq (point) start-point))
  1185. (save-match-data
  1186. (company--occurrence-predicate)))
  1187. (throw 'done t))))
  1188. (push
  1189. (cons candidate
  1190. (funcall company-occurrence-weight-function
  1191. start-point
  1192. (match-beginning 0)
  1193. (match-end 0)))
  1194. occurs)
  1195. t))
  1196. candidates))))
  1197. (nconc
  1198. (mapcar #'car (sort occurs (lambda (e1 e2) (<= (cdr e1) (cdr e2)))))
  1199. noccurs)))
  1200. (defun company--occurrence-predicate ()
  1201. (defvar comint-last-prompt)
  1202. (let ((beg (match-beginning 0))
  1203. (end (match-end 0))
  1204. (comint-last-prompt (bound-and-true-p comint-last-prompt)))
  1205. (save-excursion
  1206. (goto-char end)
  1207. ;; Workaround for python-shell-completion-at-point's behavior:
  1208. ;; https://github.com/company-mode/company-mode/issues/759
  1209. ;; https://github.com/company-mode/company-mode/issues/549
  1210. (when (derived-mode-p 'inferior-python-mode)
  1211. (let ((lbp (line-beginning-position)))
  1212. (setq comint-last-prompt (cons lbp lbp))))
  1213. (and (not (memq (get-text-property (1- (point)) 'face)
  1214. '(font-lock-function-name-face
  1215. font-lock-keyword-face)))
  1216. (let ((prefix (company--prefix-str
  1217. (company-call-backend 'prefix))))
  1218. (and (stringp prefix)
  1219. (= (length prefix) (- end beg))))))))
  1220. (defun company-sort-by-backend-importance (candidates)
  1221. "Sort CANDIDATES as two priority groups.
  1222. If `company-backend' is a function, do nothing. If it's a list, move
  1223. candidates from backends before keyword `:with' to the front. Candidates
  1224. from the rest of the backends in the group, if any, will be left at the end."
  1225. (if (functionp company-backend)
  1226. candidates
  1227. (let ((low-priority (cdr (memq :with company-backend))))
  1228. (if (null low-priority)
  1229. candidates
  1230. (sort candidates
  1231. (lambda (c1 c2)
  1232. (and
  1233. (let ((b2 (get-text-property 0 'company-backend c2)))
  1234. (and b2 (memq b2 low-priority)))
  1235. (let ((b1 (get-text-property 0 'company-backend c1)))
  1236. (or (not b1) (not (memq b1 low-priority)))))))))))
  1237. (defun company-sort-prefer-same-case-prefix (candidates)
  1238. "Prefer CANDIDATES with the exact same prefix.
  1239. If a backend returns case insensitive matches, candidates with the an exact
  1240. prefix match (same case) will be prioritized."
  1241. (cl-loop for candidate in candidates
  1242. if (string-prefix-p company-prefix candidate)
  1243. collect candidate into same-case
  1244. else collect candidate into other-case
  1245. finally return (append same-case other-case)))
  1246. (defun company-idle-begin (buf win tick pos)
  1247. (and (eq buf (current-buffer))
  1248. (eq win (selected-window))
  1249. (eq tick (buffer-chars-modified-tick))
  1250. (eq pos (point))
  1251. (when (company-auto-begin)
  1252. (when (version< emacs-version "24.3.50")
  1253. (company-input-noop))
  1254. (let ((this-command 'company-idle-begin))
  1255. (company-post-command)))))
  1256. (defun company-auto-begin ()
  1257. (and company-mode
  1258. (not company-candidates)
  1259. (let ((company-idle-delay 'now))
  1260. (condition-case-unless-debug err
  1261. (let ((inhibit-quit nil))
  1262. (company--perform)
  1263. ;; Return non-nil if active.
  1264. company-candidates)
  1265. (error (message "Company: An error occurred in auto-begin")
  1266. (message "%s" (error-message-string err))
  1267. (company-cancel))
  1268. (quit (company-cancel))))))
  1269. ;;;###autoload
  1270. (defun company-manual-begin ()
  1271. (interactive)
  1272. (company-assert-enabled)
  1273. (setq company--manual-action t)
  1274. (unwind-protect
  1275. (let ((company-minimum-prefix-length 0))
  1276. (or company-candidates
  1277. (company-auto-begin)))
  1278. (unless company-candidates
  1279. (setq company--manual-action nil))))
  1280. (defun company-other-backend (&optional backward)
  1281. (interactive (list current-prefix-arg))
  1282. (company-assert-enabled)
  1283. (let* ((after (if company-backend
  1284. (cdr (member company-backend company-backends))
  1285. company-backends))
  1286. (before (cdr (member company-backend (reverse company-backends))))
  1287. (next (if backward
  1288. (append before (reverse after))
  1289. (append after (reverse before)))))
  1290. (company-cancel)
  1291. (cl-dolist (backend next)
  1292. (when (ignore-errors (company-begin-backend backend))
  1293. (cl-return t))))
  1294. (unless company-candidates
  1295. (user-error "No other backend")))
  1296. (defun company-require-match-p ()
  1297. (let ((backend-value (company-call-backend 'require-match)))
  1298. (or (eq backend-value t)
  1299. (and (not (eq backend-value 'never))
  1300. (if (functionp company-require-match)
  1301. (funcall company-require-match)
  1302. (eq company-require-match t))))))
  1303. (defun company-auto-complete-p (input)
  1304. "Return non-nil if INPUT should trigger auto-completion."
  1305. (and (if (functionp company-auto-complete)
  1306. (funcall company-auto-complete)
  1307. company-auto-complete)
  1308. (if (functionp company-auto-complete-chars)
  1309. (funcall company-auto-complete-chars input)
  1310. (if (consp company-auto-complete-chars)
  1311. (memq (char-syntax (string-to-char input))
  1312. company-auto-complete-chars)
  1313. (string-match (regexp-quote (substring input 0 1))
  1314. company-auto-complete-chars)))))
  1315. (defun company--incremental-p ()
  1316. (and (> (point) company-point)
  1317. (> (point-max) company--point-max)
  1318. (not (eq this-command 'backward-delete-char-untabify))
  1319. (equal (buffer-substring (- company-point (length company-prefix))
  1320. company-point)
  1321. company-prefix)))
  1322. (defun company--continue-failed (new-prefix)
  1323. (cond
  1324. ((and (or (not (company-require-match-p))
  1325. ;; Don't require match if the new prefix
  1326. ;; doesn't continue the old one, and the latter was a match.
  1327. (not (stringp new-prefix))
  1328. (<= (length new-prefix) (length company-prefix)))
  1329. (member company-prefix company-candidates))
  1330. ;; Last input was a success,
  1331. ;; but we're treating it as an abort + input anyway,
  1332. ;; like the `unique' case below.
  1333. (company-cancel 'non-unique))
  1334. ((company-require-match-p)
  1335. ;; Wrong incremental input, but required match.
  1336. (delete-char (- company-point (point)))
  1337. (ding)
  1338. (message "Matching input is required")
  1339. company-candidates)
  1340. (t (company-cancel))))
  1341. (defun company--good-prefix-p (prefix)
  1342. (and (stringp (company--prefix-str prefix)) ;excludes 'stop
  1343. (or (eq (cdr-safe prefix) t)
  1344. (let ((len (or (cdr-safe prefix) (length prefix))))
  1345. (if company--manual-prefix
  1346. (or (not company-abort-manual-when-too-short)
  1347. ;; Must not be less than minimum or initial length.
  1348. (>= len (min company-minimum-prefix-length
  1349. (length company--manual-prefix))))
  1350. (>= len company-minimum-prefix-length))))))
  1351. (defun company--continue ()
  1352. (when (company-call-backend 'no-cache company-prefix)
  1353. ;; Don't complete existing candidates, fetch new ones.
  1354. (setq company-candidates-cache nil))
  1355. (let* ((new-prefix (company-call-backend 'prefix))
  1356. (ignore-case (company-call-backend 'ignore-case))
  1357. (c (when (and (company--good-prefix-p new-prefix)
  1358. (setq new-prefix (company--prefix-str new-prefix))
  1359. (= (- (point) (length new-prefix))
  1360. (- company-point (length company-prefix))))
  1361. (company-calculate-candidates new-prefix ignore-case))))
  1362. (cond
  1363. ((company--unique-match-p c new-prefix ignore-case)
  1364. ;; Handle it like completion was aborted, to differentiate from user
  1365. ;; calling one of Company's commands to insert the candidate,
  1366. ;; not to trigger template expansion, etc.
  1367. (company-cancel 'unique))
  1368. ((consp c)
  1369. ;; incremental match
  1370. (setq company-prefix new-prefix)
  1371. (company-update-candidates c)
  1372. c)
  1373. ((and (characterp last-command-event)
  1374. (company-auto-complete-p (string last-command-event)))
  1375. ;; auto-complete
  1376. (save-excursion
  1377. (goto-char company-point)
  1378. (let ((company--auto-completion t))
  1379. (company-complete-selection))
  1380. nil))
  1381. ((not (company--incremental-p))
  1382. (company-cancel))
  1383. (t (company--continue-failed new-prefix)))))
  1384. (defun company--begin-new ()
  1385. (let (prefix c)
  1386. (cl-dolist (backend (if company-backend
  1387. ;; prefer manual override
  1388. (list company-backend)
  1389. company-backends))
  1390. (setq prefix
  1391. (if (or (symbolp backend)
  1392. (functionp backend))
  1393. (when (company--maybe-init-backend backend)
  1394. (let ((company-backend backend))
  1395. (company-call-backend 'prefix)))
  1396. (company--multi-backend-adapter backend 'prefix)))
  1397. (when prefix
  1398. (when (company--good-prefix-p prefix)
  1399. (let ((ignore-case (company-call-backend 'ignore-case)))
  1400. (setq company-prefix (company--prefix-str prefix)
  1401. company-backend backend
  1402. c (company-calculate-candidates company-prefix ignore-case))
  1403. (cond
  1404. ((and (company--unique-match-p c company-prefix ignore-case)
  1405. (if company--manual-action
  1406. ;; If `company-manual-begin' was called, the user
  1407. ;; really wants something to happen. Otherwise...
  1408. (ignore (message "Sole completion"))
  1409. t))
  1410. ;; ...abort and run the hooks, e.g. to clear the cache.
  1411. (company-cancel 'unique))
  1412. ((null c)
  1413. (when company--manual-action
  1414. (message "No completion found")))
  1415. (t ;; We got completions!
  1416. (when company--manual-action
  1417. (setq company--manual-prefix prefix))
  1418. (company-update-candidates c)
  1419. (run-hook-with-args 'company-completion-started-hook
  1420. (company-explicit-action-p))
  1421. (company-call-frontends 'show)))))
  1422. (cl-return c)))))
  1423. (defun company--perform ()
  1424. (cond
  1425. (company-candidates
  1426. (company--continue))
  1427. ((company--should-complete)
  1428. (company--begin-new)))
  1429. (if (not company-candidates)
  1430. (setq company-backend nil)
  1431. (setq company-point (point)
  1432. company--point-max (point-max))
  1433. (company-ensure-emulation-alist)
  1434. (company-enable-overriding-keymap company-active-map)
  1435. (company-call-frontends 'update)))
  1436. (defun company-cancel (&optional result)
  1437. (let ((prefix company-prefix)
  1438. (backend company-backend))
  1439. (setq company-backend nil
  1440. company-prefix nil
  1441. company-candidates nil
  1442. company-candidates-length nil
  1443. company-candidates-cache nil
  1444. company-candidates-predicate nil
  1445. company-common nil
  1446. company-selection 0
  1447. company-selection-changed nil
  1448. company--manual-action nil
  1449. company--manual-prefix nil
  1450. company--point-max nil
  1451. company-point nil)
  1452. (when company-timer
  1453. (cancel-timer company-timer))
  1454. (company-echo-cancel t)
  1455. (company-search-mode 0)
  1456. (company-call-frontends 'hide)
  1457. (company-enable-overriding-keymap nil)
  1458. (when prefix
  1459. (if (stringp result)
  1460. (let ((company-backend backend))
  1461. (run-hook-with-args 'company-completion-finished-hook result)
  1462. (company-call-backend 'post-completion result))
  1463. (run-hook-with-args 'company-completion-cancelled-hook result))
  1464. (run-hook-with-args 'company-after-completion-hook result)))
  1465. ;; Make return value explicit.
  1466. nil)
  1467. (defun company-abort ()
  1468. (interactive)
  1469. (company-cancel 'abort))
  1470. (defun company-finish (result)
  1471. (company--insert-candidate result)
  1472. (company-cancel result))
  1473. (defsubst company-keep (command)
  1474. (and (symbolp command) (get command 'company-keep)))
  1475. (defun company--active-p ()
  1476. company-candidates)
  1477. (defun company-pre-command ()
  1478. (company--electric-restore-window-configuration)
  1479. (unless (company-keep this-command)
  1480. (condition-case-unless-debug err
  1481. (when company-candidates
  1482. (company-call-frontends 'pre-command)
  1483. (unless (company--should-continue)
  1484. (company-abort)))
  1485. (error (message "Company: An error occurred in pre-command")
  1486. (message "%s" (error-message-string err))
  1487. (company-cancel))))
  1488. (when company-timer
  1489. (cancel-timer company-timer)
  1490. (setq company-timer nil))
  1491. (company-echo-cancel t)
  1492. (company-uninstall-map))
  1493. (defun company-post-command ()
  1494. (when (and company-candidates
  1495. (null this-command))
  1496. ;; Happens when the user presses `C-g' while inside
  1497. ;; `flyspell-post-command-hook', for example.
  1498. ;; Or any other `post-command-hook' function that can call `sit-for',
  1499. ;; or any quittable timer function.
  1500. (company-abort)
  1501. (setq this-command 'company-abort))
  1502. (unless (company-keep this-command)
  1503. (condition-case-unless-debug err
  1504. (progn
  1505. (unless (equal (point) company-point)
  1506. (let (company-idle-delay) ; Against misbehavior while debugging.
  1507. (company--perform)))
  1508. (if company-candidates
  1509. (company-call-frontends 'post-command)
  1510. (let ((delay (company--idle-delay)))
  1511. (and (numberp delay)
  1512. (not defining-kbd-macro)
  1513. (company--should-begin)
  1514. (setq company-timer
  1515. (run-with-timer delay nil
  1516. 'company-idle-begin
  1517. (current-buffer) (selected-window)
  1518. (buffer-chars-modified-tick) (point)))))))
  1519. (error (message "Company: An error occurred in post-command")
  1520. (message "%s" (error-message-string err))
  1521. (company-cancel))))
  1522. (company-install-map))
  1523. (defun company--idle-delay ()
  1524. (let ((delay
  1525. (if (functionp company-idle-delay)
  1526. (funcall company-idle-delay)
  1527. company-idle-delay)))
  1528. (if (memql delay '(t 0 0.0))
  1529. 0.01
  1530. delay)))
  1531. (defvar company--begin-inhibit-commands '(company-abort
  1532. company-complete-mouse
  1533. company-complete
  1534. company-complete-common
  1535. company-complete-selection
  1536. company-complete-number)
  1537. "List of commands after which idle completion is (still) disabled when
  1538. `company-begin-commands' is t.")
  1539. (defun company--should-begin ()
  1540. (if (eq t company-begin-commands)
  1541. (not (memq this-command company--begin-inhibit-commands))
  1542. (or
  1543. (memq this-command company-begin-commands)
  1544. (and (symbolp this-command) (get this-command 'company-begin)))))
  1545. ;;; search ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1546. (defcustom company-search-regexp-function #'regexp-quote
  1547. "Function to construct the search regexp from input.
  1548. It's called with one argument, the current search input. It must return
  1549. either a regexp without groups, or one where groups don't intersect and
  1550. each one wraps a part of the input string."
  1551. :type '(choice
  1552. (const :tag "Exact match" regexp-quote)
  1553. (const :tag "Words separated with spaces" company-search-words-regexp)
  1554. (const :tag "Words separated with spaces, in any order"
  1555. company-search-words-in-any-order-regexp)
  1556. (const :tag "All characters in given order, with anything in between"
  1557. company-search-flex-regexp)))
  1558. (defvar-local company-search-string "")
  1559. (defvar company-search-lighter '(" "
  1560. (company-search-filtering "Filter" "Search")
  1561. ": \""
  1562. company-search-string
  1563. "\""))
  1564. (defvar-local company-search-filtering nil
  1565. "Non-nil to filter the completion candidates by the search string")
  1566. (defvar-local company--search-old-selection 0)
  1567. (defvar-local company--search-old-changed nil)
  1568. (defun company-search-words-regexp (input)
  1569. (mapconcat (lambda (word) (format "\\(%s\\)" (regexp-quote word)))
  1570. (split-string input " +" t) ".*"))
  1571. (defun company-search-words-in-any-order-regexp (input)
  1572. (let* ((words (mapcar (lambda (word) (format "\\(%s\\)" (regexp-quote word)))
  1573. (split-string input " +" t)))
  1574. (permutations (company--permutations words)))
  1575. (mapconcat (lambda (words)
  1576. (mapconcat #'identity words ".*"))
  1577. permutations
  1578. "\\|")))
  1579. (defun company-search-flex-regexp (input)
  1580. (if (zerop (length input))
  1581. ""
  1582. (concat (regexp-quote (string (aref input 0)))
  1583. (mapconcat (lambda (c)
  1584. (concat "[^" (string c) "]*"
  1585. (regexp-quote (string c))))
  1586. (substring input 1) ""))))
  1587. (defun company--permutations (lst)
  1588. (if (not lst)
  1589. '(nil)
  1590. (cl-mapcan
  1591. (lambda (e)
  1592. (mapcar (lambda (perm) (cons e perm))
  1593. (company--permutations (cl-remove e lst :count 1))))
  1594. lst)))
  1595. (defun company--search (text lines)
  1596. (let ((re (funcall company-search-regexp-function text))
  1597. (i 0))
  1598. (cl-dolist (line lines)
  1599. (when (string-match-p re line (length company-prefix))
  1600. (cl-return i))
  1601. (cl-incf i))))
  1602. (defun company-search-keypad ()
  1603. (interactive)
  1604. (let* ((name (symbol-name last-command-event))
  1605. (last-command-event (aref name (1- (length name)))))
  1606. (company-search-printing-char)))
  1607. (defun company-search-printing-char ()
  1608. (interactive)
  1609. (company--search-assert-enabled)
  1610. (let ((ss (concat company-search-string (string last-command-event))))
  1611. (when company-search-filtering
  1612. (company--search-update-predicate ss))
  1613. (company--search-update-string ss)))
  1614. (defun company--search-update-predicate (ss)
  1615. (let* ((re (funcall company-search-regexp-function ss))
  1616. (company-candidates-predicate
  1617. (and (not (string= re ""))
  1618. company-search-filtering
  1619. (lambda (candidate) (string-match re candidate))))
  1620. (cc (company-calculate-candidates company-prefix
  1621. (company-call-backend 'ignore-case))))
  1622. (unless cc (user-error "No match"))
  1623. (company-update-candidates cc)))
  1624. (defun company--search-update-string (new)
  1625. (let* ((pos (company--search new (nthcdr company-selection company-candidates))))
  1626. (if (null pos)
  1627. (ding)
  1628. (setq company-search-string new)
  1629. (company-set-selection (+ company-selection pos) t))))
  1630. (defun company--search-assert-input ()
  1631. (company--search-assert-enabled)
  1632. (when (string= company-search-string "")
  1633. (user-error "Empty search string")))
  1634. (defun company-search-repeat-forward ()
  1635. "Repeat the incremental search in completion candidates forward."
  1636. (interactive)
  1637. (company--search-assert-input)
  1638. (let ((pos (company--search company-search-string
  1639. (cdr (nthcdr company-selection
  1640. company-candidates)))))
  1641. (if (null pos)
  1642. (ding)
  1643. (company-set-selection (+ company-selection pos 1) t))))
  1644. (defun company-search-repeat-backward ()
  1645. "Repeat the incremental search in completion candidates backwards."
  1646. (interactive)
  1647. (company--search-assert-input)
  1648. (let ((pos (company--search company-search-string
  1649. (nthcdr (- company-candidates-length
  1650. company-selection)
  1651. (reverse company-candidates)))))
  1652. (if (null pos)
  1653. (ding)
  1654. (company-set-selection (- company-selection pos 1) t))))
  1655. (defun company-search-toggle-filtering ()
  1656. "Toggle `company-search-filtering'."
  1657. (interactive)
  1658. (company--search-assert-enabled)
  1659. (setq company-search-filtering (not company-search-filtering))
  1660. (let ((ss company-search-string))
  1661. (company--search-update-predicate ss)
  1662. (company--search-update-string ss)))
  1663. (defun company-search-abort ()
  1664. "Abort searching the completion candidates."
  1665. (interactive)
  1666. (company--search-assert-enabled)
  1667. (company-search-mode 0)
  1668. (company-set-selection company--search-old-selection t)
  1669. (setq company-selection-changed company--search-old-changed))
  1670. (defun company-search-other-char ()
  1671. (interactive)
  1672. (company--search-assert-enabled)
  1673. (company-search-mode 0)
  1674. (company--unread-this-command-keys))
  1675. (defun company-search-delete-char ()
  1676. (interactive)
  1677. (company--search-assert-enabled)
  1678. (if (string= company-search-string "")
  1679. (ding)
  1680. (let ((ss (substring company-search-string 0 -1)))
  1681. (when company-search-filtering
  1682. (company--search-update-predicate ss))
  1683. (company--search-update-string ss))))
  1684. (defvar company-search-map
  1685. (let ((i 0)
  1686. (keymap (make-keymap)))
  1687. (if (fboundp 'max-char)
  1688. (set-char-table-range (nth 1 keymap) (cons #x100 (max-char))
  1689. 'company-search-printing-char)
  1690. (with-no-warnings
  1691. ;; obsolete in Emacs 23
  1692. (let ((l (generic-character-list))
  1693. (table (nth 1 keymap)))
  1694. (while l
  1695. (set-char-table-default table (car l) 'company-search-printing-char)
  1696. (setq l (cdr l))))))
  1697. (define-key keymap [t] 'company-search-other-char)
  1698. (while (< i ?\s)
  1699. (define-key keymap (make-string 1 i) 'company-search-other-char)
  1700. (cl-incf i))
  1701. (while (< i 256)
  1702. (define-key keymap (vector i) 'company-search-printing-char)
  1703. (cl-incf i))
  1704. (dotimes (i 10)
  1705. (define-key keymap (read (format "[kp-%s]" i)) 'company-search-keypad))
  1706. (let ((meta-map (make-sparse-keymap)))
  1707. (define-key keymap (char-to-string meta-prefix-char) meta-map)
  1708. (define-key keymap [escape] meta-map))
  1709. (define-key keymap (vector meta-prefix-char t) 'company-search-other-char)
  1710. (define-key keymap (kbd "M-n") 'company-select-next)
  1711. (define-key keymap (kbd "M-p") 'company-select-previous)
  1712. (define-key keymap (kbd "<down>") 'company-select-next-or-abort)
  1713. (define-key keymap (kbd "<up>") 'company-select-previous-or-abort)
  1714. (define-key keymap "\e\e\e" 'company-search-other-char)
  1715. (define-key keymap [escape escape escape] 'company-search-other-char)
  1716. (define-key keymap (kbd "DEL") 'company-search-delete-char)
  1717. (define-key keymap [backspace] 'company-search-delete-char)
  1718. (define-key keymap "\C-g" 'company-search-abort)
  1719. (define-key keymap "\C-s" 'company-search-repeat-forward)
  1720. (define-key keymap "\C-r" 'company-search-repeat-backward)
  1721. (define-key keymap "\C-o" 'company-search-toggle-filtering)
  1722. (dotimes (i 10)
  1723. (define-key keymap (read-kbd-macro (format "M-%d" i)) 'company-complete-number))
  1724. keymap)
  1725. "Keymap used for incrementally searching the completion candidates.")
  1726. (define-minor-mode company-search-mode
  1727. "Search mode for completion candidates.
  1728. Don't start this directly, use `company-search-candidates' or
  1729. `company-filter-candidates'."
  1730. nil company-search-lighter nil
  1731. (if company-search-mode
  1732. (if (company-manual-begin)
  1733. (progn
  1734. (setq company--search-old-selection company-selection
  1735. company--search-old-changed company-selection-changed)
  1736. (company-call-frontends 'update)
  1737. (company-enable-overriding-keymap company-search-map))
  1738. (setq company-search-mode nil))
  1739. (kill-local-variable 'company-search-string)
  1740. (kill-local-variable 'company-search-filtering)
  1741. (kill-local-variable 'company--search-old-selection)
  1742. (kill-local-variable 'company--search-old-changed)
  1743. (when company-backend
  1744. (company--search-update-predicate "")
  1745. (company-call-frontends 'update))
  1746. (company-enable-overriding-keymap company-active-map)))
  1747. (defun company--search-assert-enabled ()
  1748. (company-assert-enabled)
  1749. (unless company-search-mode
  1750. (company-uninstall-map)
  1751. (user-error "Company not in search mode")))
  1752. (defun company-search-candidates ()
  1753. "Start searching the completion candidates incrementally.
  1754. \\<company-search-map>Search can be controlled with the commands:
  1755. - `company-search-repeat-forward' (\\[company-search-repeat-forward])
  1756. - `company-search-repeat-backward' (\\[company-search-repeat-backward])
  1757. - `company-search-abort' (\\[company-search-abort])
  1758. - `company-search-delete-char' (\\[company-search-delete-char])
  1759. Regular characters are appended to the search string.
  1760. Customize `company-search-regexp-function' to change how the input
  1761. is interpreted when searching.
  1762. The command `company-search-toggle-filtering' (\\[company-search-toggle-filtering])
  1763. uses the search string to filter the completion candidates."
  1764. (interactive)
  1765. (company-search-mode 1))
  1766. (defvar company-filter-map
  1767. (let ((keymap (make-keymap)))
  1768. (define-key keymap [remap company-search-printing-char]
  1769. 'company-filter-printing-char)
  1770. (set-keymap-parent keymap company-search-map)
  1771. keymap)
  1772. "Keymap used for incrementally searching the completion candidates.")
  1773. (defun company-filter-candidates ()
  1774. "Start filtering the completion candidates incrementally.
  1775. This works the same way as `company-search-candidates' immediately
  1776. followed by `company-search-toggle-filtering'."
  1777. (interactive)
  1778. (company-search-mode 1)
  1779. (setq company-search-filtering t))
  1780. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1781. (defun company-select-next (&optional arg)
  1782. "Select the next candidate in the list.
  1783. With ARG, move by that many elements."
  1784. (interactive "p")
  1785. (when (company-manual-begin)
  1786. (company-set-selection (+ (or arg 1) company-selection))))
  1787. (defun company-select-previous (&optional arg)
  1788. "Select the previous candidate in the list.
  1789. With ARG, move by that many elements."
  1790. (interactive "p")
  1791. (company-select-next (if arg (- arg) -1)))
  1792. (defun company-select-next-or-abort (&optional arg)
  1793. "Select the next candidate if more than one, else abort
  1794. and invoke the normal binding.
  1795. With ARG, move by that many elements."
  1796. (interactive "p")
  1797. (if (> company-candidates-length 1)
  1798. (company-select-next arg)
  1799. (company-abort)
  1800. (company--unread-this-command-keys)))
  1801. (defun company-select-previous-or-abort (&optional arg)
  1802. "Select the previous candidate if more than one, else abort
  1803. and invoke the normal binding.
  1804. With ARG, move by that many elements."
  1805. (interactive "p")
  1806. (if (> company-candidates-length 1)
  1807. (company-select-previous arg)
  1808. (company-abort)
  1809. (company--unread-this-command-keys)))
  1810. (defun company-next-page ()
  1811. "Select the candidate one page further."
  1812. (interactive)
  1813. (when (company-manual-begin)
  1814. (if (and company-selection-wrap-around
  1815. (= company-selection (1- company-candidates-length)))
  1816. (company-set-selection 0)
  1817. (let (company-selection-wrap-around)
  1818. (company-set-selection (+ company-selection
  1819. company-tooltip-limit))))))
  1820. (defun company-previous-page ()
  1821. "Select the candidate one page earlier."
  1822. (interactive)
  1823. (when (company-manual-begin)
  1824. (if (and company-selection-wrap-around
  1825. (zerop company-selection))
  1826. (company-set-selection (1- company-candidates-length))
  1827. (let (company-selection-wrap-around)
  1828. (company-set-selection (- company-selection
  1829. company-tooltip-limit))))))
  1830. (defvar company-pseudo-tooltip-overlay)
  1831. (defvar company-tooltip-offset)
  1832. (defun company--inside-tooltip-p (event-col-row row height)
  1833. (let* ((ovl company-pseudo-tooltip-overlay)
  1834. (column (overlay-get ovl 'company-column))
  1835. (width (overlay-get ovl 'company-width))
  1836. (evt-col (car event-col-row))
  1837. (evt-row (cdr event-col-row)))
  1838. (and (>= evt-col column)
  1839. (< evt-col (+ column width))
  1840. (if (> height 0)
  1841. (and (> evt-row row)
  1842. (<= evt-row (+ row height) ))
  1843. (and (< evt-row row)
  1844. (>= evt-row (+ row height)))))))
  1845. (defun company--event-col-row (event)
  1846. (company--posn-col-row (event-start event)))
  1847. (defun company-select-mouse (event)
  1848. "Select the candidate picked by the mouse."
  1849. (interactive "e")
  1850. (let ((event-col-row (company--event-col-row event))
  1851. (ovl-row (company--row))
  1852. (ovl-height (and company-pseudo-tooltip-overlay
  1853. (min (overlay-get company-pseudo-tooltip-overlay
  1854. 'company-height)
  1855. company-candidates-length))))
  1856. (if (and ovl-height
  1857. (company--inside-tooltip-p event-col-row ovl-row ovl-height))
  1858. (progn
  1859. (company-set-selection (+ (cdr event-col-row)
  1860. (1- company-tooltip-offset)
  1861. (if (and (eq company-tooltip-offset-display 'lines)
  1862. (not (zerop company-tooltip-offset)))
  1863. -1 0)
  1864. (- ovl-row)
  1865. (if (< ovl-height 0)
  1866. (- 1 ovl-height)
  1867. 0)))
  1868. t)
  1869. (company-abort)
  1870. (company--unread-this-command-keys)
  1871. nil)))
  1872. (defun company-complete-mouse (event)
  1873. "Insert the candidate picked by the mouse."
  1874. (interactive "e")
  1875. (when (company-select-mouse event)
  1876. (company-complete-selection)))
  1877. (defun company-complete-selection ()
  1878. "Insert the selected candidate."
  1879. (interactive)
  1880. (when (company-manual-begin)
  1881. (let ((result (nth company-selection company-candidates)))
  1882. (company-finish result))))
  1883. (defun company-complete-common ()
  1884. "Insert the common part of all candidates."
  1885. (interactive)
  1886. (when (company-manual-begin)
  1887. (if (and (not (cdr company-candidates))
  1888. (equal company-common (car company-candidates)))
  1889. (company-complete-selection)
  1890. (company--insert-candidate company-common))))
  1891. (defun company-complete-common-or-cycle (&optional arg)
  1892. "Insert the common part of all candidates, or select the next one.
  1893. With ARG, move by that many elements."
  1894. (interactive "p")
  1895. (when (company-manual-begin)
  1896. (let ((tick (buffer-chars-modified-tick)))
  1897. (call-interactively 'company-complete-common)
  1898. (when (eq tick (buffer-chars-modified-tick))
  1899. (let ((company-selection-wrap-around t)
  1900. (current-prefix-arg arg))
  1901. (call-interactively 'company-select-next))))))
  1902. (defun company-indent-or-complete-common (arg)
  1903. "Indent the current line or region, or complete the common part."
  1904. (interactive "P")
  1905. (cond
  1906. ((use-region-p)
  1907. (indent-region (region-beginning) (region-end)))
  1908. ((memq indent-line-function
  1909. '(indent-relative indent-relative-maybe))
  1910. (company-complete-common))
  1911. ((let ((old-point (point))
  1912. (old-tick (buffer-chars-modified-tick))
  1913. (tab-always-indent t))
  1914. (indent-for-tab-command arg)
  1915. (when (and (eq old-point (point))
  1916. (eq old-tick (buffer-chars-modified-tick)))
  1917. (company-complete-common))))))
  1918. (defun company-select-next-if-tooltip-visible-or-complete-selection ()
  1919. "Insert selection if appropriate, or select the next candidate.
  1920. Insert selection if only preview is showing or only one candidate,
  1921. otherwise select the next candidate."
  1922. (interactive)
  1923. (if (and (company-tooltip-visible-p) (> company-candidates-length 1))
  1924. (call-interactively 'company-select-next)
  1925. (call-interactively 'company-complete-selection)))
  1926. ;;;###autoload
  1927. (defun company-complete ()
  1928. "Insert the common part of all candidates or the current selection.
  1929. The first time this is called, the common part is inserted, the second
  1930. time, or when the selection has been changed, the selected candidate is
  1931. inserted."
  1932. (interactive)
  1933. (when (company-manual-begin)
  1934. (if (or company-selection-changed
  1935. (and (eq real-last-command 'company-complete)
  1936. (eq last-command 'company-complete-common)))
  1937. (call-interactively 'company-complete-selection)
  1938. (call-interactively 'company-complete-common)
  1939. (when company-candidates
  1940. (setq this-command 'company-complete-common)))))
  1941. (defun company-complete-number (n)
  1942. "Insert the Nth candidate visible in the tooltip.
  1943. To show the number next to the candidates in some backends, enable
  1944. `company-show-numbers'. When called interactively, uses the last typed
  1945. character, stripping the modifiers. That character must be a digit."
  1946. (interactive
  1947. (list (let* ((type (event-basic-type last-command-event))
  1948. (char (if (characterp type)
  1949. ;; Number on the main row.
  1950. type
  1951. ;; Keypad number, if bound directly.
  1952. (car (last (string-to-list (symbol-name type))))))
  1953. (n (- char ?0)))
  1954. (if (zerop n) 10 n))))
  1955. (when (company-manual-begin)
  1956. (and (or (< n 1) (> n (- company-candidates-length
  1957. company-tooltip-offset)))
  1958. (user-error "No candidate number %d" n))
  1959. (cl-decf n)
  1960. (company-finish (nth (+ n company-tooltip-offset)
  1961. company-candidates))))
  1962. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1963. (defconst company-space-strings-limit 100)
  1964. (defconst company-space-strings
  1965. (let (lst)
  1966. (dotimes (i company-space-strings-limit)
  1967. (push (make-string (- company-space-strings-limit 1 i) ?\ ) lst))
  1968. (apply 'vector lst)))
  1969. (defun company-space-string (len)
  1970. (if (< len company-space-strings-limit)
  1971. (aref company-space-strings len)
  1972. (make-string len ?\ )))
  1973. (defun company-safe-substring (str from &optional to)
  1974. (let ((bis buffer-invisibility-spec))
  1975. (if (> from (string-width str))
  1976. ""
  1977. (with-temp-buffer
  1978. (setq buffer-invisibility-spec bis)
  1979. (insert str)
  1980. (move-to-column from)
  1981. (let ((beg (point)))
  1982. (if to
  1983. (progn
  1984. (move-to-column to)
  1985. (concat (buffer-substring beg (point))
  1986. (let ((padding (- to (current-column))))
  1987. (when (> padding 0)
  1988. (company-space-string padding)))))
  1989. (buffer-substring beg (point-max))))))))
  1990. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1991. (defvar-local company-last-metadata nil)
  1992. (defun company-fetch-metadata ()
  1993. (let ((selected (nth company-selection company-candidates)))
  1994. (unless (eq selected (car company-last-metadata))
  1995. (setq company-last-metadata
  1996. (cons selected (company-call-backend 'meta selected))))
  1997. (cdr company-last-metadata)))
  1998. (defun company-doc-buffer (&optional string)
  1999. (with-current-buffer (get-buffer-create "*company-documentation*")
  2000. (erase-buffer)
  2001. (fundamental-mode)
  2002. (when string
  2003. (save-excursion
  2004. (insert string)
  2005. (visual-line-mode)))
  2006. (current-buffer)))
  2007. (defvar company--electric-saved-window-configuration nil)
  2008. (defvar company--electric-commands
  2009. '(scroll-other-window scroll-other-window-down mwheel-scroll)
  2010. "List of Commands that won't break out of electric commands.")
  2011. (defun company--electric-restore-window-configuration ()
  2012. "Restore window configuration (after electric commands)."
  2013. (when (and company--electric-saved-window-configuration
  2014. (not (memq this-command company--electric-commands)))
  2015. (set-window-configuration company--electric-saved-window-configuration)
  2016. (setq company--electric-saved-window-configuration nil)))
  2017. (defmacro company--electric-do (&rest body)
  2018. (declare (indent 0) (debug t))
  2019. `(when (company-manual-begin)
  2020. (cl-assert (null company--electric-saved-window-configuration))
  2021. (setq company--electric-saved-window-configuration (current-window-configuration))
  2022. (let ((height (window-height))
  2023. (row (company--row)))
  2024. ,@body
  2025. (and (< (window-height) height)
  2026. (< (- (window-height) row 2) company-tooltip-limit)
  2027. (recenter (- (window-height) row 2))))))
  2028. (defun company--unread-this-command-keys ()
  2029. (when (> (length (this-command-keys)) 0)
  2030. (setq unread-command-events (nconc
  2031. (listify-key-sequence (this-command-keys))
  2032. unread-command-events))
  2033. (clear-this-command-keys t)))
  2034. (defun company-show-doc-buffer ()
  2035. "Temporarily show the documentation buffer for the selection."
  2036. (interactive)
  2037. (let (other-window-scroll-buffer)
  2038. (company--electric-do
  2039. (let* ((selected (nth company-selection company-candidates))
  2040. (doc-buffer (or (company-call-backend 'doc-buffer selected)
  2041. (user-error "No documentation available")))
  2042. start)
  2043. (when (consp doc-buffer)
  2044. (setq start (cdr doc-buffer)
  2045. doc-buffer (car doc-buffer)))
  2046. (setq other-window-scroll-buffer (get-buffer doc-buffer))
  2047. (let ((win (display-buffer doc-buffer t)))
  2048. (set-window-start win (if start start (point-min))))))))
  2049. (put 'company-show-doc-buffer 'company-keep t)
  2050. (defun company-show-location ()
  2051. "Temporarily display a buffer showing the selected candidate in context."
  2052. (interactive)
  2053. (let (other-window-scroll-buffer)
  2054. (company--electric-do
  2055. (let* ((selected (nth company-selection company-candidates))
  2056. (location (company-call-backend 'location selected))
  2057. (pos (or (cdr location) (user-error "No location available")))
  2058. (buffer (or (and (bufferp (car location)) (car location))
  2059. (find-file-noselect (car location) t))))
  2060. (setq other-window-scroll-buffer (get-buffer buffer))
  2061. (with-selected-window (display-buffer buffer t)
  2062. (save-restriction
  2063. (widen)
  2064. (if (bufferp (car location))
  2065. (goto-char pos)
  2066. (goto-char (point-min))
  2067. (forward-line (1- pos))))
  2068. (set-window-start nil (point)))))))
  2069. (put 'company-show-location 'company-keep t)
  2070. ;;; package functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2071. (defvar-local company-callback nil)
  2072. (defun company-remove-callback (&optional ignored)
  2073. (remove-hook 'company-completion-finished-hook company-callback t)
  2074. (remove-hook 'company-completion-cancelled-hook 'company-remove-callback t)
  2075. (remove-hook 'company-completion-finished-hook 'company-remove-callback t))
  2076. (defun company-begin-backend (backend &optional callback)
  2077. "Start a completion at point using BACKEND."
  2078. (interactive (let ((val (completing-read "Company backend: "
  2079. obarray
  2080. 'functionp nil "company-")))
  2081. (when val
  2082. (list (intern val)))))
  2083. (when (setq company-callback callback)
  2084. (add-hook 'company-completion-finished-hook company-callback nil t))
  2085. (add-hook 'company-completion-cancelled-hook 'company-remove-callback nil t)
  2086. (add-hook 'company-completion-finished-hook 'company-remove-callback nil t)
  2087. (setq company-backend backend)
  2088. ;; Return non-nil if active.
  2089. (or (company-manual-begin)
  2090. (user-error "Cannot complete at point")))
  2091. (defun company-begin-with (candidates
  2092. &optional prefix-length require-match callback)
  2093. "Start a completion at point.
  2094. CANDIDATES is the list of candidates to use and PREFIX-LENGTH is the length
  2095. of the prefix that already is in the buffer before point.
  2096. It defaults to 0.
  2097. CALLBACK is a function called with the selected result if the user
  2098. successfully completes the input.
  2099. Example: \(company-begin-with '\(\"foo\" \"foobar\" \"foobarbaz\"\)\)"
  2100. (let ((begin-marker (copy-marker (point) t)))
  2101. (company-begin-backend
  2102. (lambda (command &optional arg &rest ignored)
  2103. (pcase command
  2104. (`prefix
  2105. (when (equal (point) (marker-position begin-marker))
  2106. (buffer-substring (- (point) (or prefix-length 0)) (point))))
  2107. (`candidates
  2108. (all-completions arg candidates))
  2109. (`require-match
  2110. require-match)))
  2111. callback)))
  2112. (declare-function find-library-name "find-func")
  2113. (declare-function lm-version "lisp-mnt")
  2114. (defun company-version (&optional show-version)
  2115. "Get the Company version as string.
  2116. If SHOW-VERSION is non-nil, show the version in the echo area."
  2117. (interactive (list t))
  2118. (with-temp-buffer
  2119. (require 'find-func)
  2120. (insert-file-contents (find-library-name "company"))
  2121. (require 'lisp-mnt)
  2122. (if show-version
  2123. (message "Company version: %s" (lm-version))
  2124. (lm-version))))
  2125. (defun company-diag ()
  2126. "Pop a buffer with information about completions at point."
  2127. (interactive)
  2128. (let* ((bb company-backends)
  2129. (mode (symbol-name major-mode))
  2130. backend
  2131. (prefix (cl-loop for b in bb
  2132. thereis (let ((company-backend b))
  2133. (setq backend b)
  2134. (company-call-backend 'prefix))))
  2135. cc annotations)
  2136. (when (or (stringp prefix) (consp prefix))
  2137. (let ((company-backend backend))
  2138. (condition-case nil
  2139. (setq cc (company-call-backend 'candidates (company--prefix-str prefix))
  2140. annotations
  2141. (mapcar
  2142. (lambda (c) (cons c (company-call-backend 'annotation c)))
  2143. cc))
  2144. (error (setq annotations 'error)))))
  2145. (pop-to-buffer (get-buffer-create "*company-diag*"))
  2146. (setq buffer-read-only nil)
  2147. (erase-buffer)
  2148. (insert (format "Emacs %s (%s) of %s on %s"
  2149. emacs-version system-configuration
  2150. (format-time-string "%Y-%m-%d" emacs-build-time)
  2151. emacs-build-system))
  2152. (insert "\nCompany " (company-version) "\n\n")
  2153. (insert "company-backends: " (pp-to-string bb))
  2154. (insert "\n")
  2155. (insert "Used backend: " (pp-to-string backend))
  2156. (insert "\n")
  2157. (when (if (listp backend)
  2158. (memq 'company-capf backend)
  2159. (eq backend 'company-capf))
  2160. (insert "Value of c-a-p-f: "
  2161. (pp-to-string completion-at-point-functions)))
  2162. (insert "Major mode: " mode)
  2163. (insert "\n")
  2164. (insert "Prefix: " (pp-to-string prefix))
  2165. (insert "\n")
  2166. (insert "Completions:")
  2167. (unless cc (insert " none"))
  2168. (if (eq annotations 'error)
  2169. (insert "(error fetching)")
  2170. (save-excursion
  2171. (dolist (c annotations)
  2172. (insert "\n " (prin1-to-string (car c)))
  2173. (when (cdr c)
  2174. (insert " " (prin1-to-string (cdr c)))))))
  2175. (special-mode)))
  2176. ;;; pseudo-tooltip ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2177. (defvar-local company-pseudo-tooltip-overlay nil)
  2178. (defvar-local company-tooltip-offset 0)
  2179. (defun company-tooltip--lines-update-offset (selection num-lines limit)
  2180. (cl-decf limit 2)
  2181. (setq company-tooltip-offset
  2182. (max (min selection company-tooltip-offset)
  2183. (- selection -1 limit)))
  2184. (when (<= company-tooltip-offset 1)
  2185. (cl-incf limit)
  2186. (setq company-tooltip-offset 0))
  2187. (when (>= company-tooltip-offset (- num-lines limit 1))
  2188. (cl-incf limit)
  2189. (when (= selection (1- num-lines))
  2190. (cl-decf company-tooltip-offset)
  2191. (when (<= company-tooltip-offset 1)
  2192. (setq company-tooltip-offset 0)
  2193. (cl-incf limit))))
  2194. limit)
  2195. (defun company-tooltip--simple-update-offset (selection _num-lines limit)
  2196. (setq company-tooltip-offset
  2197. (if (< selection company-tooltip-offset)
  2198. selection
  2199. (max company-tooltip-offset
  2200. (- selection limit -1)))))
  2201. ;;; propertize
  2202. (defsubst company-round-tab (arg)
  2203. (* (/ (+ arg tab-width) tab-width) tab-width))
  2204. (defun company-plainify (str)
  2205. (let ((prefix (get-text-property 0 'line-prefix str)))
  2206. (when prefix ; Keep the original value unmodified, for no special reason.
  2207. (setq str (concat prefix str))
  2208. (remove-text-properties 0 (length str) '(line-prefix) str)))
  2209. (let* ((pieces (split-string str "\t"))
  2210. (copy pieces))
  2211. (while (cdr copy)
  2212. (setcar copy (company-safe-substring
  2213. (car copy) 0 (company-round-tab (string-width (car copy)))))
  2214. (pop copy))
  2215. (apply 'concat pieces)))
  2216. (defun company-fill-propertize (value annotation width selected left right)
  2217. (let* ((margin (length left))
  2218. (common (or (company-call-backend 'match value)
  2219. (if company-common
  2220. (string-width company-common)
  2221. 0)))
  2222. (_ (setq value (company-reformat (company--pre-render value))
  2223. annotation (and annotation (company--pre-render annotation t))))
  2224. (ann-ralign company-tooltip-align-annotations)
  2225. (ann-truncate (< width
  2226. (+ (length value) (length annotation)
  2227. (if ann-ralign 1 0))))
  2228. (ann-start (+ margin
  2229. (if ann-ralign
  2230. (if ann-truncate
  2231. (1+ (length value))
  2232. (- width (length annotation)))
  2233. (length value))))
  2234. (ann-end (min (+ ann-start (length annotation)) (+ margin width)))
  2235. (line (concat left
  2236. (if (or ann-truncate (not ann-ralign))
  2237. (company-safe-substring
  2238. (concat value
  2239. (when (and annotation ann-ralign) " ")
  2240. annotation)
  2241. 0 width)
  2242. (concat
  2243. (company-safe-substring value 0
  2244. (- width (length annotation)))
  2245. annotation))
  2246. right)))
  2247. (setq width (+ width margin (length right)))
  2248. ;; TODO: Use add-face-text-property in Emacs 24.4
  2249. (font-lock-append-text-property 0 width 'mouse-face
  2250. 'company-tooltip-mouse
  2251. line)
  2252. (when (< ann-start ann-end)
  2253. (font-lock-append-text-property ann-start ann-end 'face
  2254. (if selected
  2255. 'company-tooltip-annotation-selection
  2256. 'company-tooltip-annotation)
  2257. line))
  2258. (cl-loop
  2259. with width = (- width (length right))
  2260. for (comp-beg . comp-end) in (if (integerp common) `((0 . ,common)) common)
  2261. for inline-beg = (+ margin comp-beg)
  2262. for inline-end = (min (+ margin comp-end) width)
  2263. when (< inline-beg width)
  2264. do (font-lock-prepend-text-property inline-beg inline-end 'face
  2265. (if selected
  2266. 'company-tooltip-common-selection
  2267. 'company-tooltip-common)
  2268. line))
  2269. (when (let ((re (funcall company-search-regexp-function
  2270. company-search-string)))
  2271. (and (not (string= re ""))
  2272. (string-match re value (length company-prefix))))
  2273. (pcase-dolist (`(,mbeg . ,mend) (company--search-chunks))
  2274. (let ((beg (+ margin mbeg))
  2275. (end (+ margin mend))
  2276. (width (- width (length right))))
  2277. (when (< beg width)
  2278. (font-lock-prepend-text-property beg (min end width) 'face
  2279. (if selected
  2280. 'company-tooltip-search-selection
  2281. 'company-tooltip-search)
  2282. line)))))
  2283. (when selected
  2284. (font-lock-append-text-property 0 width 'face
  2285. 'company-tooltip-selection
  2286. line))
  2287. (font-lock-append-text-property 0 width 'face
  2288. 'company-tooltip
  2289. line)
  2290. line))
  2291. (defun company--search-chunks ()
  2292. (let ((md (match-data t))
  2293. res)
  2294. (if (<= (length md) 2)
  2295. (push (cons (nth 0 md) (nth 1 md)) res)
  2296. (while (setq md (nthcdr 2 md))
  2297. (when (car md)
  2298. (push (cons (car md) (cadr md)) res))))
  2299. res))
  2300. (defun company--pre-render (str &optional annotation-p)
  2301. (or (company-call-backend 'pre-render str annotation-p)
  2302. (progn
  2303. (when (or (text-property-not-all 0 (length str) 'face nil str)
  2304. (text-property-not-all 0 (length str) 'mouse-face nil str))
  2305. (setq str (copy-sequence str))
  2306. (remove-text-properties 0 (length str)
  2307. '(face nil font-lock-face nil mouse-face nil)
  2308. str))
  2309. str)))
  2310. (defun company--clean-string (str)
  2311. (replace-regexp-in-string
  2312. "\\([^[:graph:] ]\\)\\|\\(\ufeff\\)\\|[[:multibyte:]]"
  2313. (lambda (match)
  2314. (cond
  2315. ((match-beginning 1)
  2316. ;; FIXME: Better char for 'non-printable'?
  2317. ;; We shouldn't get any of these, but sometimes we might.
  2318. "\u2017")
  2319. ((match-beginning 2)
  2320. ;; Zero-width non-breakable space.
  2321. "")
  2322. ((> (string-width match) 1)
  2323. (concat
  2324. (make-string (1- (string-width match)) ?\ufeff)
  2325. match))
  2326. (t match)))
  2327. str))
  2328. ;;; replace
  2329. (defun company-buffer-lines (beg end)
  2330. (goto-char beg)
  2331. (let (lines lines-moved)
  2332. (while (and (not (eobp)) ; http://debbugs.gnu.org/19553
  2333. (> (setq lines-moved (vertical-motion 1)) 0)
  2334. (<= (point) end))
  2335. (let ((bound (min end (point))))
  2336. ;; A visual line can contain several physical lines (e.g. with outline's
  2337. ;; folding overlay). Take only the first one.
  2338. (push (buffer-substring beg
  2339. (save-excursion
  2340. (goto-char beg)
  2341. (re-search-forward "$" bound 'move)
  2342. (point)))
  2343. lines))
  2344. ;; One physical line can be displayed as several visual ones as well:
  2345. ;; add empty strings to the list, to even the count.
  2346. (dotimes (_ (1- lines-moved))
  2347. (push "" lines))
  2348. (setq beg (point)))
  2349. (unless (eq beg end)
  2350. (push (buffer-substring beg end) lines))
  2351. (nreverse lines)))
  2352. (defun company-modify-line (old new offset)
  2353. (concat (company-safe-substring old 0 offset)
  2354. new
  2355. (company-safe-substring old (+ offset (length new)))))
  2356. (defun company--show-numbers (numbered)
  2357. (format " %d" (mod numbered 10)))
  2358. (defsubst company--window-height ()
  2359. (if (fboundp 'window-screen-lines)
  2360. (floor (window-screen-lines))
  2361. (window-body-height)))
  2362. (defun company--window-width ()
  2363. (let ((ww (window-body-width)))
  2364. ;; Account for the line continuation column.
  2365. (when (zerop (cadr (window-fringes)))
  2366. (cl-decf ww))
  2367. (when (bound-and-true-p display-line-numbers)
  2368. (cl-decf ww (+ 2 (line-number-display-width))))
  2369. (unless (or (display-graphic-p)
  2370. (version< "24.3.1" emacs-version))
  2371. ;; Emacs 24.3 and earlier included margins
  2372. ;; in window-width when in TTY.
  2373. (cl-decf ww
  2374. (let ((margins (window-margins)))
  2375. (+ (or (car margins) 0)
  2376. (or (cdr margins) 0)))))
  2377. (when (and word-wrap
  2378. (version< emacs-version "24.4.51.5"))
  2379. ;; http://debbugs.gnu.org/19300
  2380. (cl-decf ww))
  2381. ;; whitespace-mode with newline-mark
  2382. (when (and buffer-display-table
  2383. (aref buffer-display-table ?\n))
  2384. (cl-decf ww (1- (length (aref buffer-display-table ?\n)))))
  2385. ww))
  2386. (defun company--replacement-string (lines old column nl &optional align-top)
  2387. (cl-decf column company-tooltip-margin)
  2388. (when (and align-top company-tooltip-flip-when-above)
  2389. (setq lines (reverse lines)))
  2390. (let ((width (length (car lines)))
  2391. (remaining-cols (- (+ (company--window-width) (window-hscroll))
  2392. column)))
  2393. (when (> width remaining-cols)
  2394. (cl-decf column (- width remaining-cols))))
  2395. (let ((offset (and (< column 0) (- column)))
  2396. new)
  2397. (when offset
  2398. (setq column 0))
  2399. (when align-top
  2400. ;; untouched lines first
  2401. (dotimes (_ (- (length old) (length lines)))
  2402. (push (pop old) new)))
  2403. ;; length into old lines.
  2404. (while old
  2405. (push (company-modify-line (pop old)
  2406. (company--offset-line (pop lines) offset)
  2407. column)
  2408. new))
  2409. ;; Append whole new lines.
  2410. (while lines
  2411. (push (concat (company-space-string column)
  2412. (company--offset-line (pop lines) offset))
  2413. new))
  2414. (let ((str (concat (when nl " \n")
  2415. (mapconcat 'identity (nreverse new) "\n")
  2416. "\n")))
  2417. (when nl (put-text-property 0 1 'cursor t str))
  2418. str)))
  2419. (defun company--offset-line (line offset)
  2420. (if (and offset line)
  2421. (substring line offset)
  2422. line))
  2423. (defun company--create-lines (selection limit)
  2424. (let ((len company-candidates-length)
  2425. (window-width (company--window-width))
  2426. lines
  2427. width
  2428. lines-copy
  2429. items
  2430. previous
  2431. remainder
  2432. scrollbar-bounds)
  2433. ;; Maybe clear old offset.
  2434. (when (< len (+ company-tooltip-offset limit))
  2435. (setq company-tooltip-offset 0))
  2436. ;; Scroll to offset.
  2437. (if (eq company-tooltip-offset-display 'lines)
  2438. (setq limit (company-tooltip--lines-update-offset selection len limit))
  2439. (company-tooltip--simple-update-offset selection len limit))
  2440. (cond
  2441. ((eq company-tooltip-offset-display 'scrollbar)
  2442. (setq scrollbar-bounds (company--scrollbar-bounds company-tooltip-offset
  2443. limit len)))
  2444. ((eq company-tooltip-offset-display 'lines)
  2445. (when (> company-tooltip-offset 0)
  2446. (setq previous (format "...(%d)" company-tooltip-offset)))
  2447. (setq remainder (- len limit company-tooltip-offset)
  2448. remainder (when (> remainder 0)
  2449. (setq remainder (format "...(%d)" remainder))))))
  2450. (cl-decf selection company-tooltip-offset)
  2451. (setq width (max (length previous) (length remainder))
  2452. lines (nthcdr company-tooltip-offset company-candidates)
  2453. len (min limit len)
  2454. lines-copy lines)
  2455. (cl-decf window-width (* 2 company-tooltip-margin))
  2456. (when scrollbar-bounds (cl-decf window-width))
  2457. (dotimes (_ len)
  2458. (let* ((value (pop lines-copy))
  2459. (annotation (company-call-backend 'annotation value)))
  2460. (setq value (company--clean-string value))
  2461. (when annotation
  2462. (setq annotation (company--clean-string annotation))
  2463. (when company-tooltip-align-annotations
  2464. ;; `lisp-completion-at-point' adds a space.
  2465. (setq annotation (comment-string-strip annotation t nil))))
  2466. (push (cons value annotation) items)
  2467. (setq width (max (+ (length value)
  2468. (if (and annotation company-tooltip-align-annotations)
  2469. (1+ (length annotation))
  2470. (length annotation)))
  2471. width))))
  2472. (setq width (min window-width
  2473. company-tooltip-maximum-width
  2474. (max company-tooltip-minimum-width
  2475. (if company-show-numbers
  2476. (+ 2 width)
  2477. width))))
  2478. (let ((items (nreverse items))
  2479. (numbered (if company-show-numbers 0 99999))
  2480. new)
  2481. (when previous
  2482. (push (company--scrollpos-line previous width) new))
  2483. (dotimes (i len)
  2484. (let* ((item (pop items))
  2485. (str (car item))
  2486. (annotation (cdr item))
  2487. (margin (company-space-string company-tooltip-margin))
  2488. (left margin)
  2489. (right margin)
  2490. (width width))
  2491. (when (< numbered 10)
  2492. (cl-decf width 2)
  2493. (cl-incf numbered)
  2494. (setf (if (eq company-show-numbers 'left) left right)
  2495. (concat (funcall company-show-numbers-function numbered)
  2496. margin)))
  2497. (push (concat
  2498. (company-fill-propertize str annotation
  2499. width (equal i selection)
  2500. left
  2501. right)
  2502. (when scrollbar-bounds
  2503. (company--scrollbar i scrollbar-bounds)))
  2504. new)))
  2505. (when remainder
  2506. (push (company--scrollpos-line remainder width) new))
  2507. (nreverse new))))
  2508. (defun company--scrollbar-bounds (offset limit length)
  2509. (when (> length limit)
  2510. (let* ((size (ceiling (* limit (float limit)) length))
  2511. (lower (floor (* limit (float offset)) length))
  2512. (upper (+ lower size -1)))
  2513. (cons lower upper))))
  2514. (defun company--scrollbar (i bounds)
  2515. (propertize " " 'face
  2516. (if (and (>= i (car bounds)) (<= i (cdr bounds)))
  2517. 'company-scrollbar-fg
  2518. 'company-scrollbar-bg)))
  2519. (defun company--scrollpos-line (text width)
  2520. (propertize (concat (company-space-string company-tooltip-margin)
  2521. (company-safe-substring text 0 width)
  2522. (company-space-string company-tooltip-margin))
  2523. 'face 'company-tooltip))
  2524. ;; show
  2525. (defun company--pseudo-tooltip-height ()
  2526. "Calculate the appropriate tooltip height.
  2527. Returns a negative number if the tooltip should be displayed above point."
  2528. (let* ((lines (company--row))
  2529. (below (- (company--window-height) 1 lines)))
  2530. (if (and (< below (min company-tooltip-minimum company-candidates-length))
  2531. (> lines below))
  2532. (- (max 3 (min company-tooltip-limit lines)))
  2533. (max 3 (min company-tooltip-limit below)))))
  2534. (defun company-pseudo-tooltip-show (row column selection)
  2535. (company-pseudo-tooltip-hide)
  2536. (let* ((height (company--pseudo-tooltip-height))
  2537. above)
  2538. (when (< height 0)
  2539. (setq row (+ row height -1)
  2540. above t))
  2541. (let (nl beg end ov args)
  2542. (save-excursion
  2543. (setq nl (< (move-to-window-line row) row)
  2544. beg (point)
  2545. end (save-excursion
  2546. (move-to-window-line (+ row (abs height)))
  2547. (point))
  2548. ov (make-overlay beg end nil t)
  2549. args (list (mapcar 'company-plainify
  2550. (company-buffer-lines beg end))
  2551. column nl above)))
  2552. (setq company-pseudo-tooltip-overlay ov)
  2553. (overlay-put ov 'company-replacement-args args)
  2554. (let ((lines (company--create-lines selection (abs height))))
  2555. (overlay-put ov 'company-display
  2556. (apply 'company--replacement-string lines args))
  2557. (overlay-put ov 'company-width (string-width (car lines))))
  2558. (overlay-put ov 'company-column column)
  2559. (overlay-put ov 'company-height height))))
  2560. (defun company-pseudo-tooltip-show-at-point (pos column-offset)
  2561. (let* ((col-row (company--col-row pos))
  2562. (col (- (car col-row) column-offset)))
  2563. (when (< col 0) (setq col 0))
  2564. (company-pseudo-tooltip-show (1+ (cdr col-row)) col company-selection)))
  2565. (defun company-pseudo-tooltip-edit (selection)
  2566. (let* ((height (overlay-get company-pseudo-tooltip-overlay 'company-height))
  2567. (lines (company--create-lines selection (abs height))))
  2568. (overlay-put company-pseudo-tooltip-overlay 'company-width
  2569. (string-width (car lines)))
  2570. (overlay-put company-pseudo-tooltip-overlay 'company-display
  2571. (apply 'company--replacement-string
  2572. lines
  2573. (overlay-get company-pseudo-tooltip-overlay
  2574. 'company-replacement-args)))))
  2575. (defun company-pseudo-tooltip-hide ()
  2576. (when company-pseudo-tooltip-overlay
  2577. (delete-overlay company-pseudo-tooltip-overlay)
  2578. (setq company-pseudo-tooltip-overlay nil)))
  2579. (defun company-pseudo-tooltip-hide-temporarily ()
  2580. (when (overlayp company-pseudo-tooltip-overlay)
  2581. (overlay-put company-pseudo-tooltip-overlay 'invisible nil)
  2582. (overlay-put company-pseudo-tooltip-overlay 'line-prefix nil)
  2583. (overlay-put company-pseudo-tooltip-overlay 'after-string nil)
  2584. (overlay-put company-pseudo-tooltip-overlay 'display nil)
  2585. (overlay-put company-pseudo-tooltip-overlay 'face nil)))
  2586. (defun company-pseudo-tooltip-unhide ()
  2587. (when company-pseudo-tooltip-overlay
  2588. (let* ((ov company-pseudo-tooltip-overlay)
  2589. (disp (overlay-get ov 'company-display)))
  2590. ;; Beat outline's folding overlays.
  2591. ;; And Flymake (53). And Flycheck (110).
  2592. (overlay-put ov 'priority 111)
  2593. ;; No (extra) prefix for the first line.
  2594. (overlay-put ov 'line-prefix "")
  2595. ;; `display' is better
  2596. ;; (http://debbugs.gnu.org/18285, http://debbugs.gnu.org/20847),
  2597. ;; but it doesn't work on 0-length overlays.
  2598. (if (< (overlay-start ov) (overlay-end ov))
  2599. (overlay-put ov 'display disp)
  2600. (overlay-put ov 'after-string disp)
  2601. (overlay-put ov 'invisible t))
  2602. (overlay-put ov 'face 'default)
  2603. (overlay-put ov 'window (selected-window)))))
  2604. (defun company-pseudo-tooltip-guard ()
  2605. (list
  2606. (save-excursion (beginning-of-visual-line))
  2607. (window-width)
  2608. (let ((ov company-pseudo-tooltip-overlay)
  2609. (overhang (save-excursion (end-of-visual-line)
  2610. (- (line-end-position) (point)))))
  2611. (when (>= (overlay-get ov 'company-height) 0)
  2612. (cons
  2613. (buffer-substring-no-properties (point) (overlay-start ov))
  2614. (when (>= overhang 0) overhang))))))
  2615. (defun company-pseudo-tooltip-frontend (command)
  2616. "`company-mode' frontend similar to a tooltip but based on overlays."
  2617. (cl-case command
  2618. (pre-command (company-pseudo-tooltip-hide-temporarily))
  2619. (post-command
  2620. (unless (when (overlayp company-pseudo-tooltip-overlay)
  2621. (let* ((ov company-pseudo-tooltip-overlay)
  2622. (old-height (overlay-get ov 'company-height))
  2623. (new-height (company--pseudo-tooltip-height)))
  2624. (and
  2625. (>= (* old-height new-height) 0)
  2626. (>= (abs old-height) (abs new-height))
  2627. (equal (company-pseudo-tooltip-guard)
  2628. (overlay-get ov 'company-guard)))))
  2629. ;; Redraw needed.
  2630. (company-pseudo-tooltip-show-at-point (point) (length company-prefix))
  2631. (overlay-put company-pseudo-tooltip-overlay
  2632. 'company-guard (company-pseudo-tooltip-guard)))
  2633. (company-pseudo-tooltip-unhide))
  2634. (hide (company-pseudo-tooltip-hide)
  2635. (setq company-tooltip-offset 0))
  2636. (update (when (overlayp company-pseudo-tooltip-overlay)
  2637. (company-pseudo-tooltip-edit company-selection)))))
  2638. (defun company-pseudo-tooltip-unless-just-one-frontend (command)
  2639. "`company-pseudo-tooltip-frontend', but not shown for single candidates."
  2640. (unless (and (eq command 'post-command)
  2641. (company--show-inline-p))
  2642. (company-pseudo-tooltip-frontend command)))
  2643. (defun company-pseudo-tooltip-unless-just-one-frontend-with-delay (command)
  2644. "`compandy-pseudo-tooltip-frontend', but shown after a delay.
  2645. Delay is determined by `company-tooltip-idle-delay'."
  2646. (defvar company-preview-overlay)
  2647. (when (and (memq command '(pre-command hide))
  2648. company-tooltip-timer)
  2649. (cancel-timer company-tooltip-timer)
  2650. (setq company-tooltip-timer nil))
  2651. (cl-case command
  2652. (post-command
  2653. (if (or company-tooltip-timer
  2654. (overlayp company-pseudo-tooltip-overlay))
  2655. (if (not (overlayp company-preview-overlay))
  2656. (company-pseudo-tooltip-unless-just-one-frontend command)
  2657. (let (company-tooltip-timer)
  2658. (company-call-frontends 'pre-command))
  2659. (company-call-frontends 'post-command))
  2660. (setq company-tooltip-timer
  2661. (run-with-timer company-tooltip-idle-delay nil
  2662. 'company-pseudo-tooltip-unless-just-one-frontend-with-delay
  2663. 'post-command))))
  2664. (t
  2665. (company-pseudo-tooltip-unless-just-one-frontend command))))
  2666. ;;; overlay ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2667. (defvar-local company-preview-overlay nil)
  2668. (defun company-preview-show-at-point (pos completion)
  2669. (company-preview-hide)
  2670. (setq completion (copy-sequence (company--pre-render completion)))
  2671. (font-lock-append-text-property 0 (length completion)
  2672. 'face 'company-preview
  2673. completion)
  2674. (font-lock-prepend-text-property 0 (length company-common)
  2675. 'face 'company-preview-common
  2676. completion)
  2677. ;; Add search string
  2678. (and (string-match (funcall company-search-regexp-function
  2679. company-search-string)
  2680. completion)
  2681. (pcase-dolist (`(,mbeg . ,mend) (company--search-chunks))
  2682. (font-lock-prepend-text-property mbeg mend
  2683. 'face 'company-preview-search
  2684. completion)))
  2685. (setq completion (company-strip-prefix completion))
  2686. (and (equal pos (point))
  2687. (not (equal completion ""))
  2688. (add-text-properties 0 1 '(cursor 1) completion))
  2689. (let* ((beg pos)
  2690. (pto company-pseudo-tooltip-overlay)
  2691. (ptf-workaround (and
  2692. pto
  2693. (char-before pos)
  2694. (eq pos (overlay-start pto)))))
  2695. ;; Try to accommodate for the pseudo-tooltip overlay,
  2696. ;; which may start at the same position if it's at eol.
  2697. (when ptf-workaround
  2698. (cl-decf beg)
  2699. (setq completion (concat (buffer-substring beg pos) completion)))
  2700. (setq company-preview-overlay (make-overlay beg pos))
  2701. (let ((ov company-preview-overlay))
  2702. (overlay-put ov (if ptf-workaround 'display 'after-string)
  2703. completion)
  2704. (overlay-put ov 'window (selected-window)))))
  2705. (defun company-preview-hide ()
  2706. (when company-preview-overlay
  2707. (delete-overlay company-preview-overlay)
  2708. (setq company-preview-overlay nil)))
  2709. (defun company-preview-frontend (command)
  2710. "`company-mode' frontend showing the selection as if it had been inserted."
  2711. (pcase command
  2712. (`pre-command (company-preview-hide))
  2713. (`post-command (company-preview-show-at-point (point)
  2714. (nth company-selection company-candidates)))
  2715. (`hide (company-preview-hide))))
  2716. (defun company-preview-if-just-one-frontend (command)
  2717. "`company-preview-frontend', but only shown for single candidates."
  2718. (when (or (not (eq command 'post-command))
  2719. (company--show-inline-p))
  2720. (company-preview-frontend command)))
  2721. (defun company--show-inline-p ()
  2722. (and (not (cdr company-candidates))
  2723. company-common
  2724. (not (eq t (compare-strings company-prefix nil nil
  2725. (car company-candidates) nil nil
  2726. t)))
  2727. (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
  2728. (string-prefix-p company-prefix company-common))))
  2729. (defun company-tooltip-visible-p ()
  2730. "Returns whether the tooltip is visible."
  2731. (when (overlayp company-pseudo-tooltip-overlay)
  2732. (not (overlay-get company-pseudo-tooltip-overlay 'invisible))))
  2733. (defun company-preview-common--show-p ()
  2734. "Returns whether the preview of common can be showed or not"
  2735. (and company-common
  2736. (or (eq (company-call-backend 'ignore-case) 'keep-prefix)
  2737. (string-prefix-p company-prefix company-common))))
  2738. (defun company-preview-common-frontend (command)
  2739. "`company-mode' frontend preview the common part of candidates."
  2740. (when (or (not (eq command 'post-command))
  2741. (company-preview-common--show-p))
  2742. (pcase command
  2743. (`pre-command (company-preview-hide))
  2744. (`post-command (company-preview-show-at-point (point) company-common))
  2745. (`hide (company-preview-hide)))))
  2746. ;;; echo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2747. (defvar-local company-echo-last-msg nil)
  2748. (defvar company-echo-timer nil)
  2749. (defvar company-echo-delay .01)
  2750. (defcustom company-echo-truncate-lines t
  2751. "Whether frontend messages written to the echo area should be truncated."
  2752. :type 'boolean
  2753. :package-version '(company . "0.9.3"))
  2754. (defun company-echo-show (&optional getter)
  2755. (when getter
  2756. (setq company-echo-last-msg (funcall getter)))
  2757. (let ((message-log-max nil)
  2758. (message-truncate-lines company-echo-truncate-lines))
  2759. (if company-echo-last-msg
  2760. (message "%s" company-echo-last-msg)
  2761. (message ""))))
  2762. (defun company-echo-show-soon (&optional getter)
  2763. (company-echo-cancel)
  2764. (setq company-echo-timer (run-with-timer 0 nil 'company-echo-show getter)))
  2765. (defun company-echo-cancel (&optional unset)
  2766. (when company-echo-timer
  2767. (cancel-timer company-echo-timer))
  2768. (when unset
  2769. (setq company-echo-timer nil)))
  2770. (defun company-echo-show-when-idle (&optional getter)
  2771. (company-echo-cancel)
  2772. (setq company-echo-timer
  2773. (run-with-idle-timer company-echo-delay nil 'company-echo-show getter)))
  2774. (defun company-echo-format ()
  2775. (let ((limit (window-body-width (minibuffer-window)))
  2776. (len -1)
  2777. ;; Roll to selection.
  2778. (candidates (nthcdr company-selection company-candidates))
  2779. (i (if company-show-numbers company-selection 99999))
  2780. comp msg)
  2781. (while candidates
  2782. (setq comp (company-reformat (company--clean-string (pop candidates)))
  2783. len (+ len 1 (length comp)))
  2784. (if (< i 10)
  2785. ;; Add number.
  2786. (progn
  2787. (setq comp (propertize (format "%d: %s" i comp)
  2788. 'face 'company-echo))
  2789. (cl-incf len 3)
  2790. (cl-incf i)
  2791. (add-text-properties 3 (+ 3 (string-width company-common))
  2792. '(face company-echo-common) comp))
  2793. (setq comp (propertize comp 'face 'company-echo))
  2794. (add-text-properties 0 (string-width company-common)
  2795. '(face company-echo-common) comp))
  2796. (if (>= len limit)
  2797. (setq candidates nil)
  2798. (push comp msg)))
  2799. (mapconcat 'identity (nreverse msg) " ")))
  2800. (defun company-echo-strip-common-format ()
  2801. (let ((limit (window-body-width (minibuffer-window)))
  2802. (len (+ (length company-prefix) 2))
  2803. ;; Roll to selection.
  2804. (candidates (nthcdr company-selection company-candidates))
  2805. (i (if company-show-numbers company-selection 99999))
  2806. msg comp)
  2807. (while candidates
  2808. (setq comp (company-strip-prefix (pop candidates))
  2809. len (+ len 2 (length comp)))
  2810. (when (< i 10)
  2811. ;; Add number.
  2812. (setq comp (format "%s (%d)" comp i))
  2813. (cl-incf len 4)
  2814. (cl-incf i))
  2815. (if (>= len limit)
  2816. (setq candidates nil)
  2817. (push (propertize comp 'face 'company-echo) msg)))
  2818. (concat (propertize company-prefix 'face 'company-echo-common) "{"
  2819. (mapconcat 'identity (nreverse msg) ", ")
  2820. "}")))
  2821. (defun company-echo-hide ()
  2822. (unless (equal company-echo-last-msg "")
  2823. (setq company-echo-last-msg "")
  2824. (company-echo-show)))
  2825. (defun company-echo-frontend (command)
  2826. "`company-mode' frontend showing the candidates in the echo area."
  2827. (pcase command
  2828. (`post-command (company-echo-show-soon 'company-echo-format))
  2829. (`hide (company-echo-hide))))
  2830. (defun company-echo-strip-common-frontend (command)
  2831. "`company-mode' frontend showing the candidates in the echo area."
  2832. (pcase command
  2833. (`post-command (company-echo-show-soon 'company-echo-strip-common-format))
  2834. (`hide (company-echo-hide))))
  2835. (defun company-echo-metadata-frontend (command)
  2836. "`company-mode' frontend showing the documentation in the echo area."
  2837. (pcase command
  2838. (`post-command (company-echo-show-when-idle 'company-fetch-metadata))
  2839. (`hide (company-echo-hide))))
  2840. (provide 'company)
  2841. ;;; company.el ends here