Klimi's new dotfiles with stow.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3217 строки
127 KiB

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