1 ;;; thingatpt.el --- get the `thing' at point -*- lexical-binding:t -*-
3 ;; Copyright (C) 1991-1998, 2000-2016 Free Software Foundation, Inc.
5 ;; Author: Mike Williams <mikew@gopher.dosli.govt.nz>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: extensions, matching, mouse
8 ;; Created: Thu Mar 28 13:48:23 1991
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; This file provides routines for getting the "thing" at the location of
28 ;; point, whatever that "thing" happens to be. The "thing" is defined by
29 ;; its beginning and end positions in the buffer.
31 ;; The function bounds-of-thing-at-point finds the beginning and end
32 ;; positions by moving first forward to the end of the "thing", and then
33 ;; backwards to the beginning. By default, it uses the corresponding
34 ;; forward-"thing" operator (eg. forward-word, forward-line).
36 ;; Special cases are allowed for using properties associated with the named
39 ;; forward-op Function to call to skip forward over a "thing" (or
40 ;; with a negative argument, backward).
42 ;; beginning-op Function to call to skip to the beginning of a "thing".
43 ;; end-op Function to call to skip to the end of a "thing".
45 ;; Reliance on existing operators means that many `things' can be accessed
46 ;; without further code: eg.
47 ;; (thing-at-point 'line)
48 ;; (thing-at-point 'page)
57 (defun forward-thing (thing &optional n
)
58 "Move forward to the end of the Nth next THING.
59 THING should be a symbol specifying a type of syntactic entity.
60 Possibilities include `symbol', `list', `sexp', `defun',
61 `filename', `url', `email', `word', `sentence', `whitespace',
63 (let ((forward-op (or (get thing
'forward-op
)
64 (intern-soft (format "forward-%s" thing
)))))
65 (if (functionp forward-op
)
66 (funcall forward-op
(or n
1))
67 (error "Can't determine how to move over a %s" thing
))))
72 (defun bounds-of-thing-at-point (thing)
73 "Determine the start and end buffer locations for the THING at point.
74 THING should be a symbol specifying a type of syntactic entity.
75 Possibilities include `symbol', `list', `sexp', `defun',
76 `filename', `url', `email', `word', `sentence', `whitespace',
79 See the file `thingatpt.el' for documentation on how to define a
82 Return a cons cell (START . END) giving the start and end
83 positions of the thing found."
84 (if (get thing
'bounds-of-thing-at-point
)
85 (funcall (get thing
'bounds-of-thing-at-point
))
89 ;; Try moving forward, then back.
90 (funcall ;; First move to end.
91 (or (get thing
'end-op
)
92 (lambda () (forward-thing thing
1))))
93 (funcall ;; Then move to beg.
94 (or (get thing
'beginning-op
)
95 (lambda () (forward-thing thing -
1))))
98 ;; If that brings us all the way back to ORIG,
99 ;; it worked. But END may not be the real end.
100 ;; So find the real end that corresponds to BEG.
101 ;; FIXME: in which cases can `real-end' differ from `end'?
105 (or (get thing
'end-op
)
106 (lambda () (forward-thing thing
1))))
108 (when (and (<= orig real-end
) (< beg real-end
))
109 (cons beg real-end
)))
111 ;; Try a second time, moving backward first and then forward,
112 ;; so that we can find a thing that ends at ORIG.
113 (funcall ;; First, move to beg.
114 (or (get thing
'beginning-op
)
115 (lambda () (forward-thing thing -
1))))
116 (funcall ;; Then move to end.
117 (or (get thing
'end-op
)
118 (lambda () (forward-thing thing
1))))
123 (or (get thing
'beginning-op
)
124 (lambda () (forward-thing thing -
1))))
126 (if (and (<= real-beg orig
) (<= orig end
) (< real-beg end
))
127 (cons real-beg end
))))))))))
130 (defun thing-at-point (thing &optional no-properties
)
131 "Return the THING at point.
132 THING should be a symbol specifying a type of syntactic entity.
133 Possibilities include `symbol', `list', `sexp', `defun',
134 `filename', `url', `email', `word', `sentence', `whitespace',
135 `line', `number', and `page'.
137 When the optional argument NO-PROPERTIES is non-nil,
138 strip text properties from the return value.
140 See the file `thingatpt.el' for documentation on how to define
141 a symbol as a valid THING."
143 (if (get thing
'thing-at-point
)
144 (funcall (get thing
'thing-at-point
))
145 (let ((bounds (bounds-of-thing-at-point thing
)))
147 (buffer-substring (car bounds
) (cdr bounds
)))))))
148 (when (and text no-properties
(sequencep text
))
149 (set-text-properties 0 (length text
) nil text
))
152 ;; Go to beginning/end
154 (defun beginning-of-thing (thing)
155 "Move point to the beginning of THING.
156 The bounds of THING are determined by `bounds-of-thing-at-point'."
157 (let ((bounds (bounds-of-thing-at-point thing
)))
158 (or bounds
(error "No %s here" thing
))
159 (goto-char (car bounds
))))
161 (defun end-of-thing (thing)
162 "Move point to the end of THING.
163 The bounds of THING are determined by `bounds-of-thing-at-point'."
164 (let ((bounds (bounds-of-thing-at-point thing
)))
165 (or bounds
(error "No %s here" thing
))
166 (goto-char (cdr bounds
))))
172 ;; bolp will be false when you click on the last line in the buffer
173 ;; and it has no final newline.
175 (put 'line
'beginning-op
176 (lambda () (if (bolp) (forward-line -
1) (beginning-of-line))))
180 (defun in-string-p ()
181 "Return non-nil if point is in a string."
182 (declare (obsolete "use (nth 3 (syntax-ppss)) instead." "25.1"))
183 (let ((orig (point)))
186 (nth 3 (parse-partial-sexp (point) orig
)))))
188 (defun thing-at-point--end-of-sexp ()
189 "Move point to the end of the current sexp."
190 (let ((char-syntax (syntax-after (point))))
191 (if (or (eq char-syntax ?\
))
192 (and (eq char-syntax ?
\") (nth 3 (syntax-ppss))))
196 (define-obsolete-function-alias 'end-of-sexp
197 'thing-at-point--end-of-sexp
"25.1"
198 "This is an internal thingatpt function and should not be used.")
200 (put 'sexp
'end-op
'thing-at-point--end-of-sexp
)
202 (defun thing-at-point--beginning-of-sexp ()
203 "Move point to the beginning of the current sexp."
204 (let ((char-syntax (char-syntax (char-before))))
205 (if (or (eq char-syntax ?\
()
206 (and (eq char-syntax ?
\") (nth 3 (syntax-ppss))))
210 (define-obsolete-function-alias 'beginning-of-sexp
211 'thing-at-point--beginning-of-sexp
"25.1"
212 "This is an internal thingatpt function and should not be used.")
214 (put 'sexp
'beginning-op
'thing-at-point--beginning-of-sexp
)
218 (put 'list
'bounds-of-thing-at-point
'thing-at-point-bounds-of-list-at-point
)
220 (defun thing-at-point-bounds-of-list-at-point ()
221 "Return the bounds of the list at point.
222 [Internal function used by `bounds-of-thing-at-point'.]"
224 (let ((opoint (point))
230 (progn (forward-sexp)
232 ;; Are we are at the beginning of a top-level sexp?
236 (if (>= opoint
(point))
237 (cons opoint end
))))))))
241 (put 'defun
'beginning-op
'beginning-of-defun
)
242 (put 'defun
'end-op
'end-of-defun
)
243 (put 'defun
'forward-op
'end-of-defun
)
247 (defvar thing-at-point-file-name-chars
"-~/[:alnum:]_.${}#%,:"
248 "Characters allowable in filenames.")
250 (put 'filename
'end-op
252 (re-search-forward (concat "\\=[" thing-at-point-file-name-chars
"]*")
254 (put 'filename
'beginning-op
256 (if (re-search-backward (concat "[^" thing-at-point-file-name-chars
"]")
259 (goto-char (point-min)))))
263 (defvar thing-at-point-beginning-of-url-regexp nil
264 "Regexp matching the beginning of a well-formed URI.
265 If nil, construct the regexp from `thing-at-point-uri-schemes'.")
267 (defvar thing-at-point-url-path-regexp
268 "[^]\t\n \"'<>[^`{}]*[^]\t\n \"'<>[^`{}.,;]+"
269 "Regexp matching the host and filename or e-mail part of a URL.")
271 (defvar thing-at-point-short-url-regexp
272 (concat "[-A-Za-z0-9]+\\.[-A-Za-z0-9.]+" thing-at-point-url-path-regexp
)
273 "Regexp matching a URI without a scheme component.")
275 (defvar thing-at-point-uri-schemes
276 ;; Officials from http://www.iana.org/assignments/uri-schemes.html
277 '("aaa://" "about:" "acap://" "apt:" "bzr://" "bzr+ssh://"
278 "attachment:/" "chrome://" "cid:" "content://" "crid://" "cvs://"
279 "data:" "dav:" "dict://" "doi:" "dns:" "dtn:" "feed:" "file:/"
280 "finger://" "fish://" "ftp://" "geo:" "git://" "go:" "gopher://"
281 "h323:" "http://" "https://" "im:" "imap://" "info:" "ipp:"
282 "irc://" "irc6://" "ircs://" "iris.beep:" "jar:" "ldap://"
283 "ldaps://" "magnet:" "mailto:" "mid:" "mtqp://" "mupdate://"
284 "news:" "nfs://" "nntp://" "opaquelocktoken:" "pop://" "pres:"
285 "resource://" "rmi://" "rsync://" "rtsp://" "rtspu://" "service:"
286 "sftp://" "sip:" "sips:" "smb://" "sms:" "snmp://" "soap.beep://"
287 "soap.beeps://" "ssh://" "svn://" "svn+ssh://" "tag:" "tel:"
288 "telnet://" "tftp://" "tip://" "tn3270://" "udp://" "urn:"
289 "uuid:" "vemmi://" "webcal://" "xri://" "xmlrpc.beep://"
290 "xmlrpc.beeps://" "z39.50r://" "z39.50s://" "xmpp:"
292 "fax:" "man:" "mms://" "mmsh://" "modem:" "prospero:" "snews:"
294 "List of URI schemes recognized by `thing-at-point-url-at-point'.
295 Each string in this list should correspond to the start of a
296 URI's scheme component, up to and including the trailing // if
297 the scheme calls for that to be present.")
299 (defvar thing-at-point-markedup-url-regexp
"<URL:\\([^<>\n]+\\)>"
300 "Regexp matching a URL marked up per RFC1738.
301 This kind of markup was formerly recommended as a way to indicate
302 URIs, but as of RFC 3986 it is no longer recommended.
303 Subexpression 1 should contain the delimited URL.")
305 (defvar thing-at-point-newsgroup-regexp
306 "\\`[[:lower:]]+\\.[-+[:lower:]_0-9.]+\\'"
307 "Regexp matching a newsgroup name.")
309 (defvar thing-at-point-newsgroup-heads
310 '("alt" "comp" "gnu" "misc" "news" "sci" "soc" "talk")
311 "Used by `thing-at-point-newsgroup-p' if gnus is not running.")
313 (defvar thing-at-point-default-mail-uri-scheme
"mailto"
314 "Default scheme for ill-formed URIs that look like <foo@example.com>.
315 If nil, do not give such URIs a scheme.")
317 (put 'url
'bounds-of-thing-at-point
'thing-at-point-bounds-of-url-at-point
)
319 (defun thing-at-point-bounds-of-url-at-point (&optional lax
)
320 "Return a cons cell containing the start and end of the URI at point.
321 Try to find a URI using `thing-at-point-markedup-url-regexp'.
322 If that fails, try with `thing-at-point-beginning-of-url-regexp'.
323 If that also fails, and optional argument LAX is non-nil, return
324 the bounds of a possible ill-formed URI (one lacking a scheme)."
325 ;; Look for the old <URL:foo> markup. If found, use it.
326 (or (thing-at-point--bounds-of-markedup-url)
327 ;; Otherwise, find the bounds within which a URI may exist. The
328 ;; method is similar to `ffap-string-at-point'. Note that URIs
329 ;; may contain parentheses but may not contain spaces (RFC3986).
330 (let* ((allowed-chars "--:=&?$+@-Z_[:alpha:]~#,%;*()!'")
331 (skip-before "^[0-9a-zA-Z]")
332 (skip-after ":;.,!?")
335 (skip-chars-backward allowed-chars
)
336 (skip-chars-forward skip-before pt
)
339 (skip-chars-forward allowed-chars
)
340 (skip-chars-backward skip-after pt
)
342 (or (thing-at-point--bounds-of-well-formed-url beg end pt
)
343 (if lax
(cons beg end
))))))
345 (defun thing-at-point--bounds-of-markedup-url ()
346 (when thing-at-point-markedup-url-regexp
347 (let ((case-fold-search t
)
349 (beg (line-beginning-position))
350 (end (line-end-position))
354 (while (and (not found
)
357 (and (re-search-forward thing-at-point-markedup-url-regexp
362 (cons (match-beginning 1) (match-end 1))))))
364 (defun thing-at-point--bounds-of-well-formed-url (beg end pt
)
367 (let (url-beg paren-end regexp
)
369 (narrow-to-region beg end
)
370 ;; The scheme component must either match at BEG, or have no
371 ;; other alphanumerical ASCII characters before it.
372 (setq regexp
(concat "\\(?:\\`\\|[^a-zA-Z0-9]\\)\\("
373 (or thing-at-point-beginning-of-url-regexp
374 (regexp-opt thing-at-point-uri-schemes
))
376 (and (re-search-forward regexp end t
)
377 ;; URI must have non-empty contents.
379 (setq url-beg
(match-beginning 1))))
381 ;; If there is an open paren before the URI, truncate to the
382 ;; matching close paren.
383 (and (> url-beg
(point-min))
384 (eq (car-safe (syntax-after (1- url-beg
))) 4)
386 (narrow-to-region (1- url-beg
) (min end
(point-max)))
387 (setq paren-end
(ignore-errors
388 (scan-lists (1- url-beg
) 1 0))))
389 (not (blink-matching-check-mismatch (1- url-beg
) paren-end
))
390 (setq end
(1- paren-end
)))
391 ;; Ensure PT is actually within BOUNDARY. Check the following
392 ;; example with point on the beginning of the line:
394 ;; 3,1406710489,http://gnu.org,0,"0"
395 (and (<= url-beg pt end
) (cons url-beg end
))))))
397 (put 'url
'thing-at-point
'thing-at-point-url-at-point
)
399 (defun thing-at-point-url-at-point (&optional lax bounds
)
400 "Return the URL around or before point.
401 If no URL is found, return nil.
403 If optional argument LAX is non-nil, look for URLs that are not
404 well-formed, such as foo@bar or <nobody>.
406 If optional arguments BOUNDS are non-nil, it should be a cons
407 cell of the form (START . END), containing the beginning and end
408 positions of the URI. Otherwise, these positions are detected
409 automatically from the text around point.
411 If the scheme component is absent, either because a URI delimited
412 with <url:...> lacks one, or because an ill-formed URI was found
413 with LAX or BEG and END, try to add a scheme in the returned URI.
414 The scheme is chosen heuristically: \"mailto:\" if the address
415 looks like an email address, \"ftp://\" if it starts with
418 (setq bounds
(thing-at-point-bounds-of-url-at-point lax
)))
419 (when (and bounds
(< (car bounds
) (cdr bounds
)))
420 (let ((str (buffer-substring-no-properties (car bounds
) (cdr bounds
))))
421 ;; If there is no scheme component, try to add one.
422 (unless (string-match "\\`[a-zA-Z][-a-zA-Z0-9+.]*:" str
)
424 ;; If the URI has the form <foo@bar>, treat it according to
425 ;; `thing-at-point-default-mail-uri-scheme'. If there are
426 ;; no angle brackets, it must be mailto.
427 (when (string-match "\\`[^:</>@]+@[-.0-9=&?$+A-Z_a-z~#,%;*]" str
)
428 (let ((scheme (if (and (eq (char-before (car bounds
)) ?
<)
429 (eq (char-after (cdr bounds
)) ?
>))
430 thing-at-point-default-mail-uri-scheme
433 (setq str
(concat scheme
":" str
)))))
434 ;; If the string is like <FOO>, where FOO is an existing user
435 ;; name on the system, treat that as an email address.
436 (and (string-match "\\`[[:alnum:]]+\\'" str
)
437 (eq (char-before (car bounds
)) ?
<)
438 (eq (char-after (cdr bounds
)) ?
>)
439 (not (string-match "~" (expand-file-name (concat "~" str
))))
440 (setq str
(concat "mailto:" str
)))
441 ;; If it looks like news.example.com, treat it as news.
442 (if (thing-at-point-newsgroup-p str
)
443 (setq str
(concat "news:" str
)))
444 ;; If it looks like ftp.example.com. treat it as ftp.
445 (if (string-match "\\`ftp\\." str
)
446 (setq str
(concat "ftp://" str
)))
447 ;; If it looks like www.example.com. treat it as http.
448 (if (string-match "\\`www\\." str
)
449 (setq str
(concat "http://" str
)))
450 ;; Otherwise, it just isn't a URI.
454 (defun thing-at-point-newsgroup-p (string)
455 "Return STRING if it looks like a newsgroup name, else nil."
457 (string-match thing-at-point-newsgroup-regexp string
)
458 (let ((htbs '(gnus-active-hashtb gnus-newsrc-hashtb gnus-killed-hashtb
))
459 (heads thing-at-point-newsgroup-heads
)
462 (setq htb
(car htbs
) htbs
(cdr htbs
))
464 ;; errs: htb symbol may be unbound, or not a hash-table.
465 ;; gnus-gethash is just a macro for intern-soft.
466 (and (symbol-value htb
)
467 (intern-soft string
(symbol-value htb
))
468 (setq ret string htbs nil
))
469 ;; If we made it this far, gnus is running, so ignore "heads":
472 (let ((head (string-match "\\`\\([[:lower:]]+\\)\\." string
)))
473 (and head
(setq head
(substring string
0 (match-end 1)))
478 (put 'url
'end-op
(lambda () (end-of-thing 'url
)))
480 (put 'url
'beginning-op
(lambda () (end-of-thing 'url
)))
482 ;; The normal thingatpt mechanism doesn't work for complex regexps.
483 ;; This should work for almost any regexp wherever we are in the
484 ;; match. To do a perfect job for any arbitrary regexp would mean
485 ;; testing every position before point. Regexp searches won't find
486 ;; matches that straddle the start position so we search forwards once
487 ;; and then back repeatedly and then back up a char at a time.
489 (defun thing-at-point-looking-at (regexp &optional distance
)
490 "Return non-nil if point is in or just after a match for REGEXP.
491 Set the match data from the earliest such match ending at or after
494 Optional argument DISTANCE limits search for REGEXP forward and
497 (let ((old-point (point))
498 (forward-bound (and distance
(+ (point) distance
)))
499 (backward-bound (and distance
(- (point) distance
)))
500 match prev-pos new-pos
)
501 (and (looking-at regexp
)
502 (>= (match-end 0) old-point
)
503 (setq match
(point)))
504 ;; Search back repeatedly from end of next match.
505 ;; This may fail if next match ends before this match does.
506 (re-search-forward regexp forward-bound
'limit
)
507 (setq prev-pos
(point))
508 (while (and (setq new-pos
(re-search-backward regexp backward-bound t
))
509 ;; Avoid inflooping with some regexps, such as "^",
510 ;; matching which never moves point.
512 (or (> (match-beginning 0) old-point
)
513 (and (looking-at regexp
) ; Extend match-end past search start
514 (>= (match-end 0) old-point
)
515 (setq match
(point))))))
518 ;; Back up a char at a time in case search skipped
519 ;; intermediate match straddling search start pos.
520 (while (and (not (bobp))
521 (progn (backward-char 1) (looking-at regexp
))
522 (>= (match-end 0) old-point
)
523 (setq match
(point))))
525 (looking-at regexp
)))))
528 (defvar thing-at-point-email-regexp
529 "<?[-+_.~a-zA-Z][-+_.~:a-zA-Z0-9]*@[-.a-zA-Z0-9]+>?"
530 "A regular expression probably matching an email address.
531 This does not match the real name portion, only the address, optionally
532 with angle brackets.")
534 ;; Haven't set 'forward-op on 'email nor defined 'forward-email' because
535 ;; not sure they're actually needed, and URL seems to skip them too.
536 ;; Note that (end-of-thing 'email) and (beginning-of-thing 'email)
537 ;; work automagically, though.
539 (put 'email
'bounds-of-thing-at-point
541 (let ((thing (thing-at-point-looking-at
542 thing-at-point-email-regexp
500)))
544 (let ((beginning (match-beginning 0))
546 (cons beginning end
))))))
548 (put 'email
'thing-at-point
550 (let ((boundary-pair (bounds-of-thing-at-point 'email
)))
552 (buffer-substring-no-properties
553 (car boundary-pair
) (cdr boundary-pair
))))))
557 (put 'buffer
'end-op
(lambda () (goto-char (point-max))))
558 (put 'buffer
'beginning-op
(lambda () (goto-char (point-min))))
562 (defun word-at-point ()
563 "Return the word at point. See `thing-at-point'."
564 (thing-at-point 'word
))
566 (defun sentence-at-point ()
567 "Return the sentence at point. See `thing-at-point'."
568 (thing-at-point 'sentence
))
570 (defun thing-at-point--read-from-whole-string (str)
571 "Read a Lisp expression from STR.
572 Signal an error if the entire string was not used."
573 (let* ((read-data (read-from-string str
))
576 ;; The call to `ignore' suppresses a compiler warning.
577 (progn (ignore (read-from-string (substring str
(cdr read-data
))))
581 (error "Can't read whole string")
584 (define-obsolete-function-alias 'read-from-whole-string
585 'thing-at-point--read-from-whole-string
"25.1"
586 "This is an internal thingatpt function and should not be used.")
588 (defun form-at-point (&optional thing pred
)
589 (let ((sexp (ignore-errors
590 (thing-at-point--read-from-whole-string
591 (thing-at-point (or thing
'sexp
))))))
592 (if (or (not pred
) (funcall pred sexp
)) sexp
)))
595 (defun sexp-at-point ()
596 "Return the sexp at point, or nil if none is found."
597 (form-at-point 'sexp
))
599 (defun symbol-at-point ()
600 "Return the symbol at point, or nil if none is found."
601 (let ((thing (thing-at-point 'symbol
)))
602 (if thing
(intern thing
))))
604 (defun number-at-point ()
605 "Return the number at point, or nil if none is found."
606 (when (thing-at-point-looking-at "-?[0-9]+\\.?[0-9]*" 500)
608 (buffer-substring (match-beginning 0) (match-end 0)))))
610 (put 'number
'thing-at-point
'number-at-point
)
612 (defun list-at-point ()
613 "Return the Lisp list at point, or nil if none is found."
614 (form-at-point 'list
'listp
))
616 ;;; thingatpt.el ends here