1;;;; Emacs Lisp help for writing Subversion code. ;;;;
2
3;; Licensed to the Apache Software Foundation (ASF) under one
4;; or more contributor license agreements.  See the NOTICE file
5;; distributed with this work for additional information
6;; regarding copyright ownership.  The ASF licenses this file
7;; to you under the Apache License, Version 2.0 (the
8;; "License"); you may not use this file except in compliance
9;; with the License.  You may obtain a copy of the License at
10;;
11;;   http://www.apache.org/licenses/LICENSE-2.0
12;;
13;; Unless required by applicable law or agreed to in writing,
14;; software distributed under the License is distributed on an
15;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16;; KIND, either express or implied.  See the License for the
17;; specific language governing permissions and limitations
18;; under the License.
19
20
21;; Later on, there will be auto-detection of svn files, modeline
22;; status, and a whole library of routines to interface with the
23;; command-line client.  For now, there's this, at Ben's request.
24;;
25;; All this stuff should get folded into Emacs VC mode, really.
26
27(defun svn-revert ()
28  "Revert the current buffer and its file to its svn base revision."
29  (interactive)
30  (let ((obuf (current-buffer))
31        (fname (buffer-file-name))
32        (outbuf (get-buffer-create "*svn output*")))
33    (set-buffer outbuf)
34    (delete-region (point-min) (point-max))
35    (call-process "svn" nil outbuf nil "status" fname)
36    (goto-char (point-min))
37    (search-forward fname)
38    (beginning-of-line)
39    (if (looking-at "^?")
40        (error "\"%s\" is not a Subversion-controlled file" fname))
41    (call-process "svn" nil outbuf nil "revert" fname)
42    (set-buffer obuf)
43    ;; todo: make a backup~ file?
44    (save-excursion
45      (revert-buffer nil t)
46      (save-buffer))
47    (message "Reverted \"%s\"." fname)))
48
49(defun svn-resolved ()
50  "Tell Subversion that conflicts in the current buffer and its file have
51been resolved."
52  (interactive)
53  (let ((obuf (current-buffer))
54        (fname (buffer-file-name))
55        (outbuf (get-buffer-create "*svn output*")))
56    (set-buffer outbuf)
57    (delete-region (point-min) (point-max))
58    (call-process "svn" nil outbuf nil "status" fname)
59    (goto-char (point-min))
60    (search-forward fname)
61    (beginning-of-line)
62    (if (looking-at "^?")
63        (error "\"%s\" is not a Subversion-controlled file" fname))
64    (call-process "svn" nil outbuf nil "resolved" fname)
65    (set-buffer obuf)
66    ;; todo: make a backup~ file?
67    (save-excursion
68      (revert-buffer nil t)
69      (save-buffer))
70    (message "Marked \"%s\" as conflict-free." fname)))
71
72(defconst svn-adm-area ".svn"
73  "The name of the Subversion administrative subdirectory.")
74
75(defconst svn-adm-entries ".svn/entries"
76  "The path from cwd to the Subversion entries file.")
77
78(defun svn-controlled-path-p (path)
79  "Return non-nil if PATH is under Subversion version control, else
80return nil.  If PATH does not exist, return nil.
81
82In the future, this will return an Emacs Lisp reflection of PATH's
83entry, either an explicit svn-entry-struct, or a list of the form
84\(LAST-COMMIT-REV CURRENT-REV LAST-COMMITTER ...\), so we can display
85svn information in the mode line.  But that requires truly parsing the
86entries file, instead of just detecting PATH among the entries."
87  (interactive "f")  ; any use for interactive, other than testing?
88  (cond
89   ((not (file-exists-p path))
90    nil)
91   ((file-directory-p path)
92    (let ((adm-area (concat path "/" svn-adm-area)))
93      (if (file-directory-p adm-area)
94          t
95        nil)))
96   (t
97    (let ((entries  (concat (file-name-directory path) svn-adm-entries))
98          (basename (file-name-nondirectory path))
99          (found    nil))
100      (save-excursion
101	(if (file-directory-p (concat (file-name-directory path) svn-adm-area))
102	    (progn
103	      (let ((find-file-hooks nil))
104		(set-buffer (find-file-noselect entries t)))
105	      (goto-char (point-min))
106	      (if (search-forward (format "name=\"%s\"" basename) nil t)
107		  (setq found t)
108		(setq found nil))
109	      (kill-buffer nil)))
110	found)))))
111
112
113(defun svn-text-base-path (file)
114  "Return the path to the text base for FILE (a string).
115If FILE is a directory or not under version control, return nil."
116  (cond
117   ((not (svn-controlled-path-p file)) nil)
118   ((file-directory-p file)            nil)
119   (t
120    (let* ((pdir (file-name-directory file))
121           (base (file-name-nondirectory file)))
122      (format "%s%s/text-base/%s.svn-base" (or pdir "") svn-adm-area base)))))
123
124
125(defun svn-ediff (file)
126  "Ediff FILE against its text base."
127  (interactive "fsvn ediff: ")
128  (let ((tb (svn-text-base-path file)))
129    (if (not tb)
130        (error "No text base for %s" file)
131      (ediff-files file tb))))
132
133
134(defun svn-find-file-hook ()
135  "Function for find-file-hooks.
136Inhibit backup files unless `vc-make-backup-files' is non-nil."
137  (if (svn-controlled-path-p (buffer-file-name))
138      (progn
139        (if (string-match "XEMACS\\|XEmacs\\|xemacs" emacs-version)
140            (vc-load-vc-hooks)) ; for `vc-make-backup-files'
141        (unless vc-make-backup-files
142          (make-local-variable 'backup-inhibited)
143          (setq backup-inhibited t)))))
144
145(add-hook 'find-file-hooks 'svn-find-file-hook)
146
147
148
149;;; Dynamic generation of common Subversion URLs.
150;;;
151;;; (I have a version of this that actually fetches the stuff from the
152;;; Net if you don't have a local copy, but it requires a very recent
153;;; version of Emacs, so I didn't bother with it here.  -kfogel)
154
155(defvar svn-site-source-tree-top (expand-file-name "~/projects/svn/site/")
156  "*Top directory of your Subversion site source tree of
157repository \"http://svn.apache.org/repos/asf/subversion/site\".
158You almost certainly want to set this in your .emacs, to override
159the default; use `(setq svn-site-source-tree-top
160\"/path/to/the/site/tree\")'.")
161
162(defvar svn-faq-file (concat svn-site-source-tree-top "/publish/faq.html")
163  "*A local copy of the Subversion FAQ.")
164
165(defvar svn-hacking-file (concat svn-site-source-tree-top
166                                 "/docs/community-guide/community-guide.html")
167  "*A local copy of the Subversion hacking.html file.")
168
169;; Helper for referring to issue numbers in a user-friendly way.
170(defun svn-bug-url (n)
171  "Insert the url for Subversion issue number N.  Interactively, prompt for N."
172  (interactive "nSubversion issue number: ")
173  (insert (format "http://subversion.tigris.org/issues/show_bug.cgi?id=%d" n)))
174
175;; Helper for referring to revisions in a browser-friendly way.
176(defun svn-rev-url (rev &optional transform)
177  "Insert the url for Subversion revision REV, or if TRANSFORM is not
178nil, then transform the revision at or around point into an HTML link.
179
180Interactively, if at or inside a revision number, transform it into
181full HTML link; otherwise, prompt for revision number and insert just
182the resulting URL."
183  (interactive (let ((thing (thing-at-point 'word)))
184                 (if (and thing (string-match "r[0-9]+" thing))
185                     (list thing t)
186                   (list (read-string "Subversion revision number: ") nil))))
187  (if (string-match "^r[0-9]+" rev)
188      (setq rev (substring rev 1)))
189  (if transform
190      (let* ((bounds (bounds-of-thing-at-point 'word))
191             (start (car bounds))
192             (end   (cdr bounds)))
193        (delete-region start end)))
194  (insert (format "http://svn.apache.org/viewcvs?view=revision&revision=%s"
195                  rev)))
196
197(defconst svn-url-base "http://subversion.apache.org/")
198(defconst svn-faq-url (concat svn-url-base "faq.html"))
199(defconst svn-hacking-url (concat svn-url-base
200                                  "docs/community-guide/community-guide.html"))
201
202(defun svn-html-get-targets (file)
203  "Build a list of targets for the Subversion web file FILE."
204  (let* ((lst nil)
205         (already-buffer (find-buffer-visiting file))
206         (faq-buffer (or already-buffer (find-file-noselect file))))
207    (save-excursion
208      (set-buffer faq-buffer)
209      (goto-char (point-min))
210      ;; TODO: Ideally, this wouldn't depend on the presence of a
211      ;; table of contents with "#" URLs, it would read the divs and
212      ;; anchors themselves.
213      (while (search-forward "href=\"#" nil t)
214        (let ((b (point))
215              (e (progn (search-forward "\"") (forward-char -1) (point))))
216          (setq lst (cons (buffer-substring b e) lst))))
217      (if (not already-buffer)
218          (kill-buffer (current-buffer)))
219      lst)))
220
221(defun svn-url-completing-read (file prompt &optional hist-list)
222  "Completingly read an HTML target for FILE, prompting with PROMPT.
223If HIST-LIST is non-nil, it is a symbol: the completion history list to use."
224  (progn
225    (let* ((targets (svn-html-get-targets file))
226           (target-str (completing-read prompt targets nil t nil hist-list)))
227      (list target-str))))
228
229(defvar svn-faq-history-list nil
230  "History list for the 'svn-faq-url' prompt.")
231
232(defvar svn-hacking-history-list nil
233  "History list for the 'svn-hacking-url' prompt.")
234
235(defun svn-faq-url (target)
236  "Prompt with completion for a targeted SVN FAQ item, then insert it.
237If called non-interactively, TARGET is the target within the faq (an
238HTML anchor name, that is, the part after the \"#\")."
239  (interactive
240   (svn-url-completing-read svn-faq-file "FAQ entry: "
241                            'svn-faq-history-list))
242  (insert svn-faq-url "#" target))
243
244(defun svn-hacking-url (target)
245  "Prompt with completion for a targeted hacking.html item, then insert it.
246If called non-interactively, TARGET is the target within hacking.html
247(an HTML anchor name, that is, the part after the \"#\")."
248  (interactive
249   (svn-url-completing-read svn-hacking-file "hacking.html entry: "
250                            'svn-hacking-history-list))
251  (insert svn-hacking-url "#" target))
252
253
254
255;;; Subversion C conventions
256(if (eq major-mode 'c-mode)
257    (progn
258      (c-add-style "svn" '("gnu" (c-offsets-alist . ((inextern-lang . 0)))))
259      (c-set-style "svn")))
260(setq indent-tabs-mode nil)
261(setq angry-mob-with-torches-and-pitchforks t)
262
263
264
265;; Subversion Python conventions, plus some harmless helpers for
266;; people who don't have python mode set up by default.
267(autoload 'python-mode "python-mode" nil t)
268(or (assoc "\\.py$" auto-mode-alist)
269    (setq auto-mode-alist
270          (cons '("\\.py$" . python-mode) auto-mode-alist)))
271
272(defun svn-python-mode-hook ()
273  "Set up the Subversion python conventions.  The effect of this is
274local to the current buffer, which is presumably visiting a file in
275the Subversion project.  Python setup in other buffers will not be
276affected."
277  (when (string-match "/subversion/" (buffer-file-name))
278    (make-local-variable 'py-indent-offset)
279    (setq indent-tabs-mode nil)
280    (setq py-indent-offset 2)
281    (make-local-variable 'py-smart-indentation)
282    (setq py-smart-indentation nil)))
283
284(add-hook 'python-mode-hook 'svn-python-mode-hook)
285
286
287
288;; Much of the APR documentation is embedded perldoc format.  The
289;; perldoc program itself sucks, however.  If you're the author of
290;; perldoc, I'm sorry, but what were you thinking?  Don't you know
291;; that there are people in the world who don't work in vt100
292;; terminals?  If I want to view a perldoc page in my Emacs shell
293;; buffer, I have to run the ridiculous command
294;;
295;;   $ PAGER=cat perldoc -t target_file
296;;
297;; (Not that this was documented anywhere, I had to figure it out for
298;; myself by reading /usr/bin/perldoc).
299;;
300;; Non-paging behavior should be a standard command-line option.  No
301;; program that can output text should *ever* insist on invoking the
302;; pager.
303;;
304;; Anyway, these Emacs commands will solve the problem for us.
305;;
306;; Acknowledgements:
307;; Much of this code is copied from man.el in the FSF Emacs 21.x
308;; sources.
309
310(defcustom svn-perldoc-overstrike-face 'bold
311  "*Face to use when fontifying overstrike."
312  :type 'face
313  :group 'svn-dev)
314
315(defcustom svn-perldoc-underline-face 'underline
316  "*Face to use when fontifying underlining."
317  :type 'face
318  :group 'svn-dev)
319
320
321(defun svn-perldoc-softhyphen-to-minus ()
322  ;; \255 is some kind of dash in Latin-N.  Versions of Debian man, at
323  ;; least, emit it even when not in a Latin-N locale.
324  (unless (eq t (compare-strings "latin-" 0 nil
325				 current-language-environment 0 6 t))
326    (goto-char (point-min))
327    (let ((str "\255"))
328      (if enable-multibyte-characters
329	  (setq str (string-as-multibyte str)))
330      (while (search-forward str nil t) (replace-match "-")))))
331
332
333(defun svn-perldoc-fontify-buffer ()
334  "Convert overstriking and underlining to the correct fonts.
335Same for the ANSI bold and normal escape sequences."
336  (interactive)
337  (message "Please wait, making up the page...")
338  (goto-char (point-min))
339  (while (search-forward "\e[1m" nil t)
340    (delete-backward-char 4)
341    (put-text-property (point)
342		       (progn (if (search-forward "\e[0m" nil 'move)
343				  (delete-backward-char 4))
344			      (point))
345		       'face svn-perldoc-overstrike-face))
346  (goto-char (point-min))
347  (while (search-forward "_\b" nil t)
348    (backward-delete-char 2)
349    (put-text-property (point) (1+ (point)) 'face svn-perldoc-underline-face))
350  (goto-char (point-min))
351  (while (search-forward "\b_" nil t)
352    (backward-delete-char 2)
353    (put-text-property (1- (point)) (point) 'face svn-perldoc-underline-face))
354  (goto-char (point-min))
355  (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
356    (replace-match "\\1")
357    (put-text-property (1- (point)) (point) 'face svn-perldoc-overstrike-face))
358  (goto-char (point-min))
359  (while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
360    (replace-match "o")
361    (put-text-property (1- (point)) (point) 'face 'bold))
362  (goto-char (point-min))
363  (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
364    (replace-match "+")
365    (put-text-property (1- (point)) (point) 'face 'bold))
366  (svn-perldoc-softhyphen-to-minus)
367  (message "Please wait, making up the page...done"))
368
369
370(defun svn-perldoc-cleanup-buffer ()
371  "Remove overstriking and underlining from the current buffer."
372  (interactive)
373  (message "Please wait, cleaning up the page...")
374  (progn
375    (goto-char (point-min))
376    (while (search-forward "_\b" nil t) (backward-delete-char 2))
377    (goto-char (point-min))
378    (while (search-forward "\b_" nil t) (backward-delete-char 2))
379    (goto-char (point-min))
380    (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
381      (replace-match "\\1"))
382    (goto-char (point-min))
383    (while (re-search-forward "\e\\[[0-9]+m" nil t) (replace-match ""))
384    (goto-char (point-min))
385    (while (re-search-forward "o\b\\+\\|\\+\bo" nil t) (replace-match "o"))
386    (goto-char (point-min))
387    (while (re-search-forward "" nil t) (replace-match " ")))
388  (goto-char (point-min))
389  (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t) (replace-match "+"))
390  (svn-perldoc-softhyphen-to-minus)
391  (message "Please wait, cleaning up the page...done"))
392
393
394;; Entry point to svn-perldoc functionality.
395(defun svn-perldoc (file)
396  "Run perldoc on FILE, display the output in a buffer."
397  (interactive "fRun perldoc on file: ")
398  (let ((outbuf (get-buffer-create
399                 (format "*%s PerlDoc*" (file-name-nondirectory file))))
400        (savepg (getenv "PAGER")))
401    (setenv "PAGER" "cat")  ;; for perldoc
402    (save-excursion
403      (set-buffer outbuf)
404      (delete-region (point-min) (point-max))
405      (call-process "perldoc" nil outbuf nil (expand-file-name file))
406      (svn-perldoc-fontify-buffer)
407      (svn-perldoc-cleanup-buffer)
408      ;; Clean out the inevitable leading dead space.
409      (goto-char (point-min))
410      (re-search-forward "[^ \i\n]")
411      (beginning-of-line)
412      (delete-region (point-min) (point)))
413    (setenv "PAGER" savepg)
414    (display-buffer outbuf)))
415
416
417
418;;; Help developers write log messages.
419
420;; How to use this: just run `svn-log-message'.  You might want to
421;; bind it to a key, for example,
422;;
423;;   (define-key "\C-cl" 'svn-log-message)
424;;
425;; The log message will accumulate in a file.  Later, you can use
426;; that file when you commit:
427;;
428;;   $ svn ci -F msg ...
429
430(defun svn-log-path-derive (path)
431  "Derive a relative directory path for absolute PATH, for a log entry."
432  (save-match-data
433    (let ((base (file-name-nondirectory path))
434          (chop-spot (string-match
435                      "\\(code/\\)\\|\\(src/\\)\\|\\(projects/\\)"
436                      path)))
437      (if chop-spot
438          (progn
439            (setq path (substring path (match-end 0)))
440            ;; Kluge for Subversion developers.
441            (if (string-match "subversion/" path)
442                (substring path (+ (match-beginning 0) 11))
443              path))
444        (string-match (expand-file-name "~/") path)
445        (substring path (match-end 0))))))
446
447
448(defun svn-log-message-file ()
449  "Return the name of the appropriate log message accumulation file.
450Usually this is just the file `msg' in the current directory, but
451certain areas are treated specially, for example, the Subversion
452source tree."
453  (save-match-data
454    (if (string-match "subversion" default-directory)
455        (concat (substring default-directory 0 (match-end 0)) "/msg")
456      "msg")))
457
458
459(defun svn-log-message (short-file-names)
460  "Add to an in-progress log message, based on context around point.
461If prefix arg SHORT-FILE-NAMES is non-nil, then use basenames only in
462log messages, otherwise use full paths.  The current defun name is
463always used.
464
465If the log message already contains material about this defun, then put
466point there, so adding to that material is easy.
467
468Else if the log message already contains material about this file, put
469point there, and push onto the kill ring the defun name with log
470message dressing around it, plus the raw defun name, so yank and
471yank-next are both useful.
472
473Else if there is no material about this defun nor file anywhere in the
474log message, then put point at the end of the message and insert a new
475entry for file with defun.
476
477See also the function `svn-log-message-file'."
478  (interactive "P")
479  (let ((this-file (if short-file-names
480                       (file-name-nondirectory buffer-file-name)
481                     (svn-log-path-derive buffer-file-name)))
482        (this-defun (or (add-log-current-defun)
483                        (save-excursion
484                          (save-match-data
485                            (if (eq major-mode 'c-mode)
486                                (progn
487                                  (if (fboundp 'c-beginning-of-statement-1)
488                                      (c-beginning-of-statement-1)
489                                    (c-beginning-of-statement))
490                                  (search-forward "(" nil t)
491                                  (forward-char -1)
492                                  (forward-sexp -1)
493                                  (buffer-substring
494                                   (point)
495                                   (progn (forward-sexp 1) (point)))))))))
496        (log-file (svn-log-message-file)))
497    (find-file log-file)
498    (goto-char (point-min))
499    ;; Strip text properties from strings
500    (set-text-properties 0 (length this-file) nil this-file)
501    (set-text-properties 0 (length this-defun) nil this-defun)
502    ;; If log message for defun already in progress, add to it
503    (if (and
504         this-defun                        ;; we have a defun to work with
505         (search-forward this-defun nil t) ;; it's in the log msg already
506         (save-excursion                   ;; and it's about the same file
507           (save-match-data
508             (if (re-search-backward  ; Ick, I want a real filename regexp!
509                  "^\\*\\s-+\\([a-zA-Z0-9-_.@=+^$/%!?(){}<>]+\\)" nil t)
510                 (string-equal (match-string 1) this-file)
511               t))))
512        (if (re-search-forward ":" nil t)
513            (if (looking-at " ") (forward-char 1)))
514      ;; Else no log message for this defun in progress...
515      (goto-char (point-min))
516      ;; But if log message for file already in progress, add to it.
517      (if (search-forward this-file nil t)
518          (progn
519            (if this-defun (progn
520                             (kill-new (format "(%s): " this-defun))
521                             (kill-new this-defun)))
522            (search-forward ")" nil t)
523            (if (looking-at " ") (forward-char 1)))
524        ;; Found neither defun nor its file, so create new entry.
525        (goto-char (point-max))
526        (if (not (bolp)) (insert "\n"))
527        (insert (format "\n* %s (%s): " this-file (or this-defun "")))
528        ;; Finally, if no derived defun, put point where the user can
529        ;; type it themselves.
530        (if (not this-defun) (forward-char -3))))))
531
532
533
534;;; Log message helpers.
535
536(defconst svn-log-msg-sep-line
537  "------------------------------------------------------------------------"
538  "The line of dashes that separates log messages in 'svn log' output.")
539
540(defconst svn-log-msg-boundary-regexp
541  (concat "^" svn-log-msg-sep-line "\n" "r[0-9]+ | ")
542  "Regular expression matching the start of a log msg.  The start is
543the beginning of the separator line, not the rev/author/date line that
544follows the separator line.")
545
546(defun svn-narrow-to-log-msg ()
547  "Narrow to the current Subversion log message.
548This meant to be used while browsing the output of 'svn log'.
549If point is not in such output, error."
550  (interactive)
551  (let ((start nil) (end nil))
552    (save-excursion
553      (re-search-backward svn-log-msg-boundary-regexp)
554      (forward-line 1)
555      (setq start (point))
556      (end-of-line)
557      (re-search-backward "| \\([0-9]+\\) ")
558      (let ((num (match-string 1)))
559        (re-search-forward "^\n")
560        (forward-line (string-to-number num)))
561      (setq end (point)))
562    (narrow-to-region start end)))
563
564
565
566(message "loaded svn-dev.el")
567