* thingatpt.el (sexp-at-point, symbol-at-point, number-at-point)
[bpt/emacs.git] / lisp / thingatpt.el
CommitLineData
55535639 1;;; thingatpt.el --- get the `thing' at point
1a2b6c52 2
c90f2757 3;; Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 2000,
eb3fa2cf
GM
4;; 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
5;; Free Software Foundation, Inc.
1a2b6c52
RS
6
7;; Author: Mike Williams <mikew@gopher.dosli.govt.nz>
6254fc9f 8;; Maintainer: FSF
b7f66977 9;; Keywords: extensions, matching, mouse
1a2b6c52 10;; Created: Thu Mar 28 13:48:23 1991
1a2b6c52
RS
11
12;; This file is part of GNU Emacs.
13
eb3fa2cf 14;; GNU Emacs is free software: you can redistribute it and/or modify
1a2b6c52 15;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
16;; the Free Software Foundation, either version 3 of the License, or
17;; (at your option) any later version.
1a2b6c52
RS
18
19;; GNU Emacs is distributed in the hope that it will be useful,
20;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22;; GNU General Public License for more details.
23
eb3fa2cf
GM
24;; You should have received a copy of the GNU General Public License
25;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
69f9ba7e 27;;; Commentary:
b578f267 28
c851323f
RS
29;; This file provides routines for getting the "thing" at the location of
30;; point, whatever that "thing" happens to be. The "thing" is defined by
7a8f27db 31;; its beginning and end positions in the buffer.
1a2b6c52
RS
32;;
33;; The function bounds-of-thing-at-point finds the beginning and end
c851323f 34;; positions by moving first forward to the end of the "thing", and then
1a2b6c52 35;; backwards to the beginning. By default, it uses the corresponding
c851323f 36;; forward-"thing" operator (eg. forward-word, forward-line).
1a2b6c52
RS
37;;
38;; Special cases are allowed for using properties associated with the named
f1180544 39;; "thing":
1a2b6c52 40;;
c851323f 41;; forward-op Function to call to skip forward over a "thing" (or
1a2b6c52 42;; with a negative argument, backward).
f1180544 43;;
c851323f
RS
44;; beginning-op Function to call to skip to the beginning of a "thing".
45;; end-op Function to call to skip to the end of a "thing".
1a2b6c52
RS
46;;
47;; Reliance on existing operators means that many `things' can be accessed
48;; without further code: eg.
49;; (thing-at-point 'line)
50;; (thing-at-point 'page)
51
b578f267 52;;; Code:
1a2b6c52
RS
53
54(provide 'thingatpt)
55
b578f267 56;; Basic movement
1a2b6c52
RS
57
58;;;###autoload
c851323f 59(defun forward-thing (thing &optional n)
2a59b30d 60 "Move forward to the end of the Nth next THING."
c851323f
RS
61 (let ((forward-op (or (get thing 'forward-op)
62 (intern-soft (format "forward-%s" thing)))))
6254fc9f 63 (if (functionp forward-op)
c851323f
RS
64 (funcall forward-op (or n 1))
65 (error "Can't determine how to move over a %s" thing))))
1a2b6c52 66
b578f267 67;; General routines
1a2b6c52
RS
68
69;;;###autoload
c851323f
RS
70(defun bounds-of-thing-at-point (thing)
71 "Determine the start and end buffer locations for the THING at point.
72THING is a symbol which specifies the kind of syntactic entity you want.
73Possibilities include `symbol', `list', `sexp', `defun', `filename', `url',
baef4cbe 74`email', `word', `sentence', `whitespace', `line', `page' and others.
c851323f
RS
75
76See the file `thingatpt.el' for documentation on how to define
77a symbol as a valid THING.
78
79The value is a cons cell (START . END) giving the start and end positions
80of the textual entity that was found."
d9cc804b
RS
81 (if (get thing 'bounds-of-thing-at-point)
82 (funcall (get thing 'bounds-of-thing-at-point))
83 (let ((orig (point)))
84 (condition-case nil
85 (save-excursion
86 ;; Try moving forward, then back.
2a59b30d
SM
87 (funcall ;; First move to end.
88 (or (get thing 'end-op)
89 (lambda () (forward-thing thing 1))))
90 (funcall ;; Then move to beg.
91 (or (get thing 'beginning-op)
92 (lambda () (forward-thing thing -1))))
93 (let ((beg (point)))
d9cc804b
RS
94 (if (not (and beg (> beg orig)))
95 ;; If that brings us all the way back to ORIG,
96 ;; it worked. But END may not be the real end.
97 ;; So find the real end that corresponds to BEG.
98 (let ((real-end
f1180544
JB
99 (progn
100 (funcall
101 (or (get thing 'end-op)
2a59b30d 102 (lambda () (forward-thing thing 1))))
d9cc804b
RS
103 (point))))
104 (if (and beg real-end (<= beg orig) (<= orig real-end))
105 (cons beg real-end)))
106 (goto-char orig)
107 ;; Try a second time, moving backward first and then forward,
108 ;; so that we can find a thing that ends at ORIG.
2a59b30d
SM
109 (funcall ;; First, move to beg.
110 (or (get thing 'beginning-op)
111 (lambda () (forward-thing thing -1))))
112 (funcall ;; Then move to end.
113 (or (get thing 'end-op)
114 (lambda () (forward-thing thing 1))))
115 (let ((end (point))
116 (real-beg
f1180544
JB
117 (progn
118 (funcall
119 (or (get thing 'beginning-op)
2a59b30d 120 (lambda () (forward-thing thing -1))))
d9cc804b
RS
121 (point))))
122 (if (and real-beg end (<= real-beg orig) (<= orig end))
123 (cons real-beg end))))))
124 (error nil)))))
1a2b6c52
RS
125
126;;;###autoload
c851323f
RS
127(defun thing-at-point (thing)
128 "Return the THING at point.
129THING is a symbol which specifies the kind of syntactic entity you want.
130Possibilities include `symbol', `list', `sexp', `defun', `filename', `url',
baef4cbe 131`email', `word', `sentence', `whitespace', `line', `page' and others.
c851323f
RS
132
133See the file `thingatpt.el' for documentation on how to define
134a symbol as a valid THING."
d9cc804b
RS
135 (if (get thing 'thing-at-point)
136 (funcall (get thing 'thing-at-point))
137 (let ((bounds (bounds-of-thing-at-point thing)))
f1180544 138 (if bounds
d9cc804b 139 (buffer-substring (car bounds) (cdr bounds))))))
1a2b6c52 140
b578f267 141;; Go to beginning/end
1a2b6c52 142
c851323f
RS
143(defun beginning-of-thing (thing)
144 (let ((bounds (bounds-of-thing-at-point thing)))
145 (or bounds (error "No %s here" thing))
1a2b6c52
RS
146 (goto-char (car bounds))))
147
c851323f
RS
148(defun end-of-thing (thing)
149 (let ((bounds (bounds-of-thing-at-point thing)))
150 (or bounds (error "No %s here" thing))
1a2b6c52
RS
151 (goto-char (cdr bounds))))
152
f1180544 153;; Special cases
1a2b6c52 154
f1180544 155;; Lines
9f5c7ace
RS
156
157;; bolp will be false when you click on the last line in the buffer
158;; and it has no final newline.
159
160(put 'line 'beginning-op
2a59b30d 161 (lambda () (if (bolp) (forward-line -1) (beginning-of-line))))
9f5c7ace 162
f1180544 163;; Sexps
1a2b6c52
RS
164
165(defun in-string-p ()
166 (let ((orig (point)))
167 (save-excursion
168 (beginning-of-defun)
169 (nth 3 (parse-partial-sexp (point) orig)))))
170
171(defun end-of-sexp ()
172 (let ((char-syntax (char-syntax (char-after (point)))))
173 (if (or (eq char-syntax ?\))
174 (and (eq char-syntax ?\") (in-string-p)))
175 (forward-char 1)
176 (forward-sexp 1))))
177
178(put 'sexp 'end-op 'end-of-sexp)
179
6f0e09d4
RS
180(defun beginning-of-sexp ()
181 (let ((char-syntax (char-syntax (char-before (point)))))
182 (if (or (eq char-syntax ?\()
183 (and (eq char-syntax ?\") (in-string-p)))
184 (forward-char -1)
185 (forward-sexp -1))))
186
187(put 'sexp 'beginning-op 'beginning-of-sexp)
188
f1180544 189;; Lists
1a2b6c52 190
2a59b30d 191(put 'list 'end-op (lambda () (up-list 1)))
1a2b6c52
RS
192(put 'list 'beginning-op 'backward-sexp)
193
4d61e7d5 194;; Filenames and URLs www.com/foo%32bar
1a2b6c52 195
839aacc9 196(defvar thing-at-point-file-name-chars "-~/[:alnum:]_.${}#%,:"
1a2b6c52
RS
197 "Characters allowable in filenames.")
198
f1180544 199(put 'filename 'end-op
839aacc9
DL
200 (lambda ()
201 (re-search-forward (concat "\\=[" thing-at-point-file-name-chars "]*")
202 nil t)))
1a2b6c52 203(put 'filename 'beginning-op
839aacc9
DL
204 (lambda ()
205 (if (re-search-backward (concat "[^" thing-at-point-file-name-chars "]")
206 nil t)
207 (forward-char)
208 (goto-char (point-min)))))
c851323f 209
d9cc804b 210(defvar thing-at-point-url-path-regexp
42986283 211 "[^]\t\n \"'<>[^`{}]*[^]\t\n \"'<>[^`{}.,;]+"
0408f074 212 "A regular expression probably matching the host and filename or e-mail part of a URL.")
d9cc804b
RS
213
214(defvar thing-at-point-short-url-regexp
215 (concat "[-A-Za-z0-9.]+" thing-at-point-url-path-regexp)
216 "A regular expression probably matching a URL without an access scheme.
217Hostname matching is stricter in this case than for
218``thing-at-point-url-regexp''.")
219
1c1766c7 220(defvar thing-at-point-uri-schemes
4f5d4668 221 ;; Officials from http://www.iana.org/assignments/uri-schemes.html
1c1766c7
MR
222 '("ftp://" "http://" "gopher://" "mailto:" "news:" "nntp:"
223 "telnet://" "wais://" "file:/" "prospero:" "z39.50s:" "z39.50r:"
224 "cid:" "mid:" "vemmi:" "service:" "imap:" "nfs:" "acap:" "rtsp:"
225 "tip:" "pop:" "data:" "dav:" "opaquelocktoken:" "sip:" "tel:" "fax:"
226 "modem:" "ldap:" "https://" "soap.beep:" "soap.beeps:" "urn:" "go:"
227 "afs:" "tn3270:" "mailserver:"
4f5d4668
RS
228 "crid:" "dict:" "dns:" "dtn:" "h323:" "im:" "info:" "ipp:"
229 "iris.beep:" "mtqp:" "mupdate:" "pres:" "sips:" "snmp:" "tag:"
230 "tftp:" "xmlrpc.beep:" "xmlrpc.beeps:" "xmpp:"
1c1766c7 231 ;; Compatibility
4f5d4668 232 "snews:" "irc:" "mms://" "mmsh://")
2a59b30d 233 "Uniform Resource Identifier (URI) Schemes.")
1c1766c7 234
d9cc804b 235(defvar thing-at-point-url-regexp
1c1766c7
MR
236 (concat "\\<\\(" (mapconcat 'identity thing-at-point-uri-schemes "\\|") "\\)"
237 thing-at-point-url-path-regexp)
d9cc804b
RS
238 "A regular expression probably matching a complete URL.")
239
240(defvar thing-at-point-markedup-url-regexp
241 "<URL:[^>]+>"
242 "A regular expression matching a URL marked up per RFC1738.
243This may contain whitespace (including newlines) .")
244
245(put 'url 'bounds-of-thing-at-point 'thing-at-point-bounds-of-url-at-point)
246(defun thing-at-point-bounds-of-url-at-point ()
2a59b30d
SM
247 (let ((strip (thing-at-point-looking-at
248 thing-at-point-markedup-url-regexp))) ;; (url "") short
249 (if (or strip
883d1f4b 250 (thing-at-point-looking-at thing-at-point-url-regexp)
d9cc804b 251 ;; Access scheme omitted?
2a59b30d
SM
252 ;; (setq short (thing-at-point-looking-at
253 ;; thing-at-point-short-url-regexp))
254 )
d9cc804b
RS
255 (let ((beginning (match-beginning 0))
256 (end (match-end 0)))
2a59b30d
SM
257 (when strip
258 (setq beginning (+ beginning 5))
259 (setq end (- end 1)))
d9cc804b
RS
260 (cons beginning end)))))
261
262(put 'url 'thing-at-point 'thing-at-point-url-at-point)
263(defun thing-at-point-url-at-point ()
264 "Return the URL around or before point.
340483df
DL
265
266Search backwards for the start of a URL ending at or after point. If
267no URL found, return nil. The access scheme will be prepended if
268absent: \"mailto:\" if the string contains \"@\", \"ftp://\" if it
269starts with \"ftp\" and not \"ftp:/\", or \"http://\" by default."
270
d9cc804b
RS
271 (let ((url "") short strip)
272 (if (or (setq strip (thing-at-point-looking-at
273 thing-at-point-markedup-url-regexp))
274 (thing-at-point-looking-at thing-at-point-url-regexp)
275 ;; Access scheme omitted?
276 (setq short (thing-at-point-looking-at
277 thing-at-point-short-url-regexp)))
278 (progn
279 (setq url (buffer-substring-no-properties (match-beginning 0)
280 (match-end 0)))
281 (and strip (setq url (substring url 5 -1))) ; Drop "<URL:" & ">"
282 ;; strip whitespace
84841dd1 283 (while (string-match "[ \t\n\r]+" url)
d9cc804b 284 (setq url (replace-match "" t t url)))
4f5d4668
RS
285 (and short (setq url (concat (cond ((string-match "^[a-zA-Z]+:" url)
286 ;; already has a URL scheme.
287 "")
288 ((string-match "@" url)
340483df
DL
289 "mailto:")
290 ;; e.g. ftp.swiss... or ftp-swiss...
291 ((string-match "^ftp" url)
292 "ftp://")
293 (t "http://"))
294 url)))
d9cc804b
RS
295 (if (string-equal "" url)
296 nil
297 url)))))
298
299;; The normal thingatpt mechanism doesn't work for complex regexps.
300;; This should work for almost any regexp wherever we are in the
301;; match. To do a perfect job for any arbitrary regexp would mean
302;; testing every position before point. Regexp searches won't find
303;; matches that straddle the start position so we search forwards once
304;; and then back repeatedly and then back up a char at a time.
305
306(defun thing-at-point-looking-at (regexp)
307 "Return non-nil if point is in or just after a match for REGEXP.
308Set the match data from the earliest such match ending at or after
309point."
310 (save-excursion
311 (let ((old-point (point)) match)
312 (and (looking-at regexp)
313 (>= (match-end 0) old-point)
314 (setq match (point)))
315 ;; Search back repeatedly from end of next match.
316 ;; This may fail if next match ends before this match does.
317 (re-search-forward regexp nil 'limit)
318 (while (and (re-search-backward regexp nil t)
319 (or (> (match-beginning 0) old-point)
320 (and (looking-at regexp) ; Extend match-end past search start
321 (>= (match-end 0) old-point)
322 (setq match (point))))))
323 (if (not match) nil
324 (goto-char match)
325 ;; Back up a char at a time in case search skipped
326 ;; intermediate match straddling search start pos.
327 (while (and (not (bobp))
328 (progn (backward-char 1) (looking-at regexp))
329 (>= (match-end 0) old-point)
330 (setq match (point))))
331 (goto-char match)
332 (looking-at regexp)))))
333
a1c9b4d0 334(put 'url 'end-op
2a59b30d
SM
335 (lambda ()
336 (let ((bounds (thing-at-point-bounds-of-url-at-point)))
337 (if bounds
338 (goto-char (cdr bounds))
339 (error "No URL here")))))
c851323f 340(put 'url 'beginning-op
2a59b30d
SM
341 (lambda ()
342 (let ((bounds (thing-at-point-bounds-of-url-at-point)))
343 (if bounds
344 (goto-char (car bounds))
345 (error "No URL here")))))
1a2b6c52 346
baef4cbe
KF
347;; Email addresses
348(defvar thing-at-point-email-regexp
86265518 349 "<?[-+_.~a-zA-Z][-+_.~:a-zA-Z0-9]*@[-.a-zA-Z0-9]+>?"
baef4cbe
KF
350 "A regular expression probably matching an email address.
351This does not match the real name portion, only the address, optionally
352with angle brackets.")
353
354;; Haven't set 'forward-op on 'email nor defined 'forward-email' because
355;; not sure they're actually needed, and URL seems to skip them too.
356;; Note that (end-of-thing 'email) and (beginning-of-thing 'email)
357;; work automagically, though.
358
359(put 'email 'bounds-of-thing-at-point
360 (lambda ()
361 (let ((thing (thing-at-point-looking-at thing-at-point-email-regexp)))
362 (if thing
363 (let ((beginning (match-beginning 0))
364 (end (match-end 0)))
365 (cons beginning end))))))
366
367(put 'email 'thing-at-point
368 (lambda ()
369 (let ((boundary-pair (bounds-of-thing-at-point 'email)))
370 (if boundary-pair
371 (buffer-substring-no-properties
372 (car boundary-pair) (cdr boundary-pair))))))
373
f1180544 374;; Whitespace
1a2b6c52 375
c851323f 376(defun forward-whitespace (arg)
1a2b6c52 377 (interactive "p")
f1180544 378 (if (natnump arg)
9e594a2e 379 (re-search-forward "[ \t]+\\|\n" nil 'move arg)
c851323f 380 (while (< arg 0)
9e594a2e 381 (if (re-search-backward "[ \t]+\\|\n" nil 'move)
1a2b6c52
RS
382 (or (eq (char-after (match-beginning 0)) 10)
383 (skip-chars-backward " \t")))
c851323f 384 (setq arg (1+ arg)))))
1a2b6c52 385
f1180544 386;; Buffer
1a2b6c52 387
206eef6c
SM
388(put 'buffer 'end-op (lambda () (goto-char (point-max))))
389(put 'buffer 'beginning-op (lambda () (goto-char (point-min))))
1a2b6c52 390
f1180544 391;; Symbols
1a2b6c52 392
c851323f 393(defun forward-symbol (arg)
1a2b6c52 394 (interactive "p")
f1180544 395 (if (natnump arg)
9e594a2e 396 (re-search-forward "\\(\\sw\\|\\s_\\)+" nil 'move arg)
c851323f 397 (while (< arg 0)
9e594a2e 398 (if (re-search-backward "\\(\\sw\\|\\s_\\)+" nil 'move)
1a2b6c52 399 (skip-syntax-backward "w_"))
c851323f 400 (setq arg (1+ arg)))))
1a2b6c52 401
f1180544 402;; Syntax blocks
fde7326e
RS
403
404(defun forward-same-syntax (&optional arg)
405 (interactive "p")
406 (while (< arg 0)
f1180544 407 (skip-syntax-backward
fde7326e
RS
408 (char-to-string (char-syntax (char-after (1- (point))))))
409 (setq arg (1+ arg)))
410 (while (> arg 0)
411 (skip-syntax-forward (char-to-string (char-syntax (char-after (point)))))
412 (setq arg (1- arg))))
413
f1180544 414;; Aliases
1a2b6c52
RS
415
416(defun word-at-point () (thing-at-point 'word))
417(defun sentence-at-point () (thing-at-point 'sentence))
418
c851323f 419(defun read-from-whole-string (str)
2a59b30d 420 "Read a Lisp expression from STR.
c851323f
RS
421Signal an error if the entire string was not used."
422 (let* ((read-data (read-from-string str))
f1180544 423 (more-left
1a2b6c52 424 (condition-case nil
1b0d40de 425 ;; The call to `ignore' suppresses a compiler warning.
7f1422bc 426 (progn (ignore (read-from-string (substring str (cdr read-data))))
1a2b6c52
RS
427 t)
428 (end-of-file nil))))
429 (if more-left
430 (error "Can't read whole string")
431 (car read-data))))
432
f1180544
JB
433(defun form-at-point (&optional thing pred)
434 (let ((sexp (condition-case nil
c851323f 435 (read-from-whole-string (thing-at-point (or thing 'sexp)))
1a2b6c52 436 (error nil))))
c851323f 437 (if (or (not pred) (funcall pred sexp)) sexp)))
1a2b6c52 438
be64abcf 439;;;###autoload
1a2b6c52 440(defun sexp-at-point () (form-at-point 'sexp))
be64abcf 441;;;###autoload
2a59b30d
SM
442(defun symbol-at-point ()
443 (let ((thing (thing-at-point 'symbol)))
444 (if thing (intern thing))))
be64abcf 445;;;###autoload
1a2b6c52 446(defun number-at-point () (form-at-point 'sexp 'numberp))
be64abcf 447;;;###autoload
1a2b6c52
RS
448(defun list-at-point () (form-at-point 'list 'listp))
449
2a59b30d 450;; arch-tag: bb65a163-dae2-4055-aedc-fe11f497f698
55535639 451;;; thingatpt.el ends here