complete.el 82.1 KB
Newer Older
1
;;; semantic/complete.el --- Routines for performing tag completion
2

3
;; Copyright (C) 2003-2005, 2007-2014 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

;; Author: Eric M. Ludlam <zappo@gnu.org>
;; Keywords: syntax

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:
;;
;; Completion of tags by name using tables of semantic generated tags.
;;
;; While it would be a simple matter of flattening all tag known
;; tables to perform completion across them using `all-completions',
;; or `try-completion', that process would be slow.  In particular,
;; when a system database is included in the mix, the potential for a
;; ludicrous number of options becomes apparent.
;;
;; As such, dynamically searching across tables using a prefix,
;; regular expression, or other feature is needed to help find symbols
;; quickly without resorting to "show me every possible option now".
;;
;; In addition, some symbol names will appear in multiple locations.
Glenn Morris's avatar
Glenn Morris committed
38
;; If it is important to distinguish, then a way to provide a choice
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
;; over these locations is important as well.
;;
;; Beyond brute force offers for completion of plain strings,
;; using the smarts of semantic-analyze to provide reduced lists of
;; symbols, or fancy tabbing to zoom into files to show multiple hits
;; of the same name can be provided.
;;
;;; How it works:
;;
;; There are several parts of any completion engine.  They are:
;;
;; A.  Collection of possible hits
;; B.  Typing or selecting an option
;; C.  Displaying possible unique completions
;; D.  Using the result
;;
;; Here, we will treat each section separately (excluding D)
;; They can then be strung together in user-visible commands to
Paul Eggert's avatar
Paul Eggert committed
57
;; fulfill specific needs.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
;;
;; COLLECTORS:
;;
;; A collector is an object which represents the means by which tags
;; to complete on are collected.  It's first job is to find all the
;; tags which are to be completed against.  It can also rename
;; some tags if needed so long as `semantic-tag-clone' is used.
;;
;; Some collectors will gather all tags to complete against first
;; (for in buffer queries, or other small list situations).  It may
;; choose to do a broad search on each completion request.  Built in
;; functionality automatically focuses the cache in as the user types.
;;
;; A collector choosing to create and rename tags could choose a
;; plain name format, a postfix name such as method:class, or a
;; prefix name such as class.method.
;;
;; DISPLAYORS
;;
;; A displayor is in charge if showing the user interesting things
;; about available completions, and can optionally provide a focus.
;; The simplest display just lists all available names in a separate
;; window.  It may even choose to show short names when there are
;; many to choose from, or long names when there are fewer.
;;
;; A complex displayor could opt to help the user 'focus' on some
;; range.  For example, if 4 tags all have the same name, subsequent
;; calls to the displayor may opt to show each tag one at a time in
;; the buffer.  When the user likes one, selection would cause the
;; 'focus' item to be selected.
;;
;; CACHE FORMAT
;;
;; The format of the tag lists used to perform the completions are in
;; semanticdb "find" format, like this:
;;
;; ( ( DBTABLE1 TAG1 TAG2 ...)
;;   ( DBTABLE2 TAG1 TAG2 ...)
;;   ... )
;;
;; INLINE vs MINIBUFFER
;;
;; Two major ways completion is used in Emacs is either through a
;; minibuffer query, or via completion in a normal editing buffer,
;; encompassing some small range of characters.
;;
;; Structure for both types of completion are provided here.
;; `semantic-complete-read-tag-engine' will use the minibuffer.
;; `semantic-complete-inline-tag-engine' will complete text in
;; a buffer.

Chong Yidong's avatar
Chong Yidong committed
109
(eval-when-compile (require 'cl))
110
(require 'semantic)
111
(require 'eieio-opt)
112 113
(require 'semantic/analyze)
(require 'semantic/ctxt)
114
(require 'semantic/decorate)
115
(require 'semantic/format)
Chong Yidong's avatar
Chong Yidong committed
116
(require 'semantic/idle)
117

118 119 120
(eval-when-compile
  ;; For the semantic-find-tags-for-completion macro.
  (require 'semantic/find))
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

;;; Code:

(defvar semantic-complete-inline-overlay nil
  "The overlay currently active while completing inline.")

(defun semantic-completion-inline-active-p ()
  "Non-nil if inline completion is active."
  (when (and semantic-complete-inline-overlay
	     (not (semantic-overlay-live-p semantic-complete-inline-overlay)))
    (semantic-overlay-delete semantic-complete-inline-overlay)
    (setq semantic-complete-inline-overlay nil))
  semantic-complete-inline-overlay)

;;; ------------------------------------------------------------
;;; MINIBUFFER or INLINE utils
;;
(defun semantic-completion-text ()
  "Return the text that is currently in the completion buffer.
For a minibuffer prompt, this is the minibuffer text.
For inline completion, this is the text wrapped in the inline completion
overlay."
  (if semantic-complete-inline-overlay
      (semantic-complete-inline-text)
145
    (minibuffer-contents)))
146 147 148 149 150 151

(defun semantic-completion-delete-text ()
  "Delete the text that is actively being completed.
Presumably if you call this you will insert something new there."
  (if semantic-complete-inline-overlay
      (semantic-complete-inline-delete-text)
152
    (delete-minibuffer-contents)))
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

(defun semantic-completion-message (fmt &rest args)
  "Display the string FMT formatted with ARGS at the end of the minibuffer."
  (if semantic-complete-inline-overlay
      (apply 'message fmt args)
    (message (concat (buffer-string) (apply 'format fmt args)))))

;;; ------------------------------------------------------------
;;; MINIBUFFER: Option Selection harnesses
;;
(defvar semantic-completion-collector-engine nil
  "The tag collector for the current completion operation.
Value should be an object of a subclass of
`semantic-completion-engine-abstract'.")

(defvar semantic-completion-display-engine nil
  "The tag display engine for the current completion operation.
Value should be a ... what?")

(defvar semantic-complete-key-map
  (let ((km (make-sparse-keymap)))
    (define-key km " " 'semantic-complete-complete-space)
    (define-key km "\t" 'semantic-complete-complete-tab)
    (define-key km "\C-m" 'semantic-complete-done)
    (define-key km "\C-g" 'abort-recursive-edit)
    (define-key km "\M-n" 'next-history-element)
    (define-key km "\M-p" 'previous-history-element)
    (define-key km "\C-n" 'next-history-element)
    (define-key km "\C-p" 'previous-history-element)
    ;; Add history navigation
    km)
  "Keymap used while completing across a list of tags.")

(defvar semantic-completion-default-history nil
  "Default history variable for any unhistoried prompt.
Keeps STRINGS only in the history.")


(defun semantic-complete-read-tag-engine (collector displayor prompt
						    default-tag initial-input
						    history)
  "Read a semantic tag, and return a tag for the selection.
195
Argument COLLECTOR is an object which can be used to calculate
196 197
a list of possible hits.  See `semantic-completion-collector-engine'
for details on COLLECTOR.
Glenn Morris's avatar
Glenn Morris committed
198
Argument DISPLAYOR is an object used to display a list of possible
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
completions for a given prefix.  See`semantic-completion-display-engine'
for details on DISPLAYOR.
PROMPT is a string to prompt with.
DEFAULT-TAG is a semantic tag or string to use as the default value.
If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
HISTORY is a symbol representing a variable to story the history in."
  (let* ((semantic-completion-collector-engine collector)
	 (semantic-completion-display-engine displayor)
	 (semantic-complete-active-default nil)
	 (semantic-complete-current-matched-tag nil)
	 (default-as-tag (semantic-complete-default-to-tag default-tag))
	 (default-as-string (when (semantic-tag-p default-as-tag)
			      (semantic-tag-name default-as-tag)))
	 )

    (when default-as-string
      ;; Add this to the prompt.
      ;;
      ;; I really want to add a lookup of the symbol in those
      ;; tags available to the collector and only add it if it
      ;; is available as a possibility, but I'm too lazy right
      ;; now.
      ;;

      ;; @todo - move from () to into the editable area
      (if (string-match ":" prompt)
	  (setq prompt (concat
			(substring prompt 0 (match-beginning 0))
227
			" (default " default-as-string ")"
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
			(substring prompt (match-beginning 0))))
	(setq prompt (concat prompt " (" default-as-string "): "))))
    ;;
    ;; Perform the Completion
    ;;
    (unwind-protect
	(read-from-minibuffer prompt
			      initial-input
			      semantic-complete-key-map
			      nil
			      (or history
				  'semantic-completion-default-history)
			      default-tag)
      (semantic-collector-cleanup semantic-completion-collector-engine)
      (semantic-displayor-cleanup semantic-completion-display-engine)
      )
    ;;
    ;; Extract the tag from the completion machinery.
    ;;
    semantic-complete-current-matched-tag
    ))


;;; Util for basic completion prompts
;;

(defvar semantic-complete-active-default nil
  "The current default tag calculated for this prompt.")

(defun semantic-complete-default-to-tag (default)
  "Convert a calculated or passed in DEFAULT into a tag."
  (if (semantic-tag-p default)
      ;; Just return what was passed in.
      (setq semantic-complete-active-default default)
    ;; If none was passed in, guess.
    (if (null default)
	(setq default (semantic-ctxt-current-thing)))
    (if (null default)
	;; Do nothing
	nil
      ;; Turn default into something useful.
      (let ((str
	     (cond
	      ;; Semantic-ctxt-current-symbol will return a list of
	      ;; strings.  Technically, we should use the analyzer to
	      ;; fully extract what we need, but for now, just grab the
	      ;; first string
	      ((and (listp default) (stringp (car default)))
	       (car default))
	      ((stringp default)
	       default)
	      ((symbolp default)
	       (symbol-name default))
	      (t
	       (signal 'wrong-type-argument
		       (list default 'semantic-tag-p)))))
	    (tag nil))
	;; Now that we have that symbol string, look it up using the active
	;; collector.  If we get a match, use it.
	(save-excursion
	  (semantic-collector-calculate-completions
	   semantic-completion-collector-engine
	   str nil))
	;; Do we have the perfect match???
	(let ((ml (semantic-collector-current-exact-match
		   semantic-completion-collector-engine)))
	  (when ml
	    ;; We don't care about uniqueness.  Just guess for convenience
	    (setq tag (semanticdb-find-result-nth-in-buffer ml 0))))
	;; save it
	(setq semantic-complete-active-default tag)
	;; Return it.. .whatever it may be
	tag))))


;;; Prompt Return Value
;;
;; Getting a return value out of this completion prompt is a bit
;; challenging.  The read command returns the string typed in.
;; We need to convert this into a valid tag.  We can exit the minibuffer
;; for different reasons.  If we purposely exit, we must make sure
;; the focused tag is calculated... preferably once.
(defvar semantic-complete-current-matched-tag nil
  "Variable used to pass the tags being matched to the prompt.")

313 314 315
;; semantic-displayor-focus-abstract-child-p is part of the
;; semantic-displayor-focus-abstract class, defined later in this
;; file.
316 317
(declare-function semantic-displayor-focus-abstract-child-p "semantic/complete"
		  t t)
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
(defun semantic-complete-current-match ()
  "Calculate a match from the current completion environment.
Save this in our completion variable.  Make sure that variable
is cleared if any other keypress is made.
Return value can be:
  tag - a single tag that has been matched.
  string - a message to show in the minibuffer."
  ;; Query the environment for an active completion.
  (let ((collector semantic-completion-collector-engine)
	(displayor semantic-completion-display-engine)
	(contents (semantic-completion-text))
	matchlist
	answer)
    (if (string= contents "")
	;; The user wants the defaults!
	(setq answer semantic-complete-active-default)
      ;; This forces a full calculation of completion on CR.
      (save-excursion
	(semantic-collector-calculate-completions collector contents nil))
      (semantic-complete-try-completion)
      (cond
       ;; Input match displayor focus entry
       ((setq answer (semantic-displayor-current-focus displayor))
	;; We have answer, continue
	)
       ;; One match from the collector
       ((setq matchlist (semantic-collector-current-exact-match collector))
	(if (= (semanticdb-find-result-length matchlist) 1)
	    (setq answer (semanticdb-find-result-nth-in-buffer matchlist 0))
	  (if (semantic-displayor-focus-abstract-child-p displayor)
	      ;; For focusing displayors, we can claim this is
	      ;; not unique.  Multiple focuses can choose the correct
	      ;; one.
	      (setq answer "Not Unique")
	    ;; If we don't have a focusing displayor, we need to do something
	    ;; graceful.  First, see if all the matches have the same name.
	    (let ((allsame t)
		  (firstname (semantic-tag-name
			      (car
			       (semanticdb-find-result-nth matchlist 0)))
			     )
		  (cnt 1)
		  (max (semanticdb-find-result-length matchlist)))
	      (while (and allsame (< cnt max))
		(if (not (string=
			  firstname
			  (semantic-tag-name
			   (car
			    (semanticdb-find-result-nth matchlist cnt)))))
		    (setq allsame nil))
		(setq cnt (1+ cnt))
		)
	      ;; Now we know if they are all the same.  If they are, just
	      ;; accept the first, otherwise complain.
	      (if allsame
		  (setq answer (semanticdb-find-result-nth-in-buffer
				matchlist 0))
		(setq answer "Not Unique"))
	      ))))
       ;; No match
       (t
	(setq answer "No Match")))
      )
    ;; Set it into our completion target.
    (when (semantic-tag-p answer)
      (setq semantic-complete-current-matched-tag answer)
      ;; Make sure it is up to date by clearing it if the user dares
      ;; to touch the keyboard.
      (add-hook 'pre-command-hook
		(lambda () (setq semantic-complete-current-matched-tag nil)))
      )
    ;; Return it
    answer
    ))


;;; Keybindings
;;
397
;; Keys are bound to perform completion using our mechanisms.
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
;; Do that work here.
(defun semantic-complete-done ()
  "Accept the current input."
  (interactive)
  (let ((ans (semantic-complete-current-match)))
    (if (stringp ans)
	(semantic-completion-message (concat " [" ans "]"))
      (exit-minibuffer)))
  )

(defun semantic-complete-complete-space ()
  "Complete the partial input in the minibuffer."
  (interactive)
  (semantic-complete-do-completion t))

(defun semantic-complete-complete-tab ()
  "Complete the partial input in the minibuffer as far as possible."
  (interactive)
  (semantic-complete-do-completion))

;;; Completion Functions
;;
;; Thees routines are functional entry points to performing completion.
;;
(defun semantic-complete-hack-word-boundaries (original new)
  "Return a string to use for completion.
ORIGINAL is the text in the minibuffer.
NEW is the new text to insert into the minibuffer.
Within the difference bounds of ORIGINAL and NEW, shorten NEW
to the nearest word boundary, and return that."
  (save-match-data
    (let* ((diff (substring new (length original)))
	   (end (string-match "\\>" diff))
	   (start (string-match "\\<" diff)))
      (cond
       ((and start (> start 0))
	;; If start is greater than 0, include only the new
	;; white-space stuff
	(concat original (substring diff 0 start)))
       (end
	(concat original (substring diff 0 end)))
       (t new)))))

(defun semantic-complete-try-completion (&optional partial)
  "Try a completion for the current minibuffer.
If PARTIAL, do partial completion stopping at spaces."
  (let ((comp (semantic-collector-try-completion
               semantic-completion-collector-engine
	       (semantic-completion-text))))
    (cond
     ((null comp)
      (semantic-completion-message " [No Match]")
      (ding)
      )
     ((stringp comp)
      (if (string= (semantic-completion-text) comp)
	  (when partial
	    ;; Minibuffer isn't changing AND the text is not unique.
	    ;; Test for partial completion over a word separator character.
	    ;; If there is one available, use that so that SPC can
	    ;; act like a SPC insert key.
	    (let ((newcomp (semantic-collector-current-whitespace-completion
			    semantic-completion-collector-engine)))
	      (when newcomp
		(semantic-completion-delete-text)
		(insert newcomp))
	      ))
	(when partial
	  (let ((orig (semantic-completion-text)))
	    ;; For partial completion, we stop and step over
	    ;; word boundaries.  Use this nifty function to do
	    ;; that calculation for us.
	    (setq comp
		  (semantic-complete-hack-word-boundaries orig comp))))
	;; Do the replacement.
	(semantic-completion-delete-text)
        (insert comp))
      )
     ((and (listp comp) (semantic-tag-p (car comp)))
      (unless (string= (semantic-completion-text)
		       (semantic-tag-name (car comp)))
        ;; A fully unique completion was available.
        (semantic-completion-delete-text)
        (insert (semantic-tag-name (car comp))))
      ;; The match is complete
      (if (= (length comp) 1)
          (semantic-completion-message " [Complete]")
        (semantic-completion-message " [Complete, but not unique]"))
      )
     (t nil))))

(defun semantic-complete-do-completion (&optional partial inline)
  "Do a completion for the current minibuffer.
If PARTIAL, do partial completion stopping at spaces.
if INLINE, then completion is happening inline in a buffer."
  (let* ((collector semantic-completion-collector-engine)
	 (displayor semantic-completion-display-engine)
	 (contents (semantic-completion-text))
	 (ans nil))

    (save-excursion
      (semantic-collector-calculate-completions collector contents partial))
    (let* ((na (semantic-complete-next-action partial)))
      (cond
       ;; We're all done, but only from a very specific
       ;; area of completion.
       ((eq na 'done)
	(semantic-completion-message " [Complete]")
	(setq ans 'done))
       ;; Perform completion
       ((or (eq na 'complete)
	    (eq na 'complete-whitespace))
	(semantic-complete-try-completion partial)
	(setq ans 'complete))
       ;; We need to display the completions.
       ;; Set the completions into the display engine
       ((or (eq na 'display) (eq na 'displayend))
	(semantic-displayor-set-completions
	 displayor
	 (or
518 519 520 521 522 523 524
	  ;; For the below - This caused problems for Chong Yidong
	  ;; when experimenting with the completion engine.  I don't
	  ;; remember what the problem was though, and I wasn't sure why
	  ;; the below two lines were there since they obviously added
	  ;; some odd behavior.  -EML
	  ;; (and (not (eq na 'displayend))
	  ;;      (semantic-collector-current-exact-match collector))
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
	  (semantic-collector-all-completions collector contents))
	 contents)
	;; Ask the displayor to display them.
	(semantic-displayor-show-request displayor))
       ((eq na 'scroll)
	(semantic-displayor-scroll-request displayor)
	)
       ((eq na 'focus)
	(semantic-displayor-focus-next displayor)
	(semantic-displayor-focus-request displayor)
	)
       ((eq na 'empty)
	(semantic-completion-message " [No Match]"))
       (t nil)))
    ans))


;;; ------------------------------------------------------------
;;; INLINE: tag completion harness
;;
;; Unlike the minibuffer, there is no mode nor other traditional
;; means of reading user commands in completion mode.  Instead
;; we use a pre-command-hook to inset in our commands, and to
;; push ourselves out of this mode on alternate keypresses.
(defvar semantic-complete-inline-map
  (let ((km (make-sparse-keymap)))
    (define-key km "\C-i" 'semantic-complete-inline-TAB)
    (define-key km "\M-p" 'semantic-complete-inline-up)
    (define-key km "\M-n" 'semantic-complete-inline-down)
    (define-key km "\C-m" 'semantic-complete-inline-done)
    (define-key km "\C-\M-c" 'semantic-complete-inline-exit)
    (define-key km "\C-g" 'semantic-complete-inline-quit)
    (define-key km "?"
      (lambda () (interactive)
	(describe-variable 'semantic-complete-inline-map)))
    km)
561
  "Keymap used while performing Semantic inline completion.")
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680

(defface semantic-complete-inline-face
  '((((class color) (background dark))
     (:underline "yellow"))
    (((class color) (background light))
     (:underline "brown")))
  "*Face used to show the region being completed inline.
The face is used in `semantic-complete-inline-tag-engine'."
  :group 'semantic-faces)

(defun semantic-complete-inline-text ()
  "Return the text that is being completed inline.
Similar to `minibuffer-contents' when completing in the minibuffer."
  (let ((s (semantic-overlay-start semantic-complete-inline-overlay))
	(e (semantic-overlay-end semantic-complete-inline-overlay)))
    (if (= s e)
	""
      (buffer-substring-no-properties s e ))))

(defun semantic-complete-inline-delete-text ()
  "Delete the text currently being completed in the current buffer."
  (delete-region
   (semantic-overlay-start semantic-complete-inline-overlay)
   (semantic-overlay-end semantic-complete-inline-overlay)))

(defun semantic-complete-inline-done ()
  "This completion thing is DONE, OR, insert a newline."
  (interactive)
  (let* ((displayor semantic-completion-display-engine)
	 (tag (semantic-displayor-current-focus displayor)))
    (if tag
	(let ((txt (semantic-completion-text)))
	  (insert (substring (semantic-tag-name tag)
			     (length txt)))
	  (semantic-complete-inline-exit))

      ;; Get whatever binding RET usually has.
      (let ((fcn
	     (condition-case nil
		 (lookup-key (current-active-maps) (this-command-keys))
	       (error
		;; I don't know why, but for some reason the above
		;; throws an error sometimes.
		(lookup-key (current-global-map) (this-command-keys))
		))))
	(when fcn
	  (funcall fcn)))
      )))

(defun semantic-complete-inline-quit ()
  "Quit an inline edit."
  (interactive)
  (semantic-complete-inline-exit)
  (keyboard-quit))

(defun semantic-complete-inline-exit ()
  "Exit inline completion mode."
  (interactive)
  ;; Remove this hook FIRST!
  (remove-hook 'pre-command-hook 'semantic-complete-pre-command-hook)

  (condition-case nil
      (progn
	(when semantic-completion-collector-engine
	  (semantic-collector-cleanup semantic-completion-collector-engine))
	(when semantic-completion-display-engine
	  (semantic-displayor-cleanup semantic-completion-display-engine))

	(when semantic-complete-inline-overlay
	  (let ((wc (semantic-overlay-get semantic-complete-inline-overlay
					  'window-config-start))
		(buf (semantic-overlay-buffer semantic-complete-inline-overlay))
		)
	    (semantic-overlay-delete semantic-complete-inline-overlay)
	    (setq semantic-complete-inline-overlay nil)
	    ;; DONT restore the window configuration if we just
	    ;; switched windows!
	    (when (eq buf (current-buffer))
	      (set-window-configuration wc))
	    ))

	(setq semantic-completion-collector-engine nil
	      semantic-completion-display-engine nil))
    (error nil))

  ;; Remove this hook LAST!!!
  ;; This will force us back through this function if there was
  ;; some sort of error above.
  (remove-hook 'post-command-hook 'semantic-complete-post-command-hook)

  ;;(message "Exiting inline completion.")
  )

(defun semantic-complete-pre-command-hook ()
  "Used to redefine what commands are being run while completing.
When installed as a `pre-command-hook' the special keymap
`semantic-complete-inline-map' is queried to replace commands normally run.
Commands which edit what is in the region of interest operate normally.
Commands which would take us out of the region of interest, or our
quit hook, will exit this completion mode."
  (let ((fcn (lookup-key semantic-complete-inline-map
			 (this-command-keys) nil)))
    (cond ((commandp fcn)
	   (setq this-command fcn))
	  (t nil)))
  )

(defun semantic-complete-post-command-hook ()
  "Used to determine if we need to exit inline completion mode.
If completion mode is active, check to see if we are within
the bounds of `semantic-complete-inline-overlay', or within
a reasonable distance."
  (condition-case nil
      ;; Exit if something bad happened.
      (if (not semantic-complete-inline-overlay)
	  (progn
	    ;;(message "Inline Hook installed, but overlay deleted.")
	    (semantic-complete-inline-exit))
	;; Exit if commands caused us to exit the area of interest
681 682
	(let ((os (semantic-overlay-get semantic-complete-inline-overlay 'semantic-original-start))
	      (s (semantic-overlay-start semantic-complete-inline-overlay))
683 684 685 686 687 688 689
	      (e (semantic-overlay-end semantic-complete-inline-overlay))
	      (b (semantic-overlay-buffer semantic-complete-inline-overlay))
	      (txt nil)
	      )
	  (cond
	   ;; EXIT when we are no longer in a good place.
	   ((or (not (eq b (current-buffer)))
690 691 692 693
		(< (point) s)
		(< (point) os)
		(> (point) e)
		)
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
	    ;;(message "Exit: %S %S %S" s e (point))
	    (semantic-complete-inline-exit)
	    )
	   ;; Exit if the user typed in a character that is not part
	   ;; of the symbol being completed.
	   ((and (setq txt (semantic-completion-text))
		 (not (string= txt ""))
		 (and (/= (point) s)
		      (save-excursion
			(forward-char -1)
			(not (looking-at "\\(\\w\\|\\s_\\)")))))
	    ;;(message "Non symbol character.")
	    (semantic-complete-inline-exit))
	   ((lookup-key semantic-complete-inline-map
			(this-command-keys) nil)
	    ;; If the last command was one of our completion commands,
	    ;; then do nothing.
	    nil
	    )
	   (t
	    ;; Else, show completions now
	    (semantic-complete-inline-force-display)
	    ))))
    ;; If something goes terribly wrong, clean up after ourselves.
    (error (semantic-complete-inline-exit))))

(defun semantic-complete-inline-force-display ()
  "Force the display of whatever the current completions are.
DO NOT CALL THIS IF THE INLINE COMPLETION ENGINE IS NOT ACTIVE."
  (condition-case e
      (save-excursion
	(let ((collector semantic-completion-collector-engine)
	      (displayor semantic-completion-display-engine)
	      (contents (semantic-completion-text)))
	  (when collector
	    (semantic-collector-calculate-completions
	     collector contents nil)
	    (semantic-displayor-set-completions
	     displayor
	     (semantic-collector-all-completions collector contents)
	     contents)
	    ;; Ask the displayor to display them.
	    (semantic-displayor-show-request displayor))
	  ))
    (error (message "Bug Showing Completions: %S" e))))

(defun semantic-complete-inline-tag-engine
  (collector displayor buffer start end)
  "Perform completion based on semantic tags in a buffer.
743
Argument COLLECTOR is an object which can be used to calculate
744 745
a list of possible hits.  See `semantic-completion-collector-engine'
for details on COLLECTOR.
Glenn Morris's avatar
Glenn Morris committed
746
Argument DISPLAYOR is an object used to display a list of possible
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
completions for a given prefix.  See`semantic-completion-display-engine'
for details on DISPLAYOR.
BUFFER is the buffer in which completion will take place.
START is a location for the start of the full symbol.
If the symbol being completed is \"foo.ba\", then START
is on the \"f\" character.
END is at the end of the current symbol being completed."
  ;; Set us up for doing completion
  (setq semantic-completion-collector-engine collector
	semantic-completion-display-engine displayor)
  ;; Create an overlay
  (setq semantic-complete-inline-overlay
	(semantic-make-overlay start end buffer nil t))
  (semantic-overlay-put semantic-complete-inline-overlay
			'face
			'semantic-complete-inline-face)
  (semantic-overlay-put semantic-complete-inline-overlay
			'window-config-start
			(current-window-configuration))
766 767 768 769
  ;; Save the original start.  We need to exit completion if START
  ;; moves.
  (semantic-overlay-put semantic-complete-inline-overlay
			'semantic-original-start start)
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
  ;; Install our command hooks
  (add-hook 'pre-command-hook 'semantic-complete-pre-command-hook)
  (add-hook 'post-command-hook 'semantic-complete-post-command-hook)
  ;; Go!
  (semantic-complete-inline-force-display)
  )

;;; Inline Completion Keymap Functions
;;
(defun semantic-complete-inline-TAB ()
  "Perform inline completion."
  (interactive)
  (let ((cmpl (semantic-complete-do-completion nil t)))
    (cond
     ((eq cmpl 'complete)
      (semantic-complete-inline-force-display))
     ((eq cmpl 'done)
      (semantic-complete-inline-done))
     ))
  )

(defun semantic-complete-inline-down()
  "Focus forwards through the displayor."
  (interactive)
  (let ((displayor semantic-completion-display-engine))
    (semantic-displayor-focus-next    displayor)
    (semantic-displayor-focus-request displayor)
    ))

(defun semantic-complete-inline-up ()
  "Focus backwards through the displayor."
  (interactive)
  (let ((displayor semantic-completion-display-engine))
    (semantic-displayor-focus-previous displayor)
    (semantic-displayor-focus-request  displayor)
    ))


;;; ------------------------------------------------------------
;;; Interactions between collection and displaying
;;
;; Functional routines used to help collectors communicate with
;; the current displayor, or for the previous section.

(defun semantic-complete-next-action (partial)
  "Determine what the next completion action should be.
PARTIAL is non-nil if we are doing partial completion.
First, the collector can determine if we should perform a completion or not.
If there is nothing to complete, then the displayor determines if we are
to show a completion list, scroll, or perhaps do a focus (if it is capable.)
Expected return values are:
  done -> We have a singular match
  empty -> There are no matches to the current text
  complete -> Perform a completion action
  complete-whitespace -> Complete next whitespace type character.
  display -> Show the list of completions
  scroll -> The completions have been shown, and the user keeps hitting
            the complete button.  If possible, scroll the completions
  focus -> The displayor knows how to shift focus among possible completions.
           Let it do that.
  displayend -> Whatever options the displayor had for repeating options, there
           are none left.  Try something new."
  (let ((ans1 (semantic-collector-next-action
		semantic-completion-collector-engine
		partial))
	(ans2 (semantic-displayor-next-action
		semantic-completion-display-engine))
	)
    (cond
     ;; No collector answer, use displayor answer.
     ((not ans1)
      ans2)
     ;; Displayor selection of 'scroll, 'display, or 'focus trumps
     ;; 'done
     ((and (eq ans1 'done) ans2)
      ans2)
     ;; Use ans1 when we have it.
     (t
      ans1))))



;;; ------------------------------------------------------------
;;; Collection Engines
;;
;; Collection engines can scan tags from the current environment and
;; provide lists of possible completions.
;;
;; General features of the abstract collector:
;; * Cache completion lists between uses
;; * Cache itself per buffer.  Handle reparse hooks
;;
;; Key Interface Functions to implement:
;; * semantic-collector-next-action
;; * semantic-collector-calculate-completions
;; * semantic-collector-try-completion
;; * semantic-collector-all-completions

(defvar semantic-collector-per-buffer-list nil
  "List of collectors active in this buffer.")
(make-variable-buffer-local 'semantic-collector-per-buffer-list)

(defvar semantic-collector-list nil
  "List of global collectors active this session.")

(defclass semantic-collector-abstract ()
  ((buffer :initarg :buffer
	   :type buffer
	   :documentation "Originating buffer for this collector.
Some collectors use a given buffer as a starting place while looking up
tags.")
   (cache :initform nil
	  :type (or null semanticdb-find-result-with-nil)
	  :documentation "Cache of tags.
These tags are re-used during a completion session.
Sometimes these tags are cached between completion sessions.")
   (last-all-completions :initarg nil
			 :type semanticdb-find-result-with-nil
			 :documentation "Last result of `all-completions'.
This result can be used for refined completions as `last-prefix' gets
closer to a specific result.")
   (last-prefix :type string
		:protection :protected
		:documentation "The last queried prefix.
This prefix can be used to cache intermediate completion offers.
making the action of homing in on a token faster.")
   (last-completion :type (or null string)
		    :documentation "The last calculated completion.
This completion is calculated and saved for future use.")
   (last-whitespace-completion :type (or null string)
			       :documentation "The last whitespace completion.
Paul Eggert's avatar
Paul Eggert committed
901
For partial completion, SPC will disambiguate over whitespace type
902 903 904 905 906 907 908 909 910 911 912 913
characters.  This is the last calculated version.")
   (current-exact-match :type list
			:protection :protected
			:documentation "The list of matched tags.
When tokens are matched, they are added to this list.")
   )
  "Root class for completion engines.
The baseclass provides basic functionality for interacting with
a completion displayor object, and tracking the current progress
of a completion."
  :abstract t)

Chong Yidong's avatar
Chong Yidong committed
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
;;; Smart completion collector
(defclass semantic-collector-analyze-completions (semantic-collector-abstract)
  ((context :initarg :context
	    :type semantic-analyze-context
	    :documentation "An analysis context.
Specifies some context location from whence completion lists will be drawn."
	    )
   (first-pass-completions :type list
			   :documentation "List of valid completion tags.
This list of tags is generated when completion starts.  All searches
derive from this list.")
   )
  "Completion engine that uses the context analyzer to provide options.
The only options available for completion are those which can be logically
inserted into the current context.")

(defmethod semantic-collector-calculate-completions-raw
  ((obj semantic-collector-analyze-completions) prefix completionlist)
  "calculate the completions for prefix from completionlist."
  ;; if there are no completions yet, calculate them.
  (if (not (slot-boundp obj 'first-pass-completions))
      (oset obj first-pass-completions
	    (semantic-analyze-possible-completions (oref obj context))))
  ;; search our cached completion list.  make it look like a semanticdb
  ;; results type.
  (list (cons (with-current-buffer (oref (oref obj context) buffer)
		semanticdb-current-table)
	      (semantic-find-tags-for-completion
	       prefix
	       (oref obj first-pass-completions)))))

945 946 947 948 949 950
(defmethod semantic-collector-cleanup ((obj semantic-collector-abstract))
  "Clean up any mess this collector may have."
  nil)

(defmethod semantic-collector-next-action
  ((obj semantic-collector-abstract) partial)
Chong Yidong's avatar
Chong Yidong committed
951
  "What should we do next?  OBJ can be used to determine the next action.
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
PARTIAL indicates if we are doing a partial completion."
  (if (and (slot-boundp obj 'last-completion)
	   (string= (semantic-completion-text) (oref obj last-completion)))
      (let* ((cem (semantic-collector-current-exact-match obj))
	     (cemlen (semanticdb-find-result-length cem))
	     (cac (semantic-collector-all-completions
		   obj (semantic-completion-text)))
	     (caclen (semanticdb-find-result-length cac)))
	(cond ((and cem (= cemlen 1)
		    cac (> caclen 1)
		    (eq last-command this-command))
	       ;; Defer to the displayor...
	       nil)
	      ((and cem (= cemlen 1))
	       'done)
	      ((and (not cem) (not cac))
	       'empty)
	      ((and partial (semantic-collector-try-completion-whitespace
			     obj (semantic-completion-text)))
	       'complete-whitespace)))
    'complete))

(defmethod semantic-collector-last-prefix= ((obj semantic-collector-abstract)
					    last-prefix)
  "Return non-nil if OBJ's prefix matches PREFIX."
  (and (slot-boundp obj 'last-prefix)
       (string= (oref obj last-prefix) last-prefix)))

(defmethod semantic-collector-get-cache ((obj semantic-collector-abstract))
  "Get the raw cache of tags for completion.
Calculate the cache if there isn't one."
  (or (oref obj cache)
      (semantic-collector-calculate-cache obj)))

(defmethod semantic-collector-calculate-completions-raw
  ((obj semantic-collector-abstract) prefix completionlist)
  "Calculate the completions for prefix from completionlist.
Output must be in semanticdb Find result format."
  ;; Must output in semanticdb format
991 992 993 994
  (unless completionlist
    (setq completionlist
	  (or (oref obj cache)
	      (semantic-collector-calculate-cache obj))))
995
  (let ((table (with-current-buffer (oref obj buffer)
996 997 998 999 1000
		 semanticdb-current-table))
	(result (semantic-find-tags-for-completion
		 prefix
		 ;; To do this kind of search with a pre-built completion
		 ;; list, we need to strip it first.
1001
		 (semanticdb-strip-find-results completionlist))))
1002 1003 1004 1005 1006 1007 1008 1009
    (if result
	(list (cons table result)))))

(defmethod semantic-collector-calculate-completions
  ((obj semantic-collector-abstract) prefix partial)
  "Calculate completions for prefix as setup for other queries."
  (let* ((case-fold-search semantic-case-fold)
	 (same-prefix-p (semantic-collector-last-prefix= obj prefix))
Chong Yidong's avatar
Chong Yidong committed
1010 1011
	 (last-prefix (and (slot-boundp obj 'last-prefix)
			   (oref obj last-prefix)))
1012
	 (completionlist
Chong Yidong's avatar
Chong Yidong committed
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
	  (cond ((or same-prefix-p
		     (and last-prefix (eq (compare-strings
					   last-prefix 0 nil
					   prefix 0 (length last-prefix)) t)))
		 ;; We have the same prefix, or last-prefix is a
		 ;; substring of the of new prefix, in which case we are
		 ;; refining our symbol so just re-use cache.
		 (oref obj last-all-completions))
		((and last-prefix
		      (> (length prefix) 1)
		      (eq (compare-strings
			   prefix 0 nil
			   last-prefix 0 (length prefix)) t))
		   ;; The new prefix is a substring of the old
		   ;; prefix, and it's longer than one character.
		   ;; Perform a full search to pull in additional
		   ;; matches.
		 (let ((context (semantic-analyze-current-context (point))))
		   ;; Set new context and make first-pass-completions
		   ;; unbound so that they are newly calculated.
		   (oset obj context context)
		   (when (slot-boundp obj 'first-pass-completions)
		     (slot-makeunbound obj 'first-pass-completions)))
		 nil)))
1037 1038 1039 1040
	 ;; Get the result
	 (answer (if same-prefix-p
		     completionlist
		   (semantic-collector-calculate-completions-raw
Chong Yidong's avatar
Chong Yidong committed
1041
		    obj prefix completionlist)))
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
	 (completion nil)
	 (complete-not-uniq nil)
	 )
    ;;(semanticdb-find-result-test answer)
    (when (not same-prefix-p)
      ;; Save results if it is interesting and beneficial
      (oset obj last-prefix prefix)
      (oset obj last-all-completions answer))
    ;; Now calculate the completion.
    (setq completion (try-completion
		      prefix
		      (semanticdb-strip-find-results answer)))
    (oset obj last-whitespace-completion nil)
    (oset obj current-exact-match nil)
    ;; Only do this if a completion was found.  Letting a nil in
    ;; could cause a full semanticdb search by accident.
    (when completion
      (oset obj last-completion
	    (cond
	     ;; Unique match in AC.  Last completion is a match.
	     ;; Also set the current-exact-match.
	     ((eq completion t)
	      (oset obj current-exact-match answer)
	      prefix)
	     ;; It may be complete (a symbol) but still not unique.
	     ;; We can capture a match
	     ((setq complete-not-uniq
		    (semanticdb-find-tags-by-name
		     prefix
		     answer))
	      (oset obj current-exact-match
		    complete-not-uniq)
	      prefix
	      )
	     ;; Non unique match, return the string that handles
	     ;; completion
	     (t (or completion prefix))
	     )))
    ))

(defmethod semantic-collector-try-completion-whitespace
  ((obj semantic-collector-abstract) prefix)
Paul Eggert's avatar
Paul Eggert committed
1084
  "For OBJ, do whitespace completion based on PREFIX.
1085
This implies that if there are two completions, one matching
Paul Eggert's avatar
Paul Eggert committed
1086
the test \"prefix\\>\", and one not, the one matching the full
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
word version of PREFIX will be chosen, and that text returned.
This function requires that `semantic-collector-calculate-completions'
has been run first."
  (let* ((ac (semantic-collector-all-completions obj prefix))
	 (matchme (concat "^" prefix "\\>"))
	 (compare (semanticdb-find-tags-by-name-regexp matchme ac))
	 (numtag (semanticdb-find-result-length compare))
	 )
    (if compare
	(let* ((idx 0)
	       (cutlen (1+ (length prefix)))
	       (twws (semanticdb-find-result-nth compare idx)))
	  ;; Is our tag with whitespace a match that has whitespace
	  ;; after it, or just an already complete symbol?
	  (while (and (< idx numtag)
		      (< (length (semantic-tag-name (car twws))) cutlen))
	    (setq idx (1+ idx)
		  twws (semanticdb-find-result-nth compare idx)))
	  (when (and twws (car-safe twws))
	    ;; If COMPARE has succeeded, then we should take the very
	    ;; first match, and extend prefix by one character.
	    (oset obj last-whitespace-completion
		  (substring (semantic-tag-name (car twws))
			     0 cutlen))))
      )))


(defmethod semantic-collector-current-exact-match ((obj semantic-collector-abstract))
  "Return the active valid MATCH from the semantic collector.
For now, just return the first element from our list of available
matches.  For semanticdb based results, make sure the file is loaded
into a buffer."
  (when (slot-boundp obj 'current-exact-match)
    (oref obj current-exact-match)))

(defmethod semantic-collector-current-whitespace-completion ((obj semantic-collector-abstract))
  "Return the active whitespace completion value."
  (when (slot-boundp obj 'last-whitespace-completion)
    (oref obj last-whitespace-completion)))

(defmethod semantic-collector-get-match ((obj semantic-collector-abstract))
  "Return the active valid MATCH from the semantic collector.
For now, just return the first element from our list of available
matches.  For semanticdb based results, make sure the file is loaded
into a buffer."
  (when (slot-boundp obj 'current-exact-match)
    (semanticdb-find-result-nth-in-buffer (oref obj current-exact-match) 0)))

(defmethod semantic-collector-all-completions
  ((obj semantic-collector-abstract) prefix)
  "For OBJ, retrieve all completions matching PREFIX.
The returned list consists of all the tags currently
matching PREFIX."
  (when (slot-boundp obj 'last-all-completions)
    (oref obj last-all-completions)))

(defmethod semantic-collector-try-completion
  ((obj semantic-collector-abstract) prefix)
  "For OBJ, attempt to match PREFIX.
See `try-completion' for details on how this works.
Return nil for no match.
Return a string for a partial match.
For a unique match of PREFIX, return the list of all tags
with that name."
  (if (slot-boundp obj 'last-completion)
      (oref obj last-completion)))

(defmethod semantic-collector-calculate-cache
  ((obj semantic-collector-abstract))
  "Calculate the completion cache for OBJ."
  nil
  )

(defmethod semantic-collector-flush ((this semantic-collector-abstract))
  "Flush THIS collector object, clearing any caches and prefix."
  (oset this cache nil)
  (slot-makeunbound this 'last-prefix)
  (slot-makeunbound this 'last-completion)
  (slot-makeunbound this 'last-all-completions)
  (slot-makeunbound this 'current-exact-match)
  )

;;; PER BUFFER
;;
(defclass semantic-collector-buffer-abstract (semantic-collector-abstract)
  ()
  "Root class for per-buffer completion engines.
These collectors track themselves on a per-buffer basis."
  :abstract t)

(defmethod constructor :STATIC ((this semantic-collector-buffer-abstract)
				newname &rest fields)
  "Reuse previously created objects of this type in buffer."
  (let ((old nil)
	(bl semantic-collector-per-buffer-list))
    (while (and bl (null old))
1183
      (if (eq (eieio-object-class (car bl)) this)
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
	  (setq old (car bl))))
    (unless old
      (let ((new (call-next-method)))
	(add-to-list 'semantic-collector-per-buffer-list new)
	(setq old new)))
    (slot-makeunbound old 'last-completion)
    (slot-makeunbound old 'last-prefix)
    (slot-makeunbound old 'current-exact-match)
    old))

;; Buffer specific collectors should flush themselves
(defun semantic-collector-buffer-flush (newcache)
  "Flush all buffer collector objects.
NEWCACHE is the new tag table, but we ignore it."
  (condition-case nil
      (let ((l semantic-collector-per-buffer-list))
	(while l
	  (if (car l) (semantic-collector-flush (car l)))
	  (setq l (cdr l))))
    (error nil)))

(add-hook 'semantic-after-toplevel-cache-change-hook
	  'semantic-collector-buffer-flush)

;;; DEEP BUFFER SPECIFIC COMPLETION
;;
(defclass semantic-collector-buffer-deep
  (semantic-collector-buffer-abstract)
  ()
  "Completion engine for tags in the current buffer.
Chong Yidong's avatar
Chong Yidong committed
1214
When searching for a tag, uses semantic deep search functions.
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
Basics search only in the current buffer.")

(defmethod semantic-collector-calculate-cache
  ((obj semantic-collector-buffer-deep))
  "Calculate the completion cache for OBJ.
Uses `semantic-flatten-tags-table'"
  (oset obj cache
	;; Must create it in SEMANTICDB find format.
	;; ( ( DBTABLE TAG TAG ... ) ... )
	(list
	 (cons semanticdb-current-table
	       (semantic-flatten-tags-table (oref obj buffer))))))

;;; PROJECT SPECIFIC COMPLETION
;;
(defclass semantic-collector-project-abstract (semantic-collector-abstract)
  ((path :initarg :path
	 :initform nil
	 :documentation "List of database tables to search.
At creation time, it can be anything accepted by
`semanticdb-find-translate-path' as a PATH argument.")
   )
  "Root class for project wide completion engines.
Uses semanticdb for searching all tags in the current project."
  :abstract t)

;;; Project Search
(defclass semantic-collector-project (semantic-collector-project-abstract)
  ()
  "Completion engine for tags in a project.")


(defmethod semantic-collector-calculate-completions-raw
  ((obj semantic-collector-project) prefix completionlist)
  "Calculate the completions for prefix from completionlist."
  (semanticdb-find-tags-for-completion prefix (oref obj path)))

;;; Brutish Project search
(defclass semantic-collector-project-brutish (semantic-collector-project-abstract)
  ()
  "Completion engine for tags in a project.")

1257 1258 1259
(declare-function semanticdb-brute-deep-find-tags-for-completion
		  "semantic/db-find")

1260 1261 1262
(defmethod semantic-collector-calculate-completions-raw
  ((obj semantic-collector-project-brutish) prefix completionlist)
  "Calculate the completions for prefix from completionlist."
1263
  (require 'semantic/db-find)
1264 1265
  (semanticdb-brute-deep-find-tags-for-completion prefix (oref obj path)))

Chong Yidong's avatar
Chong Yidong committed
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
;;; Current Datatype member search.
(defclass semantic-collector-local-members (semantic-collector-project-abstract)
  ((scope :initform nil
	  :type (or null semantic-scope-cache)
	  :documentation
	  "The scope the local members are being completed from."))
  "Completion engine for tags in a project.")

(defmethod semantic-collector-calculate-completions-raw
  ((obj semantic-collector-local-members) prefix completionlist)
  "Calculate the completions for prefix from completionlist."
  (let* ((scope (or (oref obj scope)
		    (oset obj scope (semantic-calculate-scope))))
	 (localstuff (oref scope scope)))
    (list
     (cons
      (oref scope :table)
      (semantic-find-tags-for-completion prefix localstuff)))))
    ;(semanticdb-brute-deep-find-tags-for-completion prefix (oref obj path))))

1286 1287 1288 1289 1290 1291 1292

;;; ------------------------------------------------------------
;;; Tag List Display Engines
;;
;; A typical displayor accepts a pre-determined list of completions
;; generated by a collector.  This format is in semanticdb search
;; form.  This vaguely standard form is a bit challenging to navigate
Juanma Barranquero's avatar
Juanma Barranquero committed
1293
;; because the tags do not contain buffer info, but the file associated
Glenn Morris's avatar
Glenn Morris committed
1294
;; with the tags precedes the tag in the list.
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
;;
;; Basic displayors don't care, and can strip the results.
;; Advanced highlighting displayors need to know when they need
;; to load a file so that the tag in question can be highlighted.
;;
;; Key interface methods to a displayor are:
;; * semantic-displayor-next-action
;; * semantic-displayor-set-completions
;; * semantic-displayor-current-focus
;; * semantic-displayor-show-request
;; * semantic-displayor-scroll-request
;; * semantic-displayor-focus-request

(defclass semantic-displayor-abstract ()
  ((table :type (or null semanticdb-find-result-with-nil)
	  :initform nil
	  :protection :protected
	  :documentation "List of tags this displayor is showing.")
   (last-prefix :type string
		:protection :protected
		:documentation "Prefix associated with slot `table'")
   )
  "Abstract displayor baseclass.
Manages the display of some number of tags.
Provides the basics for a displayor, including interacting with
a collector, and tracking tables of completion to display."
  :abstract t)

(defmethod semantic-displayor-cleanup ((obj semantic-displayor-abstract))
  "Clean up any mess this displayor may have."
  nil)

(defmethod semantic-displayor-next-action ((obj semantic-displayor-abstract))
  "The next action to take on the minibuffer related to display."
  (if (and (slot-boundp obj 'last-prefix)
Chong Yidong's avatar
Chong Yidong committed
1330 1331 1332
	   (or (eq this-command 'semantic-complete-inline-TAB)
	       (and (string= (oref obj last-prefix) (semantic-completion-text))
		    (eq last-command this-command))))
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
      'scroll
    'display))

(defmethod semantic-displayor-set-completions ((obj semantic-displayor-abstract)
					       table prefix)
  "Set the list of tags to be completed over to TABLE."
  (oset obj table table)
  (oset obj last-prefix prefix))

(defmethod semantic-displayor-show-request ((obj semantic-displayor-abstract))
  "A request to show the current tags table."
  (ding))

(defmethod semantic-displayor-focus-request ((obj semantic-displayor-abstract))
  "A request to for the displayor to focus on some tag option."
  (ding))

(defmethod semantic-displayor-scroll-request ((obj semantic-displayor-abstract))
  "A request to for the displayor to scroll the completion list (if needed)."
  (scroll-other-window))

(defmethod semantic-displayor-focus-previous ((obj semantic-displayor-abstract))
  "Set the current focus to the previous item."
  nil)

(defmethod semantic-displayor-focus-next ((obj semantic-displayor-abstract))
  "Set the current focus to the next item."
  nil)

(defmethod semantic-displayor-current-focus ((obj semantic-displayor-abstract))
  "Return a single tag currently in focus.
This object type doesn't do focus, so will never have a focus object."
  nil)

;; Traditional displayor
(defcustom semantic-completion-displayor-format-tag-function
  #'semantic-format-tag-name
  "*A Tag format function to use when showing completions."
  :group 'semantic
  :type semantic-format-tag-custom-list)

(defclass semantic-displayor-traditional (semantic-displayor-abstract)
  ()
  "Display options in *Completions* buffer.
Traditional display mechanism for a list of possible completions.
Completions are showin in a new buffer and listed with the ability
to click on the items to aid in completion.")

(defmethod semantic-displayor-show-request ((obj semantic-displayor-traditional))
  "A request to show the current tags table."

Paul Eggert's avatar
Paul Eggert committed
1384
  ;; NOTE TO SELF.  Find the character to type next, and emphasize it.
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407

  (with-output-to-temp-buffer "*Completions*"
    (display-completion-list
     (mapcar semantic-completion-displayor-format-tag-function
	     (semanticdb-strip-find-results (oref obj table))))
    )
  )

;;; Abstract baseclass for any displayor which supports focus
(defclass semantic-displayor-focus-abstract (semantic-displayor-abstract)
  ((focus :type number
	  :protection :protected
	  :documentation "A tag index from `table' which has focus.
Multiple calls to the display function can choose to focus on a
given tag, by highlighting its location.")
   (find-file-focus
    :allocation :class
    :initform nil
    :documentation
    "Non-nil if focusing requires a tag's buffer be in memory.")
   )
  "Abstract displayor supporting `focus'.
A displayor which has the ability to focus in on one tag.
Paul Eggert's avatar
Paul Eggert committed
1408
Focusing is a way of differentiating among multiple tags
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
which have the same name."
  :abstract t)

(defmethod semantic-displayor-next-action ((obj semantic-displayor-focus-abstract))
  "The next action to take on the minibuffer related to display."
  (if (and (slot-boundp obj 'last-prefix)
	   (string= (oref obj last-prefix) (semantic-completion-text))
	   (eq last-command this-command))
      (if (and
	   (slot-boundp obj 'focus)
	   (slot-boundp obj 'table)
	   (<= (semanticdb-find-result-length (oref obj table))
	       (1+ (oref obj focus))))
	  ;; We are at the end of the focus road.
	  'displayend
	;; Focus on some item.
	'focus)
    'display))

(defmethod semantic-displayor-set-completions ((obj semantic-displayor-focus-abstract)
					       table prefix)
  "Set the list of tags to be completed over to TABLE."
  (call-next-method)
  (slot-makeunbound obj 'focus))

(defmethod semantic-displayor-focus-previous ((obj semantic-displayor-focus-abstract))
  "Set the current focus to the previous item.
Not meaningful return value."
  (when (and (slot-boundp obj 'table) (oref obj table))
    (with-slots (table) obj
      (if (or (not (slot-boundp obj 'focus))
	      (<= (oref obj focus) 0))
	  (oset obj focus (1- (semanticdb-find-result-length table)))
	(oset obj focus (1- (oref obj focus)))
	)
      )))

(defmethod semantic-displayor-focus-next ((obj semantic-displayor-focus-abstract))
  "Set the current focus to the next item.
Not meaningful return value."
  (when (and (slot-boundp obj 'table) (oref obj table))
    (with-slots (table) obj
      (if (not (slot-boundp obj 'focus))
	  (oset obj focus 0)
	(oset obj focus (1+ (oref obj focus)))
	)
      (if (<= (semanticdb-find-result-length table) (oref obj focus))
	  (oset obj focus 0))
      )))

(defmethod semantic-displayor-focus-tag ((obj semantic-displayor-focus-abstract))
  "Return the next tag OBJ should focus on."
  (when (and (slot-boundp obj 'table) (oref obj table))
    (with-slots (table) obj
      (semanticdb-find-result-nth table (oref obj focus)))))

(defmethod semantic-displayor-current-focus ((obj semantic-displayor-focus-abstract))
  "Return the tag currently in focus, or call parent method."
  (if (and (slot-boundp obj 'focus)
	   (slot-boundp obj 'table)
	   ;; Only return the current focus IFF the minibuffer reflects
	   ;; the list this focus was derived from.
	   (slot-boundp obj 'last-prefix)
	   (string= (semantic-completion-text) (oref obj last-prefix))
	   )
      ;; We need to focus
      (if (oref obj find-file-focus)
	  (semanticdb-find-result-nth-in-buffer (oref obj table) (oref obj focus))
	;; result-nth returns a cons with car being the tag, and cdr the
	;; database.
	(car (semanticdb-find-result-nth (oref obj table) (oref obj focus))))
    ;; Do whatever
    (call-next-method)))

;;; Simple displayor which performs traditional display completion,
;; and also focuses with highlighting.
(defclass semantic-displayor-traditional-with-focus-highlight
  (semantic-displayor-focus-abstract semantic-displayor-traditional)
  ((find-file-focus :initform t))
  "Display completions in *Completions* buffer, with focus highlight.
A traditional displayor which can focus on a tag by showing it.
Same as `semantic-displayor-traditional', but with selection between
multiple tags with the same name done by 'focusing' on the source
location of the different tags to differentiate them.")

(defmethod semantic-displayor-focus-request
  ((obj semantic-displayor-traditional-with-focus-highlight))
  "Focus in on possible tag completions.
Focus is performed by cycling through the tags and highlighting
one in the source buffer."
  (let* ((tablelength (semanticdb-find-result-length (oref obj table)))
	 (focus (semantic-displayor-focus-tag obj))
	 ;; Raw tag info.
	 (rtag (car focus))
	 (rtable (cdr focus))
	 ;; Normalize
	 (nt (semanticdb-normalize-one-tag rtable rtag))
	 (tag (cdr nt))
	 (table (car nt))
Chong Yidong's avatar
Chong Yidong committed
1508
	 (curwin (selected-window)))
Paul Eggert's avatar
Paul Eggert committed
1509
    ;; If we fail to normalize, reset.
1510 1511 1512 1513 1514 1515
    (when (not tag) (setq table rtable tag rtag))
    ;; Do the focus.
    (let ((buf (or (semantic-tag-buffer tag)
		   (and table (semanticdb-get-buffer table)))))
      ;; If no buffer is provided, then we can make up a summary buffer.
      (when (not buf)
1516
	(with-current-buffer (get-buffer-create "*Completion Focus*")
1517 1518 1519 1520 1521
	  (erase-buffer)
	  (insert "Focus on tag: \n")
	  (insert (semantic-format-tag-summarize tag nil t) "\n\n")
	  (when table
	    (insert "From table: \n")
1522
	    (insert (eieio-object-name table) "\n\n"))
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
	  (when buf
	    (insert "In buffer: \n\n")
	    (insert (format "%S" buf)))
	  (setq buf (current-buffer))))
      ;; Show the tag in the buffer.
      (if (get-buffer-window buf)
	  (select-window (get-buffer-window buf))
	(switch-to-buffer-other-window buf t)
	(select-window (get-buffer-window buf)))
      ;; Now do some positioning
Chong Yidong's avatar
Chong Yidong committed
1533 1534 1535 1536 1537 1538 1539 1540
      (when (semantic-tag-with-position-p tag)
	;; Full tag positional information available
	(goto-char (semantic-tag-start tag))
	;; This avoids a dangerous problem if we just loaded a tag
	;; from a file, but the original position was not updated
	;; in the TAG variable we are currently using.
	(semantic-momentary-highlight-tag (semantic-current-tag)))
      (select-window curwin)
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
      ;; Calculate text difference between contents and the focus item.
      (let* ((mbc (semantic-completion-text))
	     (ftn (semantic-tag-name tag))
	     (diff (substring ftn (length mbc))))
	(semantic-completion-message
	 (format "%s [%d of %d matches]" diff (1+ (oref obj focus)) tablelength)))
      )))


;;; Tooltip completion lister
;;
;; Written and contributed by Masatake YAMATO <jet@gyve.org>
;;
;; Modified by Eric Ludlam for
;; * Safe compatibility for tooltip free systems.
;; * Don't use 'avoid package for tooltip positioning.

Chong Yidong's avatar
Chong Yidong committed
1558 1559 1560 1561 1562 1563 1564 1565 1566
;;;###autoload
(defcustom semantic-displayor-tooltip-mode 'standard
  "Mode for the tooltip inline completion.

Standard: Show only `semantic-displayor-tooltip-initial-max-tags'
number of completions initially.  Pressing TAB will show the
extended set.

Quiet: Only show completions when we have narrowed all
Paul Eggert's avatar
Paul Eggert committed
1567
possibilities down to a maximum of
Chong Yidong's avatar
Chong Yidong committed
1568 1569 1570 1571 1572 1573 1574 1575
`semantic-displayor-tooltip-initial-max-tags' tags.  Pressing TAB
multiple times will also show completions.

Verbose: Always show all completions available.

The absolute maximum number of completions for all mode is
determined through `semantic-displayor-tooltip-max-tags'."
  :group 'semantic
Glenn Morris's avatar
Glenn Morris committed
1576
  :version "24.3"
Chong Yidong's avatar
Chong Yidong committed
1577 1578 1579 1580 1581 1582 1583 1584 1585
  :type '(choice (const :tag "Standard" standard)
		 (const :tag "Quiet" quiet)
		 (const :tag "Verbose" verbose)))

;;;###autoload
(defcustom semantic-displayor-tooltip-initial-max-tags 5
  "Maximum number of tags to be displayed initially.
See doc-string of `semantic-displayor-tooltip-mode' for details."
  :group 'semantic
Glenn Morris's avatar
Glenn Morris committed
1586
  :version "24.3"
Chong Yidong's avatar
Chong Yidong committed
1587 1588 1589
  :type 'integer)

(defcustom semantic-displayor-tooltip-max-tags 25
Glenn Morris's avatar
Glenn Morris committed
1590
  "The maximum number of tags to be displayed.
Chong Yidong's avatar
Chong Yidong committed
1591 1592 1593 1594 1595
Maximum number of completions where we have activated the
extended completion list through typing TAB or SPACE multiple
times.  This limit needs to fit on your screen!

Note: If available, customizing this variable increases
Glenn Morris's avatar
Glenn Morris committed
1596 1597 1598 1599 1600 1601 1602 1603 1604
`x-max-tooltip-size' to force over-sized tooltips when necessary.
This will not happen if you directly set this variable via `setq'."
  :group 'semantic
  :version "24.3"
  :type 'integer
  :set '(lambda (sym var)
	  (set-default sym var)
	  (when (boundp 'x-max-tooltip-size)
	    (setcdr x-max-tooltip-size (max (1+ var) (cdr x-max-tooltip-size))))))
Chong Yidong's avatar
Chong Yidong committed
1605 1606


1607
(defclass semantic-displayor-tooltip (semantic-displayor-traditional)
Chong Yidong's avatar
Chong Yidong committed
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
  ((mode :initarg :mode
	 :initform
	 (symbol-value 'semantic-displayor-tooltip-mode)
	 :documentation
	 "See `semantic-displayor-tooltip-mode'.")
   (max-tags-initial :initarg max-tags-initial
		     :initform
		     (symbol-value 'semantic-displayor-tooltip-initial-max-tags)
		     :documentation
		     "See `semantic-displayor-tooltip-initial-max-tags'.")
1618 1619 1620 1621 1622 1623 1624
   (typing-count :type integer
		 :initform 0
		 :documentation
		 "Counter holding how many times the user types space or tab continuously before showing tags.")
   (shown        :type boolean
		 :initform nil
		 :documentation
Chong Yidong's avatar
Chong Yidong committed
1625
		 "Flag representing whether tooltip has been shown yet.")
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
   )
  "Display completions options in a tooltip.
Display mechanism using tooltip for a list of possible completions.")

(defmethod initialize-instance :AFTER ((obj semantic-displayor-tooltip) &rest args)
  "Make sure we have tooltips required."
  (condition-case nil
      (require 'tooltip)
    (error nil))
  )

1637 1638
(defvar tooltip-mode)

1639 1640 1641 1642 1643 1644 1645 1646
(defmethod semantic-displayor-show-request ((obj semantic-displayor-tooltip))
  "A request to show the current tags table."
  (if (or (not (featurep 'tooltip)) (not tooltip-mode))
      ;; If we cannot use tooltips, then go to the normal mode with
      ;; a traditional completion buffer.
      (call-next-method)
    (let* ((tablelong (semanticdb-strip-find-results (oref obj table)))
	   (table (semantic-unique-tag-table-by-name tablelong))
Chong Yidong's avatar
Chong Yidong committed
1647 1648
	   (completions (mapcar semantic-completion-displayor-format-tag-function table))
	   (numcompl (length completions))
1649
	   (typing-count (oref obj typing-count))
Chong Yidong's avatar
Chong Yidong committed
1650 1651
	   (mode (oref obj mode))
	   (max-tags (oref obj max-tags-initial))
1652
	   (matchtxt (semantic-completion-text))
Chong Yidong's avatar
Chong Yidong committed
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
	   msg msg-tail)
      ;; Keep a count of the consecutive completion commands entered by the user.
      (if (and (stringp (this-command-keys))
	       (string= (this-command-keys) "\C-i"))
	  (oset obj typing-count (1+ (oref obj typing-count)))
	(oset obj typing-count 0))
      (cond
       ((eq mode 'quiet)
	;; Switch back to standard mode if user presses key more than 5 times.
	(when (>= (oref obj typing-count) 5)
	  (oset obj mode 'standard)
	  (setq mode 'standard)
	  (message "Resetting inline-mode to 'standard'."))
	(when (and (> numcompl max-tags)
		   (< (oref obj typing-count) 2))
	  ;; Discretely hint at completion availability.
	  (setq msg "...")))
       ((eq mode 'verbose)
	;; Always show extended match set.
1672
	(oset obj max-tags-initial semantic-displayor-tooltip-max-tags)
Chong Yidong's avatar
Chong Yidong committed
1673 1674 1675
	(setq max-tags semantic-displayor-tooltip-max-tags)))
      (unless msg
	(oset obj shown t)
1676
	(cond
Chong Yidong's avatar
Chong Yidong committed
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
	 ((> numcompl max-tags)
	  ;; We have too many items, be brave and truncate 'completions'.
	  (setcdr (nthcdr (1- max-tags) completions) nil)
	  (if (= max-tags semantic-displayor-tooltip-initial-max-tags)
	      (setq msg-tail (concat "\n[<TAB> " (number-to-string (- numcompl max-tags)) " more]"))
	    (setq msg-tail (concat "\n[<n/a> " (number-to-string (- numcompl max-tags)) " more]"))
	    (when (>= (oref obj typing-count) 2)
	      (message "Refine search to display results beyond the '%s' limit"
		       (symbol-name 'semantic-complete-inline-max-tags-extended)))))
	 ((= numcompl 1)
	  ;; two possible cases
	  ;; 1. input text != single match - we found a unique completion!
	  ;; 2. input text == single match - we found no additional matches, it's just the input text!
	  (when (string= matchtxt (semantic-tag-name (car table)))
	    (setq msg "[COMPLETE]\n")))
	 ((zerop numcompl)
	  (oset obj shown nil)
	  ;; No matches, say so if in verbose mode!
	  (when semantic-idle-scheduler-verbose-flag
	    (setq msg "[NO MATCH]"))))
	;; Create the tooltip text.
	(setq msg (concat msg (mapconcat 'identity completions "\n"))))
      ;; Add any tail info.
      (setq msg (concat msg msg-tail))
      ;; Display tooltip.
      (when (not (eq msg ""))
	(semantic-displayor-tooltip-show msg)))))
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720

;;; Compatibility
;;
(eval-and-compile
  (if (fboundp 'window-inside-edges)
      ;; Emacs devel.
      (defalias 'semantic-displayor-window-edges
        'window-inside-edges)
    ;; Emacs 21
    (defalias 'semantic-displayor-window-edges
      'window-edges)
    ))

(defun semantic-displayor-point-position ()
  "Return the location of POINT as positioned on the selected frame.
Return a cons cell (X . Y)"
  (let* ((frame (selected-frame))
Chong Yidong's avatar
Chong Yidong committed
1721 1722 1723 1724
	 (left (or (car-safe (cdr-safe (frame-parameter frame 'left)))
		   (frame-parameter frame 'left)))
         (top (or (car-safe (cdr-safe (frame-parameter frame 'top)))
		  (frame-parameter frame 'top)))
1725 1726 1727 1728 1729 1730
	 (point-pix-pos (posn-x-y (posn-at-point)))
	 (edges (window-inside-pixel-edges (selected-window))))
    (cons (+ (car point-pix-pos) (car edges) left)
          (+ (cdr point-pix-pos) (cadr edges) top))))


1731 1732 1733
(defvar tooltip-frame-parameters)
(declare-function tooltip-show "tooltip" (text &optional use-echo-area))

1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
(defun semantic-displayor-tooltip-show (text)
  "Display a tooltip with TEXT near cursor."
  (let ((point-pix-pos (semantic-displayor-point-position))
	(tooltip-frame-parameters
	 (append tooltip-frame-parameters nil)))
    (push
     (cons 'left (+ (car point-pix-pos) (frame-char-width)))
     tooltip-frame-parameters)
    (push
     (cons 'top (+ (cdr point-pix-pos) (frame-char-height)))
     tooltip-frame-parameters)
    (tooltip-show text)))

(defmethod semantic-displayor-scroll-request ((obj semantic-displayor-tooltip))
  "A request to for the displayor to scroll the completion list (if needed)."
  ;; Do scrolling in the tooltip.
Chong Yidong's avatar
Chong Yidong committed
1750
  (oset obj max-tags-initial 30)
1751 1752 1753 1754 1755