Path: blob/master/elisp/emacs-for-python/auto-complete/auto-complete.el
990 views
;;; auto-complete.el --- Auto Completion for GNU Emacs12;; Copyright (C) 2008, 2009, 2010 Tomohiro Matsuyama34;; Author: Tomohiro Matsuyama <[email protected]>5;; URL: http://cx4a.org/software/auto-complete6;; Keywords: completion, convenience7;; Version: 1.389;; This program is free software; you can redistribute it and/or modify10;; it under the terms of the GNU General Public License as published by11;; the Free Software Foundation, either version 3 of the License, or12;; (at your option) any later version.1314;; This program is distributed in the hope that it will be useful,15;; but WITHOUT ANY WARRANTY; without even the implied warranty of16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the17;; GNU General Public License for more details.1819;; You should have received a copy of the GNU General Public License20;; along with this program. If not, see <http://www.gnu.org/licenses/>.2122;;; Commentary:23;;24;; This extension provides a way to complete with popup menu like:25;;26;; def-!-27;; +-----------------+28;; |defun::::::::::::|29;; |defvar |30;; |defmacro |31;; | ... |32;; +-----------------+33;;34;; You can complete by typing and selecting menu.35;;36;; Entire documents are located in doc/ directory.37;; Take a look for information.38;;39;; Enjoy!4041;;; Code:42434445(eval-when-compile46(require 'cl))4748(require 'popup)4950;;;; Global stuff5152(defun ac-error (&optional var)53"Report an error and disable `auto-complete-mode'."54(ignore-errors55(message "auto-complete error: %s" var)56(auto-complete-mode -1)57var))58596061;;;; Customization6263(defgroup auto-complete nil64"Auto completion."65:group 'completion66:prefix "ac-")6768(defcustom ac-delay 0.169"Delay to completions will be available."70:type 'float71:group 'auto-complete)7273(defcustom ac-auto-show-menu 0.874"Non-nil means completion menu will be automatically shown."75:type '(choice (const :tag "Yes" t)76(const :tag "Never" nil)77(float :tag "Timer"))78:group 'auto-complete)7980(defcustom ac-show-menu-immediately-on-auto-complete t81"Non-nil means menu will be showed immediately on `auto-complete'."82:type 'boolean83:group 'auto-complete)8485(defcustom ac-expand-on-auto-complete t86"Non-nil means expand whole common part on first time `auto-complete'."87:type 'boolean88:group 'auto-complete)8990(defcustom ac-disable-faces '(font-lock-comment-face font-lock-string-face font-lock-doc-face)91"Non-nil means disable automatic completion on specified faces."92:type '(repeat symbol)93:group 'auto-complete)9495(defcustom ac-stop-flymake-on-completing t96"Non-nil means disble flymake temporarily on completing."97:type 'boolean98:group 'auto-complete)99100(defcustom ac-use-fuzzy t101"Non-nil means use fuzzy matching."102:type 'boolean103:group 'auto-complete)104105(defcustom ac-fuzzy-cursor-color "red"106"Cursor color in fuzzy mode."107:type 'string108:group 'auto-complete)109110(defcustom ac-use-comphist t111"Non-nil means use intelligent completion history."112:type 'boolean113:group 'auto-complete)114115(defcustom ac-comphist-threshold 0.7116"Percentage of ignoring low scored candidates."117:type 'float118:group 'auto-complete)119120(defcustom ac-comphist-file121(expand-file-name (concat (if (boundp 'user-emacs-directory)122user-emacs-directory123"~/.emacs.d/")124"/ac-comphist.dat"))125"Completion history file name."126:type 'string127:group 'auto-complete)128129(defcustom ac-use-quick-help t130"Non-nil means use quick help."131:type 'boolean132:group 'auto-complete)133134(defcustom ac-quick-help-delay 1.5135"Delay to show quick help."136:type 'float137:group 'auto-complete)138139(defcustom ac-menu-height 10140"Max height of candidate menu."141:type 'integer142:group 'auto-complete)143(defvaralias 'ac-candidate-menu-height 'ac-menu-height)144145(defcustom ac-quick-help-height 20146"Max height of quick help."147:type 'integer148:group 'auto-complete)149150(defcustom ac-quick-help-prefer-x t151"Prefer X tooltip than overlay popup for displaying quick help."152:type 'boolean153:group 'auto-complete)154155(defcustom ac-candidate-limit nil156"Limit number of candidates. Non-integer means no limit."157:type 'integer158:group 'auto-complete)159(defvaralias 'ac-candidate-max 'ac-candidate-limit)160161(defcustom ac-modes162'(emacs-lisp-mode163lisp-interaction-mode164c-mode cc-mode c++-mode165java-mode clojure-mode scala-mode166scheme-mode167ocaml-mode tuareg-mode168perl-mode cperl-mode python-mode ruby-mode169ecmascript-mode javascript-mode js-mode js2-mode php-mode css-mode170makefile-mode sh-mode fortran-mode f90-mode ada-mode171xml-mode sgml-mode)172"Major modes `auto-complete-mode' can run on."173:type '(repeat symbol)174:group 'auto-complete)175176(defcustom ac-compatible-packages-regexp177"^ac-"178"Regexp to indicate what packages can work with auto-complete."179:type 'string180:group 'auto-complete)181182(defcustom ac-trigger-commands183'(self-insert-command)184"Trigger commands that specify whether `auto-complete' should start or not."185:type '(repeat symbol)186:group 'auto-complete)187188(defcustom ac-trigger-commands-on-completing189'(delete-backward-char190backward-delete-char191backward-delete-char-untabify)192"Trigger commands that specify whether `auto-complete' should continue or not."193:type '(repeat symbol)194:group 'auto-complete)195196(defcustom ac-trigger-key nil197"Non-nil means `auto-complete' will start by typing this key.198If you specify this TAB, for example, `auto-complete' will start by typing TAB,199and if there is no completions, an original command will be fallbacked."200:type 'string201:group 'auto-complete202:set (lambda (symbol value)203(set-default symbol value)204(when (and value205(fboundp 'ac-set-trigger-key))206(ac-set-trigger-key value))))207208(defcustom ac-auto-start 2209"Non-nil means completion will be started automatically.210Positive integer means if a length of a word you entered is larger than the value,211completion will be started automatically.212If you specify `nil', never be started automatically."213:type '(choice (const :tag "Yes" t)214(const :tag "Never" nil)215(integer :tag "Require"))216:group 'auto-complete)217218(defcustom ac-ignores nil219"List of string to ignore completion."220:type '(repeat string)221:group 'auto-complete)222223(defcustom ac-ignore-case 'smart224"Non-nil means auto-complete ignores case.225If this value is `smart', auto-complete ignores case only when226a prefix doen't contain any upper case letters."227:type '(choice (const :tag "Yes" t)228(const :tag "Smart" smart)229(const :tag "No" nil))230:group 'auto-complete)231232(defcustom ac-dwim t233"Non-nil means `auto-complete' works based on Do What I Mean."234:type 'boolean235:group 'auto-complete)236237(defcustom ac-use-menu-map nil238"Non-nil means a special keymap `ac-menu-map' on completing menu will be used."239:type 'boolean240:group 'auto-complete)241242(defcustom ac-use-overriding-local-map nil243"Non-nil means `overriding-local-map' will be used to hack for overriding key events on auto-copletion."244:type 'boolean245:group 'auto-complete)246247(defface ac-completion-face248'((t (:foreground "darkgray" :underline t)))249"Face for inline completion"250:group 'auto-complete)251252(defface ac-candidate-face253'((t (:background "lightgray" :foreground "black")))254"Face for candidate."255:group 'auto-complete)256257(defface ac-selection-face258'((t (:background "steelblue" :foreground "white")))259"Face for selected candidate."260:group 'auto-complete)261262(defvar auto-complete-mode-hook nil263"Hook for `auto-complete-mode'.")264265266267;;;; Internal variables268269(defvar auto-complete-mode nil270"Dummy variable to suppress compiler warnings.")271272(defvar ac-cursor-color nil273"Old cursor color.")274275(defvar ac-inline nil276"Inline completion instance.")277278(defvar ac-menu nil279"Menu instance.")280281(defvar ac-show-menu nil282"Flag to show menu on timer tick.")283284(defvar ac-last-completion nil285"Cons of prefix marker and selected item of last completion.")286287(defvar ac-quick-help nil288"Quick help instance")289290(defvar ac-completing nil291"Non-nil means `auto-complete-mode' is now working on completion.")292293(defvar ac-buffer nil294"Buffer where auto-complete is started.")295296(defvar ac-point nil297"Start point of prefix.")298299(defvar ac-last-point nil300"Last point of updating pattern.")301302(defvar ac-prefix nil303"Prefix string.")304(defvaralias 'ac-target 'ac-prefix)305306(defvar ac-selected-candidate nil307"Last selected candidate.")308309(defvar ac-common-part nil310"Common part string of meaningful candidates.311If there is no common part, this will be nil.")312313(defvar ac-whole-common-part nil314"Common part string of whole candidates.315If there is no common part, this will be nil.")316317(defvar ac-prefix-overlay nil318"Overlay for prefix string.")319320(defvar ac-timer nil321"Completion idle timer.")322323(defvar ac-show-menu-timer nil324"Show menu idle timer.")325326(defvar ac-quick-help-timer nil327"Quick help idle timer.")328329(defvar ac-triggered nil330"Flag to update.")331332(defvar ac-limit nil333"Limit number of candidates for each sources.")334335(defvar ac-candidates nil336"Current candidates.")337338(defvar ac-candidates-cache nil339"Candidates cache for individual sources.")340341(defvar ac-fuzzy-enable nil342"Non-nil means fuzzy matching is enabled.")343344(defvar ac-dwim-enable nil345"Non-nil means DWIM completion will be allowed.")346347(defvar ac-mode-map (make-sparse-keymap)348"Auto-complete mode map. It is also used for trigger key command. See also `ac-trigger-key'.")349350(defvar ac-completing-map351(let ((map (make-sparse-keymap)))352(define-key map "\t" 'ac-expand)353(define-key map "\r" 'ac-complete)354(define-key map (kbd "M-TAB") 'auto-complete)355(define-key map "\C-s" 'ac-isearch)356357(define-key map "\M-n" 'ac-next)358(define-key map "\M-p" 'ac-previous)359(define-key map [down] 'ac-next)360(define-key map [up] 'ac-previous)361362(define-key map [f1] 'ac-help)363(define-key map [M-f1] 'ac-persist-help)364(define-key map (kbd "C-?") 'ac-help)365(define-key map (kbd "C-M-?") 'ac-persist-help)366367(define-key map [C-down] 'ac-quick-help-scroll-down)368(define-key map [C-up] 'ac-quick-help-scroll-up)369(define-key map "\C-\M-n" 'ac-quick-help-scroll-down)370(define-key map "\C-\M-p" 'ac-quick-help-scroll-up)371372(dotimes (i 9)373(let ((symbol (intern (format "ac-complete-%d" (1+ i)))))374(fset symbol375`(lambda ()376(interactive)377(when (and (ac-menu-live-p) (popup-select ac-menu ,i))378(ac-complete))))379(define-key map (read-kbd-macro (format "M-%s" (1+ i))) symbol)))380381map)382"Keymap for completion.")383(defvaralias 'ac-complete-mode-map 'ac-completing-map)384385(defvar ac-menu-map386(let ((map (make-sparse-keymap)))387(define-key map "\C-n" 'ac-next)388(define-key map "\C-p" 'ac-previous)389(set-keymap-parent map ac-completing-map)390map)391"Keymap for completion on completing menu.")392393(defvar ac-current-map394(let ((map (make-sparse-keymap)))395(set-keymap-parent map ac-completing-map)396map))397398(defvar ac-match-function 'all-completions399"Default match function.")400401(defvar ac-prefix-definitions402'((symbol . ac-prefix-symbol)403(file . ac-prefix-file)404(valid-file . ac-prefix-valid-file)405(c-dot . ac-prefix-c-dot)406(c-dot-ref . ac-prefix-c-dot-ref))407"Prefix definitions for common use.")408409(defvar ac-sources '(ac-source-words-in-same-mode-buffers)410"Sources for completion.")411(make-variable-buffer-local 'ac-sources)412413(defvar ac-compiled-sources nil414"Compiled source of `ac-sources'.")415416(defvar ac-current-sources nil417"Current working sources. This is sublist of `ac-compiled-sources'.")418419(defvar ac-omni-completion-sources nil420"Do not use this anymore.")421422(defvar ac-current-prefix-def nil)423424(defvar ac-ignoring-prefix-def nil)425426427428;;;; Intelligent completion history429430(defvar ac-comphist nil431"Database of completion history.")432433(defsubst ac-comphist-make-tab ()434(make-hash-table :test 'equal))435436(defsubst ac-comphist-tab (db)437(nth 0 db))438439(defsubst ac-comphist-cache (db)440(nth 1 db))441442(defun ac-comphist-make (&optional tab)443(list (or tab (ac-comphist-make-tab)) (make-hash-table :test 'equal :weakness t)))444445(defun ac-comphist-get (db string &optional create)446(let* ((tab (ac-comphist-tab db))447(index (gethash string tab)))448(when (and create (null index))449(setq index (make-vector (length string) 0))450(puthash string index tab))451index))452453(defun ac-comphist-add (db string prefix)454(setq prefix (min prefix (1- (length string))))455(when (<= 0 prefix)456(setq string (substring-no-properties string))457(let ((stat (ac-comphist-get db string t)))458(incf (aref stat prefix))459(remhash string (ac-comphist-cache db)))))460461(defun ac-comphist-score (db string prefix)462(setq prefix (min prefix (1- (length string))))463(if (<= 0 prefix)464(let ((cache (gethash string (ac-comphist-cache db))))465(or (and cache (aref cache prefix))466(let ((stat (ac-comphist-get db string))467(score 0.0))468(when stat469(loop for p from 0 below (length string)470;; sigmoid function471with a = 5472with d = (/ 6.0 a)473for x = (- d (abs (- prefix p)))474for r = (/ 1.0 (1+ (exp (* (- a) x))))475do476(incf score (* (aref stat p) r))))477;; Weight by distance478(incf score (max 0.0 (- 0.3 (/ (- (length string) prefix) 100.0))))479(unless cache480(setq cache (make-vector (length string) nil))481(puthash string cache (ac-comphist-cache db)))482(aset cache prefix score)483score)))4840.0))485486(defun ac-comphist-sort (db collection prefix &optional threshold)487(let (result488(n 0)489(total 0)490(cur 0))491(setq result (mapcar (lambda (a)492(when (and cur threshold)493(if (>= cur (* total threshold))494(setq cur nil)495(incf n)496(incf cur (cdr a))))497(car a))498(sort (mapcar (lambda (string)499(let ((score (ac-comphist-score db string prefix)))500(incf total score)501(cons string score)))502collection)503(lambda (a b) (< (cdr b) (cdr a))))))504(if threshold505(cons n result)506result)))507508(defun ac-comphist-serialize (db)509(let (alist)510(maphash (lambda (k v)511(push (cons k v) alist))512(ac-comphist-tab db))513(list alist)))514515(defun ac-comphist-deserialize (sexp)516(condition-case nil517(ac-comphist-make (let ((tab (ac-comphist-make-tab)))518(mapc (lambda (cons)519(puthash (car cons) (cdr cons) tab))520(nth 0 sexp))521tab))522(error (message "Invalid comphist db.") nil)))523524(defun ac-comphist-init ()525(ac-comphist-load)526(add-hook 'kill-emacs-hook 'ac-comphist-save))527528(defun ac-comphist-load ()529(interactive)530(let ((db (if (file-exists-p ac-comphist-file)531(ignore-errors532(with-temp-buffer533(insert-file-contents ac-comphist-file)534(goto-char (point-min))535(ac-comphist-deserialize (read (current-buffer))))))))536(setq ac-comphist (or db (ac-comphist-make)))))537538(defun ac-comphist-save ()539(interactive)540(require 'pp)541(ignore-errors542(with-temp-buffer543(pp (ac-comphist-serialize ac-comphist) (current-buffer))544(write-region (point-min) (point-max) ac-comphist-file))))545546547548;;;; Auto completion internals549550(defun ac-menu-at-wrapper-line-p ()551"Return non-nil if current line is long and wrapped to next visual line."552(and (not truncate-lines)553(eq (line-beginning-position)554(save-excursion555(vertical-motion 1)556(line-beginning-position)))))557558(defun ac-prefix-symbol ()559"Default prefix definition function."560(require 'thingatpt)561(car-safe (bounds-of-thing-at-point 'symbol)))562(defalias 'ac-prefix-default 'ac-prefix-symbol)563564(defun ac-prefix-file ()565"File prefix."566(let ((point (re-search-backward "[\"<>' \t\r\n]" nil t)))567(if point (1+ point))))568569(defun ac-prefix-valid-file ()570"Existed (or to be existed) file prefix."571(let* ((line-beg (line-beginning-position))572(end (point))573(start (or (let ((point (re-search-backward "[\"<>'= \t\r\n]" line-beg t)))574(if point (1+ point)))575line-beg))576(file (buffer-substring start end)))577(if (and file (or (string-match "^/" file)578(and (setq file (and (string-match "^[^/]*/" file)579(match-string 0 file)))580(file-directory-p file))))581start)))582583(defun ac-prefix-c-dot ()584"C-like languages dot(.) prefix."585(if (re-search-backward "\\.\\(\\(?:[a-zA-Z0-9][_a-zA-Z0-9]*\\)?\\)\\=" nil t)586(match-beginning 1)))587588(defun ac-prefix-c-dot-ref ()589"C-like languages dot(.) and reference(->) prefix."590(if (re-search-backward "\\(?:\\.\\|->\\)\\(\\(?:[a-zA-Z0-9][_a-zA-Z0-9]*\\)?\\)\\=" nil t)591(match-beginning 1)))592593(defun ac-define-prefix (name prefix)594"Define new prefix definition.595You can not use it in source definition like (prefix . `NAME')."596(push (cons name prefix) ac-prefix-definitions))597598(defun ac-match-substring (prefix candidates)599(loop with regexp = (regexp-quote prefix)600for candidate in candidates601if (string-match regexp candidate)602collect candidate))603604(defsubst ac-source-entity (source)605(if (symbolp source)606(symbol-value source)607source))608609(defun ac-source-available-p (source)610(if (and (symbolp source)611(get source 'available))612(eq (get source 'available) t)613(let* ((src (ac-source-entity source))614(avail-pair (assq 'available src))615(avail-cond (cdr avail-pair))616(available (and (if avail-pair617(cond618((symbolp avail-cond)619(funcall avail-cond))620((listp avail-cond)621(eval avail-cond)))622t)623(loop for feature in (assoc-default 'depends src)624unless (require feature nil t) return nil625finally return t))))626(if (symbolp source)627(put source 'available (if available t 'no)))628available)))629630(defun ac-compile-sources (sources)631"Compiled `SOURCES' into expanded sources style."632(loop for source in sources633if (ac-source-available-p source)634do635(setq source (ac-source-entity source))636(flet ((add-attribute (name value &optional append) (add-to-list 'source (cons name value) append)))637;; prefix638(let* ((prefix (assoc 'prefix source))639(real (assoc-default (cdr prefix) ac-prefix-definitions)))640(cond641(real642(add-attribute 'prefix real))643((null prefix)644(add-attribute 'prefix 'ac-prefix-default))))645;; match646(let ((match (assq 'match source)))647(cond648((eq (cdr match) 'substring)649(setcdr match 'ac-match-substring)))))650and collect source))651652(defun ac-compiled-sources ()653(or ac-compiled-sources654(setq ac-compiled-sources655(ac-compile-sources ac-sources))))656657(defsubst ac-menu-live-p ()658(popup-live-p ac-menu))659660(defun ac-menu-create (point width height)661(setq ac-menu662(popup-create point width height663:around t664:face 'ac-candidate-face665:selection-face 'ac-selection-face666:symbol t667:scroll-bar t668:margin-left 1)))669670(defun ac-menu-delete ()671(when ac-menu672(popup-delete ac-menu)673(setq ac-menu)))674675(defsubst ac-inline-marker ()676(nth 0 ac-inline))677678(defsubst ac-inline-overlay ()679(nth 1 ac-inline))680681(defsubst ac-inline-live-p ()682(and ac-inline (ac-inline-overlay) t))683684(defun ac-inline-show (point string)685(unless ac-inline686(setq ac-inline (list (make-marker) nil)))687(save-excursion688(let ((overlay (ac-inline-overlay))689(width 0)690(string-width (string-width string))691(length 0)692(original-string string))693;; Calculate string space to show completion694(goto-char point)695(let (c)696(while (and (not (eolp))697(< width string-width)698(setq c (char-after))699(not (eq c ?\t))) ; special case for tab700(incf width (char-width c))701(incf length)702(forward-char)))703704;; Show completion705(goto-char point)706(cond707((= width 0)708(set-marker (ac-inline-marker) point)709(let ((buffer-undo-list t))710(insert " "))711(setq width 1712length 1))713((<= width string-width)714;; No space to show715;; Do nothing716)717((> width string-width)718;; Need to fill space719(setq string (concat string (make-string (- width string-width) ? )))))720(setq string (propertize string 'face 'ac-completion-face))721(if overlay722(progn723(move-overlay overlay point (+ point length))724(overlay-put overlay 'invisible nil))725(setq overlay (make-overlay point (+ point length)))726(setf (nth 1 ac-inline) overlay)727(overlay-put overlay 'priority 9999)728;; Help prefix-overlay in some cases729(overlay-put overlay 'keymap ac-current-map))730(overlay-put overlay 'display (substring string 0 1))731;; TODO no width but char732(overlay-put overlay 'after-string (substring string 1))733(overlay-put overlay 'string original-string))))734735(defun ac-inline-delete ()736(when (ac-inline-live-p)737(ac-inline-hide)738(delete-overlay (ac-inline-overlay))739(setq ac-inline nil)))740741(defun ac-inline-hide ()742(when (ac-inline-live-p)743(let ((overlay (ac-inline-overlay))744(marker (ac-inline-marker))745(buffer-undo-list t))746(when overlay747(when (marker-position marker)748(save-excursion749(goto-char marker)750(delete-char 1)751(set-marker marker nil)))752(move-overlay overlay (point-min) (point-min))753(overlay-put overlay 'invisible t)754(overlay-put overlay 'display nil)755(overlay-put overlay 'after-string nil)))))756757(defun ac-inline-update ()758(if (and ac-completing ac-prefix (stringp ac-common-part))759(let ((common-part-length (length ac-common-part))760(prefix-length (length ac-prefix)))761(if (> common-part-length prefix-length)762(progn763(ac-inline-hide)764(ac-inline-show (point) (substring ac-common-part prefix-length)))765(ac-inline-delete)))766(ac-inline-delete)))767768(defun ac-put-prefix-overlay ()769(unless ac-prefix-overlay770(let (newline)771;; Insert newline to make sure that cursor always on the overlay772(when (and (eq ac-point (point-max))773(eq ac-point (point)))774(popup-save-buffer-state775(insert "\n"))776(setq newline t))777(setq ac-prefix-overlay (make-overlay ac-point (1+ (point)) nil t t))778(overlay-put ac-prefix-overlay 'priority 9999)779(overlay-put ac-prefix-overlay 'keymap (make-sparse-keymap))780(overlay-put ac-prefix-overlay 'newline newline))))781782(defun ac-remove-prefix-overlay ()783(when ac-prefix-overlay784(when (overlay-get ac-prefix-overlay 'newline)785;; Remove inserted newline786(popup-save-buffer-state787(goto-char (point-max))788(if (eq (char-before) ?\n)789(delete-char -1))))790(delete-overlay ac-prefix-overlay)))791792(defun ac-activate-completing-map ()793(if (and ac-show-menu ac-use-menu-map)794(set-keymap-parent ac-current-map ac-menu-map))795(when (and ac-use-overriding-local-map796(null overriding-terminal-local-map))797(setq overriding-terminal-local-map ac-current-map))798(when ac-prefix-overlay799(set-keymap-parent (overlay-get ac-prefix-overlay 'keymap) ac-current-map)))800801(defun ac-deactivate-completing-map ()802(set-keymap-parent ac-current-map ac-completing-map)803(when (and ac-use-overriding-local-map804(eq overriding-terminal-local-map ac-current-map))805(setq overriding-terminal-local-map nil))806(when ac-prefix-overlay807(set-keymap-parent (overlay-get ac-prefix-overlay 'keymap) nil)))808809(defsubst ac-selected-candidate ()810(if ac-menu811(popup-selected-item ac-menu)))812813(defun ac-prefix (requires ignore-list)814(loop with current = (point)815with point816with prefix-def817with sources818for source in (ac-compiled-sources)819for prefix = (assoc-default 'prefix source)820for req = (or (assoc-default 'requires source) requires 1)821822if (null prefix-def)823do824(unless (member prefix ignore-list)825(save-excursion826(setq point (cond827((symbolp prefix)828(funcall prefix))829((stringp prefix)830(and (re-search-backward (concat prefix "\\=") nil t)831(or (match-beginning 1) (match-beginning 0))))832((stringp (car-safe prefix))833(let ((regexp (nth 0 prefix))834(end (nth 1 prefix))835(group (nth 2 prefix)))836(and (re-search-backward (concat regexp "\\=") nil t)837(funcall (if end 'match-end 'match-beginning)838(or group 0)))))839(t840(eval prefix))))841(if (and point842(integerp req)843(< (- current point) req))844(setq point nil))845(if point846(setq prefix-def prefix))))847848if (equal prefix prefix-def) do (push source sources)849850finally return851(and point (list prefix-def point (nreverse sources)))))852853(defun ac-init ()854"Initialize current sources to start completion."855(setq ac-candidates-cache nil)856(loop for source in ac-current-sources857for function = (assoc-default 'init source)858if function do859(save-excursion860(cond861((functionp function)862(funcall function))863(t864(eval function))))))865866(defun ac-candidates-1 (source)867(let* ((do-cache (assq 'cache source))868(function (assoc-default 'candidates source))869(action (assoc-default 'action source))870(document (assoc-default 'document source))871(symbol (assoc-default 'symbol source))872(ac-limit (or (assoc-default 'limit source) ac-limit))873(face (or (assoc-default 'face source) (assoc-default 'candidate-face source)))874(selection-face (assoc-default 'selection-face source))875(cache (and do-cache (assq source ac-candidates-cache)))876(candidates (cdr cache)))877(unless cache878(setq candidates (save-excursion879(cond880((functionp function)881(funcall function))882(t883(eval function)))))884;; Convert (name value) format candidates into name with text properties.885(setq candidates (mapcar (lambda (candidate)886(if (consp candidate)887(propertize (car candidate) 'value (cdr candidate))888candidate))889candidates))890(when do-cache891(push (cons source candidates) ac-candidates-cache)))892(setq candidates (funcall (or (assoc-default 'match source)893ac-match-function)894ac-prefix candidates))895;; Remove extra items regarding to ac-limit896(if (and (integerp ac-limit) (> ac-limit 1) (> (length candidates) ac-limit))897(setcdr (nthcdr (1- ac-limit) candidates) nil))898;; Put candidate properties899(setq candidates (mapcar (lambda (candidate)900(popup-item-propertize candidate901'action action902'symbol symbol903'document document904'popup-face face905'selection-face selection-face))906candidates))907candidates))908909(defun ac-candidates ()910"Produce candidates for current sources."911(loop with completion-ignore-case = (or (eq ac-ignore-case t)912(and (eq ac-ignore-case 'smart)913(let ((case-fold-search nil)) (not (string-match "[[:upper:]]" ac-prefix)))))914with case-fold-search = completion-ignore-case915with prefix-len = (length ac-prefix)916for source in ac-current-sources917append (ac-candidates-1 source) into candidates918finally return919(progn920(delete-dups candidates)921(if (and ac-use-comphist ac-comphist)922(if ac-show-menu923(let* ((pair (ac-comphist-sort ac-comphist candidates prefix-len ac-comphist-threshold))924(n (car pair))925(result (cdr pair))926(cons (if (> n 0) (nthcdr (1- n) result)))927(cdr (cdr cons)))928(if cons (setcdr cons nil))929(setq ac-common-part (try-completion ac-prefix result))930(setq ac-whole-common-part (try-completion ac-prefix candidates))931(if cons (setcdr cons cdr))932result)933(setq candidates (ac-comphist-sort ac-comphist candidates prefix-len))934(setq ac-common-part (if candidates (popup-x-to-string (car candidates))))935(setq ac-whole-common-part (try-completion ac-prefix candidates))936candidates)937(setq ac-common-part (try-completion ac-prefix candidates))938(setq ac-whole-common-part ac-common-part)939candidates))))940941(defun ac-update-candidates (cursor scroll-top)942"Update candidates of menu to `ac-candidates' and redraw it."943(setf (popup-cursor ac-menu) cursor944(popup-scroll-top ac-menu) scroll-top)945(setq ac-dwim-enable (= (length ac-candidates) 1))946(if ac-candidates947(progn948(setq ac-completing t)949(ac-activate-completing-map))950(setq ac-completing nil)951(ac-deactivate-completing-map))952(ac-inline-update)953(popup-set-list ac-menu ac-candidates)954(if (and (not ac-fuzzy-enable)955(<= (length ac-candidates) 1))956(popup-hide ac-menu)957(if ac-show-menu958(popup-draw ac-menu))))959960(defun ac-reposition ()961"Force to redraw candidate menu with current `ac-candidates'."962(let ((cursor (popup-cursor ac-menu))963(scroll-top (popup-scroll-top ac-menu)))964(ac-menu-delete)965(ac-menu-create ac-point (popup-preferred-width ac-candidates) (popup-height ac-menu))966(ac-update-candidates cursor scroll-top)))967968(defun ac-cleanup ()969"Cleanup auto completion."970(if ac-cursor-color971(set-cursor-color ac-cursor-color))972(when (and ac-use-comphist ac-comphist)973(when (and (null ac-selected-candidate)974(member ac-prefix ac-candidates))975;; Assume candidate is selected by just typing976(setq ac-selected-candidate ac-prefix)977(setq ac-last-point ac-point))978(when ac-selected-candidate979(ac-comphist-add ac-comphist980ac-selected-candidate981(if ac-last-point982(- ac-last-point ac-point)983(length ac-prefix)))))984(ac-deactivate-completing-map)985(ac-remove-prefix-overlay)986(ac-remove-quick-help)987(ac-inline-delete)988(ac-menu-delete)989(ac-cancel-timer)990(ac-cancel-show-menu-timer)991(ac-cancel-quick-help-timer)992(setq ac-cursor-color nil993ac-inline nil994ac-show-menu nil995ac-menu nil996ac-completing nil997ac-point nil998ac-last-point nil999ac-prefix nil1000ac-prefix-overlay nil1001ac-selected-candidate nil1002ac-common-part nil1003ac-whole-common-part nil1004ac-triggered nil1005ac-limit nil1006ac-candidates nil1007ac-candidates-cache nil1008ac-fuzzy-enable nil1009ac-dwim-enable nil1010ac-compiled-sources nil1011ac-current-sources nil1012ac-current-prefix-def nil1013ac-ignoring-prefix-def nil))10141015(defsubst ac-abort ()1016"Abort completion."1017(ac-cleanup))10181019(defun ac-expand-string (string &optional remove-undo-boundary)1020"Expand `STRING' into the buffer and update `ac-prefix' to `STRING'.1021This function records deletion and insertion sequences by `undo-boundary'.1022If `remove-undo-boundary' is non-nil, this function also removes `undo-boundary'1023that have been made before in this function."1024(when (not (equal string (buffer-substring ac-point (point))))1025(undo-boundary)1026;; We can't use primitive-undo since it undoes by1027;; groups, divided by boundaries.1028;; We don't want boundary between deletion and insertion.1029;; So do it manually.1030;; Delete region silently for undo:1031(if remove-undo-boundary1032(progn1033(let (buffer-undo-list)1034(save-excursion1035(delete-region ac-point (point))))1036(setq buffer-undo-list1037(nthcdr 2 buffer-undo-list)))1038(delete-region ac-point (point)))1039(insert string)1040;; Sometimes, possible when omni-completion used, (insert) added1041;; to buffer-undo-list strange record about position changes.1042;; Delete it here:1043(when (and remove-undo-boundary1044(integerp (cadr buffer-undo-list)))1045(setcdr buffer-undo-list (nthcdr 2 buffer-undo-list)))1046(undo-boundary)1047(setq ac-selected-candidate string)1048(setq ac-prefix string)))10491050(defun ac-set-trigger-key (key)1051"Set `ac-trigger-key' to `KEY'. It is recommemded to use this function instead of calling `setq'."1052;; Remove old mapping1053(when ac-trigger-key1054(define-key ac-mode-map (read-kbd-macro ac-trigger-key) nil))10551056;; Make new mapping1057(setq ac-trigger-key key)1058(when key1059(define-key ac-mode-map (read-kbd-macro key) 'ac-trigger-key-command)))10601061(defun ac-set-timer ()1062(unless ac-timer1063(setq ac-timer (run-with-idle-timer ac-delay ac-delay 'ac-update-greedy))))10641065(defun ac-cancel-timer ()1066(when (timerp ac-timer)1067(cancel-timer ac-timer)1068(setq ac-timer nil)))10691070(defun ac-update (&optional force)1071(when (and auto-complete-mode1072ac-prefix1073(or ac-triggered1074force)1075(not isearch-mode))1076(ac-put-prefix-overlay)1077(setq ac-candidates (ac-candidates))1078(let ((preferred-width (popup-preferred-width ac-candidates)))1079;; Reposition if needed1080(when (or (null ac-menu)1081(>= (popup-width ac-menu) preferred-width)1082(<= (popup-width ac-menu) (- preferred-width 10))1083(and (> (popup-direction ac-menu) 0)1084(ac-menu-at-wrapper-line-p)))1085(ac-inline-hide) ; Hide overlay to calculate correct column1086(ac-menu-delete)1087(ac-menu-create ac-point preferred-width ac-menu-height)))1088(ac-update-candidates 0 0)1089t))10901091(defun ac-update-greedy (&optional force)1092(let (result)1093(while (when (and (setq result (ac-update force))1094(null ac-candidates))1095(add-to-list 'ac-ignoring-prefix-def ac-current-prefix-def)1096(ac-start :force-init t)1097ac-current-prefix-def))1098result))10991100(defun ac-set-show-menu-timer ()1101(when (and (or (integerp ac-auto-show-menu) (floatp ac-auto-show-menu))1102(null ac-show-menu-timer))1103(setq ac-show-menu-timer (run-with-idle-timer ac-auto-show-menu ac-auto-show-menu 'ac-show-menu))))11041105(defun ac-cancel-show-menu-timer ()1106(when (timerp ac-show-menu-timer)1107(cancel-timer ac-show-menu-timer)1108(setq ac-show-menu-timer nil)))11091110(defun ac-show-menu ()1111(when (not (eq ac-show-menu t))1112(setq ac-show-menu t)1113(ac-inline-hide)1114(ac-remove-quick-help)1115(ac-update t)))11161117(defun ac-help (&optional persist)1118(interactive "P")1119(when ac-menu1120(popup-menu-show-help ac-menu persist)))11211122(defun ac-persist-help ()1123(interactive)1124(ac-help t))11251126(defun ac-last-help (&optional persist)1127(interactive "P")1128(when ac-last-completion1129(popup-item-show-help (cdr ac-last-completion) persist)))11301131(defun ac-last-persist-help ()1132(interactive)1133(ac-last-help t))11341135(defun ac-set-quick-help-timer ()1136(when (and ac-use-quick-help1137(null ac-quick-help-timer))1138(setq ac-quick-help-timer (run-with-idle-timer ac-quick-help-delay ac-quick-help-delay 'ac-quick-help))))11391140(defun ac-cancel-quick-help-timer ()1141(when (timerp ac-quick-help-timer)1142(cancel-timer ac-quick-help-timer)1143(setq ac-quick-help-timer nil)))11441145(defun ac-pos-tip-show-quick-help (menu &optional item &rest args)1146(let* ((point (plist-get args :point))1147(around nil)1148(parent-offset (popup-offset menu))1149(doc (popup-menu-documentation menu item)))1150(when (stringp doc)1151(if (popup-hidden-p menu)1152(setq around t)1153(setq point nil))1154(with-no-warnings1155(pos-tip-show doc1156'popup-tip-face1157(or point1158(and menu1159(popup-child-point menu parent-offset))1160(point))1161nil 01162popup-tip-max-width1163nil nil1164(and (not around) 0))1165(unless (plist-get args :nowait)1166(clear-this-command-keys)1167(unwind-protect1168(push (read-event (plist-get args :prompt)) unread-command-events)1169(pos-tip-hide))1170t)))))11711172(defun ac-quick-help (&optional force)1173(interactive)1174(when (and (or force (null this-command))1175(ac-menu-live-p)1176(null ac-quick-help))1177(setq ac-quick-help1178(funcall (if (and ac-quick-help-prefer-x1179(eq window-system 'x)1180(featurep 'pos-tip))1181'ac-pos-tip-show-quick-help1182'popup-menu-show-quick-help)1183ac-menu nil1184:point ac-point1185:height ac-quick-help-height1186:nowait t))))11871188(defun ac-remove-quick-help ()1189(when ac-quick-help1190(popup-delete ac-quick-help)1191(setq ac-quick-help nil)))11921193(defun ac-last-quick-help ()1194(interactive)1195(when (and ac-last-completion1196(eq (marker-buffer (car ac-last-completion))1197(current-buffer)))1198(let ((doc (popup-item-documentation (cdr ac-last-completion)))1199(point (marker-position (car ac-last-completion))))1200(when (stringp doc)1201(if (and ac-quick-help-prefer-x1202(eq window-system 'x)1203(featurep 'pos-tip))1204(with-no-warnings (pos-tip-show doc nil point nil 0))1205(popup-tip doc1206:point point1207:around t1208:scroll-bar t1209:margin t))))))12101211(defmacro ac-define-quick-help-command (name arglist &rest body)1212(declare (indent 2))1213`(progn1214(defun ,name ,arglist ,@body)1215(put ',name 'ac-quick-help-command t)))12161217(ac-define-quick-help-command ac-quick-help-scroll-down ()1218(interactive)1219(when ac-quick-help1220(popup-scroll-down ac-quick-help)))12211222(ac-define-quick-help-command ac-quick-help-scroll-up ()1223(interactive)1224(when ac-quick-help1225(popup-scroll-up ac-quick-help)))1226122712281229;;;; Auto completion isearch12301231(defun ac-isearch-callback (list)1232(setq ac-dwim-enable (eq (length list) 1)))12331234(defun ac-isearch ()1235(interactive)1236(when (ac-menu-live-p)1237(ac-cancel-show-menu-timer)1238(ac-cancel-quick-help-timer)1239(ac-show-menu)1240(popup-isearch ac-menu :callback 'ac-isearch-callback)))1241124212431244;;;; Auto completion commands12451246(defun auto-complete (&optional sources)1247"Start auto-completion at current point."1248(interactive)1249(let ((menu-live (ac-menu-live-p))1250(inline-live (ac-inline-live-p)))1251(ac-abort)1252(let ((ac-sources (or sources ac-sources)))1253(if (or ac-show-menu-immediately-on-auto-complete1254inline-live)1255(setq ac-show-menu t))1256(ac-start))1257(when (ac-update-greedy t)1258;; TODO Not to cause inline completion to be disrupted.1259(if (ac-inline-live-p)1260(ac-inline-hide))1261;; Not to expand when it is first time to complete1262(when (and (or (and (not ac-expand-on-auto-complete)1263(> (length ac-candidates) 1)1264(not menu-live))1265(not (let ((ac-common-part ac-whole-common-part))1266(ac-expand-common))))1267ac-use-fuzzy1268(null ac-candidates))1269(ac-fuzzy-complete)))))12701271(defun ac-fuzzy-complete ()1272"Start fuzzy completion at current point."1273(interactive)1274(when (require 'fuzzy nil)1275(unless (ac-menu-live-p)1276(ac-start))1277(let ((ac-match-function 'fuzzy-all-completions))1278(unless ac-cursor-color1279(setq ac-cursor-color (frame-parameter (selected-frame) 'cursor-color)))1280(if ac-fuzzy-cursor-color1281(set-cursor-color ac-fuzzy-cursor-color))1282(setq ac-show-menu t)1283(setq ac-fuzzy-enable t)1284(setq ac-triggered nil)1285(ac-update t)))1286t)12871288(defun ac-next ()1289"Select next candidate."1290(interactive)1291(when (ac-menu-live-p)1292(popup-next ac-menu)1293(setq ac-show-menu t)1294(if (eq this-command 'ac-next)1295(setq ac-dwim-enable t))))12961297(defun ac-previous ()1298"Select previous candidate."1299(interactive)1300(when (ac-menu-live-p)1301(popup-previous ac-menu)1302(setq ac-show-menu t)1303(if (eq this-command 'ac-previous)1304(setq ac-dwim-enable t))))13051306(defun ac-expand ()1307"Try expand, and if expanded twice, select next candidate."1308(interactive)1309(unless (ac-expand-common)1310(let ((string (ac-selected-candidate)))1311(when string1312(when (equal ac-prefix string)1313(ac-next)1314(setq string (ac-selected-candidate)))1315(ac-expand-string string (eq last-command this-command))1316;; Do reposition if menu at long line1317(if (and (> (popup-direction ac-menu) 0)1318(ac-menu-at-wrapper-line-p))1319(ac-reposition))1320(setq ac-show-menu t)1321string))))13221323(defun ac-expand-common ()1324"Try to expand meaningful common part."1325(interactive)1326(if (and ac-dwim ac-dwim-enable)1327(ac-complete)1328(when (and (ac-inline-live-p)1329ac-common-part)1330(ac-inline-hide)1331(ac-expand-string ac-common-part (eq last-command this-command))1332(setq ac-common-part nil)1333t)))13341335(defun ac-complete ()1336"Try complete."1337(interactive)1338(let* ((candidate (ac-selected-candidate))1339(action (popup-item-property candidate 'action))1340(fallback nil))1341(when candidate1342(unless (ac-expand-string candidate)1343(setq fallback t))1344;; Remember to show help later1345(when (and ac-point candidate)1346(unless ac-last-completion1347(setq ac-last-completion (cons (make-marker) nil)))1348(set-marker (car ac-last-completion) ac-point ac-buffer)1349(setcdr ac-last-completion candidate)))1350(ac-abort)1351(cond1352(action1353(funcall action))1354(fallback1355(ac-fallback-command)))1356candidate))13571358(defun* ac-start (&key1359requires1360force-init)1361"Start completion."1362(interactive)1363(if (not auto-complete-mode)1364(message "auto-complete-mode is not enabled")1365(let* ((info (ac-prefix requires ac-ignoring-prefix-def))1366(prefix-def (nth 0 info))1367(point (nth 1 info))1368(sources (nth 2 info))1369prefix1370(init (or force-init (not (eq ac-point point)))))1371(if (or (null point)1372(member (setq prefix (buffer-substring-no-properties point (point)))1373ac-ignores))1374(prog1 nil1375(ac-abort))1376(unless ac-cursor-color1377(setq ac-cursor-color (frame-parameter (selected-frame) 'cursor-color)))1378(setq ac-show-menu (or ac-show-menu (if (eq ac-auto-show-menu t) t))1379ac-current-sources sources1380ac-buffer (current-buffer)1381ac-point point1382ac-prefix prefix1383ac-limit ac-candidate-limit1384ac-triggered t1385ac-current-prefix-def prefix-def)1386(when (or init (null ac-prefix-overlay))1387(ac-init))1388(ac-set-timer)1389(ac-set-show-menu-timer)1390(ac-set-quick-help-timer)1391(ac-put-prefix-overlay)))))13921393(defun ac-stop ()1394"Stop completiong."1395(interactive)1396(setq ac-selected-candidate nil)1397(ac-abort))13981399(defun ac-trigger-key-command (&optional force)1400(interactive "P")1401(if (or force (ac-trigger-command-p last-command))1402(auto-complete)1403(ac-fallback-command 'ac-trigger-key-command)))1404140514061407;;;; Basic cache facility14081409(defvar ac-clear-variables-every-minute-timer nil)1410(defvar ac-clear-variables-after-save nil)1411(defvar ac-clear-variables-every-minute nil)1412(defvar ac-minutes-counter 0)14131414(defun ac-clear-variable-after-save (variable &optional pred)1415(add-to-list 'ac-clear-variables-after-save (cons variable pred)))14161417(defun ac-clear-variables-after-save ()1418(dolist (pair ac-clear-variables-after-save)1419(if (or (null (cdr pair))1420(funcall (cdr pair)))1421(set (car pair) nil))))14221423(defun ac-clear-variable-every-minutes (variable minutes)1424(add-to-list 'ac-clear-variables-every-minute (cons variable minutes)))14251426(defun ac-clear-variable-every-minute (variable)1427(ac-clear-variable-every-minutes variable 1))14281429(defun ac-clear-variable-every-10-minutes (variable)1430(ac-clear-variable-every-minutes variable 10))14311432(defun ac-clear-variables-every-minute ()1433(incf ac-minutes-counter)1434(dolist (pair ac-clear-variables-every-minute)1435(if (eq (% ac-minutes-counter (cdr pair)) 0)1436(set (car pair) nil))))1437143814391440;;;; Auto complete mode14411442(defun ac-cursor-on-diable-face-p (&optional point)1443(memq (get-text-property (or point (point)) 'face) ac-disable-faces))14441445(defun ac-trigger-command-p (command)1446"Return non-nil if `COMMAND' is a trigger command."1447(and (symbolp command)1448(or (memq command ac-trigger-commands)1449(string-match "self-insert-command" (symbol-name command))1450(string-match "electric" (symbol-name command)))))14511452(defun ac-fallback-command (&optional except-command)1453(let* ((auto-complete-mode nil)1454(keys (this-command-keys-vector))1455(command (if keys (key-binding keys))))1456(when (and (commandp command)1457(not (eq command except-command)))1458(setq this-command command)1459(call-interactively command))))14601461(defun ac-compatible-package-command-p (command)1462"Return non-nil if `COMMAND' is compatible with auto-complete."1463(and (symbolp command)1464(string-match ac-compatible-packages-regexp (symbol-name command))))14651466(defun ac-handle-pre-command ()1467(condition-case var1468(if (or (setq ac-triggered (and (not ac-fuzzy-enable) ; ignore key storkes in fuzzy mode1469(or (eq this-command 'auto-complete) ; special case1470(ac-trigger-command-p this-command)1471(and ac-completing1472(memq this-command ac-trigger-commands-on-completing)))1473(not (ac-cursor-on-diable-face-p))))1474(ac-compatible-package-command-p this-command))1475(progn1476(if (or (not (symbolp this-command))1477(not (get this-command 'ac-quick-help-command)))1478(ac-remove-quick-help))1479;; Not to cause inline completion to be disrupted.1480(ac-inline-hide))1481(ac-abort))1482(error (ac-error var))))14831484(defun ac-handle-post-command ()1485(condition-case var1486(when (and ac-triggered1487(or ac-auto-start1488ac-completing)1489(not isearch-mode))1490(setq ac-last-point (point))1491(ac-start :requires (unless ac-completing ac-auto-start))1492(ac-inline-update))1493(error (ac-error var))))14941495(defun ac-setup ()1496(if ac-trigger-key1497(ac-set-trigger-key ac-trigger-key))1498(if ac-use-comphist1499(ac-comphist-init))1500(unless ac-clear-variables-every-minute-timer1501(setq ac-clear-variables-every-minute-timer (run-with-timer 60 60 'ac-clear-variables-every-minute)))1502(if ac-stop-flymake-on-completing1503(defadvice flymake-on-timer-event (around ac-flymake-stop-advice activate)1504(unless ac-completing1505ad-do-it))1506(ad-disable-advice 'flymake-on-timer-event 'around 'ac-flymake-stop-advice)))15071508(define-minor-mode auto-complete-mode1509"AutoComplete mode"1510:lighter " AC"1511:keymap ac-mode-map1512:group 'auto-complete1513(if auto-complete-mode1514(progn1515(ac-setup)1516(add-hook 'pre-command-hook 'ac-handle-pre-command nil t)1517(add-hook 'post-command-hook 'ac-handle-post-command nil t)1518(add-hook 'after-save-hook 'ac-clear-variables-after-save nil t)1519(run-hooks 'auto-complete-mode-hook))1520(remove-hook 'pre-command-hook 'ac-handle-pre-command t)1521(remove-hook 'post-command-hook 'ac-handle-post-command t)1522(remove-hook 'after-save-hook 'ac-clear-variables-after-save t)1523(ac-abort)))15241525(defun auto-complete-mode-maybe ()1526"What buffer `auto-complete-mode' prefers."1527(if (and (not (minibufferp (current-buffer)))1528(memq major-mode ac-modes))1529(auto-complete-mode 1)))15301531(define-global-minor-mode global-auto-complete-mode1532auto-complete-mode auto-complete-mode-maybe1533:group 'auto-complete)1534153515361537;;;; Compatibilities with other extensions15381539(defun ac-flyspell-workaround ()1540"Flyspell uses `sit-for' for delaying its process. Unfortunatelly,1541it stops auto completion which is trigger with `run-with-idle-timer'.1542This workaround avoid flyspell processes when auto completion is being started."1543(interactive)1544(defadvice flyspell-post-command-hook (around ac-flyspell-workaround activate)1545(unless ac-triggered1546ad-do-it)))1547154815491550;;;; Standard sources15511552(defmacro ac-define-source (name source)1553"Source definition macro. It defines a complete command also."1554(declare (indent 1))1555`(progn1556(defvar ,(intern (format "ac-source-%s" name))1557,source)1558(defun ,(intern (format "ac-complete-%s" name)) ()1559(interactive)1560(auto-complete '(,(intern (format "ac-source-%s" name)))))))15611562;; Words in buffer source1563(defvar ac-word-index nil)15641565(defun ac-candidate-words-in-buffer (point prefix limit)1566(let ((i 0)1567candidate1568candidates1569(regexp (concat "\\_<" (regexp-quote prefix) "\\(\\sw\\|\\s_\\)+\\_>")))1570(save-excursion1571;; Search backward1572(goto-char point)1573(while (and (or (not (integerp limit)) (< i limit))1574(re-search-backward regexp nil t))1575(setq candidate (match-string-no-properties 0))1576(unless (member candidate candidates)1577(push candidate candidates)1578(incf i)))1579;; Search backward1580(goto-char (+ point (length prefix)))1581(while (and (or (not (integerp limit)) (< i limit))1582(re-search-forward regexp nil t))1583(setq candidate (match-string-no-properties 0))1584(unless (member candidate candidates)1585(push candidate candidates)1586(incf i)))1587(nreverse candidates))))15881589(defun ac-incremental-update-word-index ()1590(unless (local-variable-p 'ac-word-index)1591(make-local-variable 'ac-word-index))1592(if (null ac-word-index)1593(setq ac-word-index (cons nil nil)))1594;; Mark incomplete1595(if (car ac-word-index)1596(setcar ac-word-index nil))1597(let ((index (cdr ac-word-index))1598(words (ac-candidate-words-in-buffer ac-point ac-prefix (or (and (integerp ac-limit) ac-limit) 10))))1599(dolist (word words)1600(unless (member word index)1601(push word index)1602(setcdr ac-word-index index)))))16031604(defun ac-update-word-index-1 ()1605(unless (local-variable-p 'ac-word-index)1606(make-local-variable 'ac-word-index))1607(when (and (not (car ac-word-index))1608(< (buffer-size) 1048576))1609;; Complete index1610(setq ac-word-index1611(cons t1612(split-string (buffer-substring-no-properties (point-min) (point-max))1613"\\(?:^\\|\\_>\\).*?\\(?:\\_<\\|$\\)")))))16141615(defun ac-update-word-index ()1616(dolist (buffer (buffer-list))1617(when (or ac-fuzzy-enable1618(not (eq buffer (current-buffer))))1619(with-current-buffer buffer1620(ac-update-word-index-1)))))16211622(defun ac-word-candidates (&optional buffer-pred)1623(loop initially (unless ac-fuzzy-enable (ac-incremental-update-word-index))1624for buffer in (buffer-list)1625if (and (or (not (integerp ac-limit)) (< (length candidates) ac-limit))1626(if buffer-pred (funcall buffer-pred buffer) t))1627append (funcall ac-match-function1628ac-prefix1629(and (local-variable-p 'ac-word-index buffer)1630(cdr (buffer-local-value 'ac-word-index buffer))))1631into candidates1632finally return candidates))16331634(ac-define-source words-in-buffer1635'((candidates . ac-word-candidates)))16361637(ac-define-source words-in-all-buffer1638'((init . ac-update-word-index)1639(candidates . ac-word-candidates)))16401641(ac-define-source words-in-same-mode-buffers1642'((init . ac-update-word-index)1643(candidates . (ac-word-candidates1644(lambda (buffer)1645(derived-mode-p (buffer-local-value 'major-mode buffer)))))))16461647;; Lisp symbols source1648(defvar ac-symbols-cache nil)1649(ac-clear-variable-every-10-minutes 'ac-symbols-cache)16501651(defun ac-symbol-file (symbol type)1652(if (fboundp 'find-lisp-object-file-name)1653(find-lisp-object-file-name symbol type)1654(let ((file-name (with-no-warnings1655(describe-simplify-lib-file-name1656(symbol-file symbol type)))))1657(when (equal file-name "loaddefs.el")1658;; Find the real def site of the preloaded object.1659(let ((location (condition-case nil1660(if (eq type 'defun)1661(find-function-search-for-symbol symbol nil1662"loaddefs.el")1663(find-variable-noselect symbol file-name))1664(error nil))))1665(when location1666(with-current-buffer (car location)1667(when (cdr location)1668(goto-char (cdr location)))1669(when (re-search-backward1670"^;;; Generated autoloads from \\(.*\\)" nil t)1671(setq file-name (match-string 1)))))))1672(if (and (null file-name)1673(or (eq type 'defun)1674(integerp (get symbol 'variable-documentation))))1675;; It's a object not defined in Elisp but in C.1676(if (get-buffer " *DOC*")1677(if (eq type 'defun)1678(help-C-file-name (symbol-function symbol) 'subr)1679(help-C-file-name symbol 'var))1680'C-source)1681file-name))))16821683(defun ac-symbol-documentation (symbol)1684(if (stringp symbol)1685(setq symbol (intern-soft symbol)))1686(ignore-errors1687(with-temp-buffer1688(let ((standard-output (current-buffer)))1689(prin1 symbol)1690(princ " is ")1691(cond1692((fboundp symbol)1693(let ((help-xref-following t))1694(describe-function-1 symbol))1695(buffer-string))1696((boundp symbol)1697(let ((file-name (ac-symbol-file symbol 'defvar)))1698(princ "a variable")1699(when file-name1700(princ " defined in `")1701(princ (if (eq file-name 'C-source)1702"C source code"1703(file-name-nondirectory file-name))))1704(princ "'.\n\n")1705(princ (or (documentation-property symbol 'variable-documentation t)1706"Not documented."))1707(buffer-string)))1708((facep symbol)1709(let ((file-name (ac-symbol-file symbol 'defface)))1710(princ "a face")1711(when file-name1712(princ " defined in `")1713(princ (if (eq file-name 'C-source)1714"C source code"1715(file-name-nondirectory file-name))))1716(princ "'.\n\n")1717(princ (or (documentation-property symbol 'face-documentation t)1718"Not documented."))1719(buffer-string)))1720(t1721(let ((doc (documentation-property symbol 'group-documentation t)))1722(when doc1723(princ "a group.\n\n")1724(princ doc)1725(buffer-string)))))))))17261727(defun ac-symbol-candidates ()1728(or ac-symbols-cache1729(setq ac-symbols-cache1730(loop for x being the symbols1731if (or (fboundp x)1732(boundp x)1733(symbol-plist x))1734collect (symbol-name x)))))17351736(ac-define-source symbols1737'((candidates . ac-symbol-candidates)1738(document . ac-symbol-documentation)1739(symbol . "s")1740(cache)))17411742;; Lisp functions source1743(defvar ac-functions-cache nil)1744(ac-clear-variable-every-10-minutes 'ac-functions-cache)17451746(defun ac-function-candidates ()1747(or ac-functions-cache1748(setq ac-functions-cache1749(loop for x being the symbols1750if (fboundp x)1751collect (symbol-name x)))))17521753(ac-define-source functions1754'((candidates . ac-function-candidates)1755(document . ac-symbol-documentation)1756(symbol . "f")1757(prefix . "(\\(\\(?:\\sw\\|\\s_\\)+\\)")1758(cache)))17591760;; Lisp variables source1761(defvar ac-variables-cache nil)1762(ac-clear-variable-every-10-minutes 'ac-variables-cache)17631764(defun ac-variable-candidates ()1765(or ac-variables-cache1766(setq ac-variables-cache1767(loop for x being the symbols1768if (boundp x)1769collect (symbol-name x)))))17701771(ac-define-source variables1772'((candidates . ac-variable-candidates)1773(document . ac-symbol-documentation)1774(symbol . "v")1775(cache)))17761777;; Lisp features source1778(defvar ac-emacs-lisp-features nil)1779(ac-clear-variable-every-10-minutes 'ac-emacs-lisp-features)17801781(defun ac-emacs-lisp-feature-candidates ()1782(or ac-emacs-lisp-features1783(if (fboundp 'find-library-suffixes)1784(let ((suffix (concat (regexp-opt (find-library-suffixes) t) "\\'")))1785(setq ac-emacs-lisp-features1786(append (mapcar 'prin1-to-string features)1787(loop for dir in load-path1788if (file-directory-p dir)1789append (loop for file in (directory-files dir)1790if (string-match suffix file)1791collect (substring file 0 (match-beginning 0))))))))))17921793(ac-define-source features1794'((depends find-func)1795(candidates . ac-emacs-lisp-feature-candidates)1796(prefix . "require +'\\(\\(?:\\sw\\|\\s_\\)*\\)")1797(requires . 0)))17981799(defvaralias 'ac-source-emacs-lisp-features 'ac-source-features)18001801;; Abbrev source1802(ac-define-source abbrev1803'((candidates . (mapcar 'popup-x-to-string (append (vconcat local-abbrev-table global-abbrev-table) nil)))1804(action . expand-abbrev)1805(symbol . "a")1806(cache)))18071808;; Files in current directory source1809(ac-define-source files-in-current-dir1810'((candidates . (directory-files default-directory))1811(cache)))18121813;; Filename source1814(defvar ac-filename-cache nil)18151816(defun ac-filename-candidate ()1817(unless (file-regular-p ac-prefix)1818(ignore-errors1819(loop with dir = (file-name-directory ac-prefix)1820with files = (or (assoc-default dir ac-filename-cache)1821(let ((files (directory-files dir nil "^[^.]")))1822(push (cons dir files) ac-filename-cache)1823files))1824for file in files1825for path = (concat dir file)1826collect (if (file-directory-p path)1827(concat path "/")1828path)))))18291830(ac-define-source filename1831'((init . (setq ac-filename-cache nil))1832(candidates . ac-filename-candidate)1833(prefix . valid-file)1834(requires . 0)1835(action . ac-start)1836(limit . nil)))18371838;; Dictionary source1839(defcustom ac-user-dictionary nil1840"User dictionary"1841:type '(repeat string)1842:group 'auto-complete)18431844(defcustom ac-user-dictionary-files '("~/.dict")1845"User dictionary files."1846:type '(repeat string)1847:group 'auto-complete)18481849(defcustom ac-dictionary-directories nil1850"Dictionary directories."1851:type '(repeat string)1852:group 'auto-complete)18531854(defvar ac-dictionary nil)1855(defvar ac-dictionary-cache (make-hash-table :test 'equal))18561857(defun ac-clear-dictionary-cache ()1858(interactive)1859(clrhash ac-dictionary-cache))18601861(defun ac-read-file-dictionary (filename)1862(let ((cache (gethash filename ac-dictionary-cache 'none)))1863(if (and cache (not (eq cache 'none)))1864cache1865(let (result)1866(ignore-errors1867(with-temp-buffer1868(insert-file-contents filename)1869(setq result (split-string (buffer-string) "\n"))))1870(puthash filename result ac-dictionary-cache)1871result))))18721873(defun ac-buffer-dictionary ()1874(apply 'append1875(mapcar 'ac-read-file-dictionary1876(mapcar (lambda (name)1877(loop for dir in ac-dictionary-directories1878for file = (concat dir "/" name)1879if (file-exists-p file)1880return file))1881(list (symbol-name major-mode)1882(ignore-errors1883(file-name-extension (buffer-file-name))))))))18841885(defun ac-dictionary-candidates ()1886(apply 'append `(,ac-user-dictionary1887,(ac-buffer-dictionary)1888,@(mapcar 'ac-read-file-dictionary1889ac-user-dictionary-files))))18901891(ac-define-source dictionary1892'((candidates . ac-dictionary-candidates)1893(symbol . "d")))18941895(provide 'auto-complete)1896;;; auto-complete.el ends here189718981899