Remove non-free old and crusty clearcase pkg
[packages] / xemacs-packages / semantic / document.el.upstream
1 ;;; document.el --- Use the semantic parser to generate documentation.
2
3 ;;; Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007 Eric M. Ludlam
4
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6 ;; Keywords: doc
7 ;; X-RCS: $Id: document.el.upstream,v 1.1 2007-11-26 15:10:31 michaels Exp $
8
9 ;; Semantic is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; This software is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, USA.
23
24 ;;; Commentary:
25 ;;
26 ;; Document provides the ability to create a documentation framework
27 ;; for functions and variables.  It uses `semantic' to find the
28 ;; current function, and to provide additional context information for
29 ;; generating the documentation.
30 ;;
31 ;;   Document then provides some rules for creating English Text based
32 ;; on the name of a given function, it's return type, or variable
33 ;; type.  It also has output rules for texinfo, or comments.
34 ;;
35 ;; NOTE: Some of the user level commands in document.el dealing with
36 ;; texinfo files have been obsoleted commands in semantic-texi, which
37 ;; can not insert foriegn tokens.
38
39 (require 'sformat)
40 ;; This contains most variable settings for auto-comment generation.
41 (require 'document-vars)
42
43 ;; XEmacs change: needed to define macros at compile time.
44 (condition-case nil
45     (require 'ede)
46   (error nil))
47 (require 'semantic)
48 (require 'semantic-util)
49
50 ;;; Code:
51
52 ;;; User customizations
53 ;;
54 (defgroup document nil
55   "File and tag browser frame."
56   :group 'semantic
57   :group 'texinfo
58   )
59
60 (defcustom document-my-initials (user-login-name)
61   "*The initials to use when commenting something."
62   :group 'document
63   :type 'string)
64
65 (defcustom document-copyright-holder (user-full-name)
66   "*The string to use as the copyright holder in the file comment."
67   :group 'document
68   :type 'string)
69
70 (defvar document-runflags nil
71   "Flags collected while updating a comment.
72 This is used to create a history element.")
73
74 ;;; Status tracking
75 ;;
76 (defvar document-current-output-file nil
77   "A marker for the current output file used for documentation.")
78
79 ;;; User Functions
80 ;;
81 (defun document (&optional resetfile)
82   "Document in a texinfo file the function or variable the cursor is in.
83 Optional argument RESETFILE is provided w/ universal argument.
84 When non-nil, query for a new documentation file.
85 To document a function in a source file, use `document-inline'."
86   (interactive (if current-prefix-arg
87                    (save-excursion
88                      (list (document-locate-file
89                             (current-buffer) t)))))
90   ;; First, garner some information from Semantic.
91   (semantic-fetch-tags)
92   (let ((cdi (semantic-current-tag))
93         (cdib (current-buffer)))
94     ;; Make sure we have a file.
95     (document-locate-file (current-buffer))
96     ;; Now go and create the documentation
97     (if (not document-current-output-file)
98         (error "No file found for your documentation"))
99     (set-buffer (marker-buffer document-current-output-file))
100     (goto-char document-current-output-file)
101     (insert "\n")
102     (document-insert-texinfo cdi cdib)
103     (insert "\n")
104     (setq document-current-output-file (point-marker))
105     ))
106
107 (defun document-inline ()
108   "Document the current function with an inline comment."
109   (interactive)
110   (semantic-fetch-tags)
111   (let ((cf (semantic-current-tag)))
112     (document-insert-defun-comment cf (current-buffer))))
113
114 ;;; Documentation insertion functions
115 ;;
116 (defun document-insert-texinfo (tag buffer)
117   "Insert texinfo documentation about TAG from BUFFER."
118   (let ((tt (semantic-tag-class tag)))
119     (insert "@"
120             (cond ((eq tt 'variable)
121                    (if (semantic-tag-get-attribute tag :user-visible-flag)
122                        "deffn Option"
123                      "defvar"))
124                   ((eq tt 'function)
125                    (if (semantic-tag-get-attribute tag :user-visible-flag)
126                        "deffn Command"
127                      "defun"))
128                   ((eq tt 'type)
129                    "deffn Type")
130                   (t (error "Don't know how to document that")))
131             " "
132             (semantic-tag-name tag))
133     (if (eq tt 'function)
134         (let ((args (semantic-tag-function-arguments tag)))
135           (while args
136             (insert " ")
137             (if (stringp (car args))
138                 (insert (car args))
139               (insert (semantic-tag-name (car args))))
140             (setq args (cdr args)))))
141     (insert "\n@anchor{" (semantic-tag-name tag) "}\n")
142     (insert (document-massage-to-texinfo
143              tag
144              buffer
145              (document-generate-documentation tag buffer)))
146     (insert "\n@end "
147             (cond ((eq tt 'variable)
148                    (if (semantic-tag-get-attribute tag :user-visible-flag)
149                        "deffn"
150                      "defvar"))
151                   ((eq tt 'function)
152                    (if (semantic-tag-get-attribute tag :user-visible-flag)
153                        "deffn"
154                      "defun"))
155                   ((eq tt 'type)
156                    "deffn"))
157             )))
158
159 (defun document-insert-defun-comment (tag buffer)
160   "Insert mode-comment documentation about TAG from BUFFER."
161   (interactive)
162   (let ((document-runflags nil)
163         (tt (semantic-tag-class tag)))
164     (cond
165      ((eq tt 'function)
166       (if (semantic-documentation-for-tag tag t)
167           (document-update-comment tag)
168         (document-insert-function-comment-new tag))
169       (message "Done..."))
170      (t
171       (error "Type %S is not yet managed by document `document-inline'" tt)))))
172
173 (defun document-update-comment (tag)
174   "Update an existing comment for TAG."
175   (let ((comment (semantic-documentation-for-tag tag 'lex)))
176     (save-excursion
177       (document-update-paramlist tag comment))
178     (semantic-fetch-tags)
179     (let ((ct (semantic-brute-find-tag-by-position
180                (point) (current-buffer))))
181       (setq comment (semantic-documentation-for-tag tag 'lex))
182       (document-update-history comment (document-get-history-elt "")))))
183
184 (defun document-insert-new-file-header (header)
185   "Insert a new header file into this buffer.  Add reference to HEADER.
186 Used by `prototype' if this file doesn't have an introductory comment."
187   (interactive)
188   (goto-char 0)
189   (let ((pnt nil))
190     (insert (document-new-file-header header))
191     (if pnt
192         (goto-char pnt))))
193
194 ;;; Top level comment things.
195 ;;
196 (defun document-new-file-header (&optional header)
197   "Return a comment string customized for the current buffer.
198 Optional HEADER is the header file to use under Token."
199   (Sformat (list (list ?B '(lambda () (document-file-brief-comment)))
200                  (list ?D
201                        (if (boundp 'pnt)
202                            '(lambda () (setq pnt (Sformat-point)) "")
203                          ""))
204                  (list ?N '(lambda ()
205                              (document-copyright-notice)))
206                  (list ?O document-copyright-holder)
207                  (list ?Y (document-get-date-time-string "%Y"))
208                  (list ?T '(lambda ()
209                              (concat
210                               cpr-header-token
211                               " "
212                               (if header header
213                                 (semantic-prototype-file (current-buffer))))))
214                  (list ?H (document-get-history-elt "Created"))
215                  (list ?b (document-comment-start))
216                  (list ?m (document-comment-line-prefix))
217                  (list ?e (document-comment-end)))
218            ;; This is lame!  Fix it sometime soon.
219            (if (string-match "\\.c$" (buffer-file-name))
220                document-file-comment
221              document-header-comment)))
222
223 (defun document-set-copyright-file (f)
224   "Interactively find the file name with the copyright blurb.
225 Argument F is the file to use."
226   (interactive "FCopyright Notice File (RET for none): ")
227   (if (string= f (buffer-file-name))
228       (setq document-copyright-notice-file "")
229     (setq document-copyright-notice-file f)))
230
231 (defun document-copyright-notice ()
232   "Create, or find a copyright notice.
233 Adds the comment line PREFIX to each line."
234   (if (not document-copyright-notice-file)
235       (call-interactively 'document-set-copyright-file))
236   (if (= (length document-copyright-notice-file) 0)
237       "??Public Domain Software??"
238     (let* ((b (get-buffer-create "DOCUMENT TEMP"))
239            (s nil)
240            (plen (Sformat-column))
241            (pstr (substring (concat (document-comment-line-prefix)
242                                     "         ")
243                             0 plen)))
244       (setq s
245             (save-excursion
246               (set-buffer b)
247               (insert-file-contents document-copyright-notice-file)
248               ;; Now put comment marks all over.
249               (goto-char 0)
250               (forward-line 1)
251               (end-of-line)
252               (while (not (eobp))
253                 (beginning-of-line)
254                 (insert pstr)
255                 (end-of-line)
256                 (forward-char 1)
257                 (end-of-line))
258               (forward-char -1)
259               (if (equal (following-char) ?\n)
260                   (delete-char 1))
261               (set-buffer-modified-p nil)
262               (buffer-string)))
263       (kill-buffer b)
264       s)))
265
266 (defun document-file-brief-comment ()
267   "Make a brief comment about the file we are currently editing."
268   (Sformat (list (list ?F (file-name-nondirectory (buffer-file-name)))
269                  (list ?C '(lambda ()
270                             (read-string "Brief Description of file: "))))
271            document-file-brief-comment))
272
273 ;;; Documentatation generation functions
274 ;;
275 (defun document-generate-documentation (tag buffer)
276   "Return a plain string documenting TAG from BUFFER."
277   (save-excursion
278     (set-buffer buffer)
279     (let ((doc ;; Second, does this thing have docs in the source buffer which
280            ;; an override method might be able to find?
281            (semantic-documentation-for-tag tag)
282            ))
283       (if (not doc)
284           (document-generate-new-documentation tag buffer)
285         ;; Ok, now lets see what sort of formatting there might be,
286         ;; and see about removing some of it.. (Tables of arguments,
287         ;; and that sort of thing.)
288         nil
289         ;; Return the string.
290         doc))))
291
292 (defun document-generate-new-documentation (tag buffer)
293   "Look at elements of TAG in BUFFER to make documentation.
294 This will create a new documentation string from scratch."
295   ;; We probably want more than this, but for now it's close.
296   (document-function-name-comment tag))
297
298 ;;; Inline comment mangling.
299 ;;
300 (defun document-insert-function-comment-new (tag)
301   "Insert a new comment which explains the function found in TAG."
302   (let ((hist (document-get-history-elt ""))
303         (pnt 0)
304         (upnt 0)
305         (st 0)
306         (zpnt 0)
307         (fname (semantic-tag-name tag))
308         (returns (semantic-tag-type tag))
309         (params (semantic-tag-function-arguments tag))
310         )
311     (if (listp returns)
312         ;; convert a type list into a long string to analyze.
313         (setq returns (car returns)))
314     ;; tag should always be correct.
315     (goto-char (semantic-tag-start tag))
316     (setq st (point))
317     (insert (Sformat (list (list ?F fname)
318                            (list ?f '(lambda () (setq zpnt (Sformat-point)) ""))
319                            (list ?p '(lambda () (setq pnt (Sformat-point)) ""))
320                            (list ?D (document-function-name-comment tag))
321                            (list ?R (document-insert-return returns))
322                            (list ?P '(lambda ()
323                                        (document-insert-parameters params)))
324                            (list ?H (concat hist document-new-hist-comment))
325                            (list ?b (document-comment-start))
326                            (list ?m (document-comment-line-prefix))
327                            (list ?e (document-comment-end)))
328                      document-function-comment))
329     (goto-char (+ zpnt st))
330     (message "Setting fill prefix to: \"%s\""
331              (setq fill-prefix
332                    (concat (document-comment-line-prefix)
333                            (make-string
334                             (- (current-column)
335                                (length (document-comment-line-prefix)))
336                             ? ))))
337     (goto-char (+ pnt st))
338     (auto-fill-mode 1)
339     )
340   )
341
342 (defun document-function-name-comment (tag)
343   "Create documentation for the function defined in TAG.
344 If we can identify a verb in the list followed by some
345 name part then check the return value to see if we can use that to
346 finish off the sentence.  ie. any function with 'alloc' in it will be
347 allocating something based on its type."
348   (let ((al document-autocomment-return-first-alist)
349         (dropit nil)
350         (tailit nil)
351         (news "")
352         (fname (semantic-tag-name tag))
353         (retval (or (semantic-tag-type tag) "")))
354     (if (listp retval)
355         ;; convert a type list into a long string to analyze.
356         (setq retval (car retval)))
357     ;; check for modifiers like static
358     (while al
359       (if (string-match (car (car al)) (downcase retval))
360           (progn
361             (setq news (concat news (cdr (car al))))
362             (setq dropit t)
363             (setq al nil)))
364       (setq al (cdr al)))
365     ;; check for verb parts!
366     (setq al document-autocomment-function-alist)
367     (while al
368       (if (string-match (car (car al)) (downcase fname))
369           (progn
370             (setq news
371                   (concat news (if dropit (downcase (cdr (car al)))
372                                  (cdr (car al)))))
373             ;; if we end in a space, then we are expecting a potential
374             ;; return value.
375             (if (= ?  (aref news (1- (length news))))
376                 (setq tailit t))
377             (setq al nil)))
378       (setq al (cdr al)))
379     ;; check for noun parts!
380     (setq al document-autocomment-common-nouns-abbrevs)
381     (while al
382       (if (string-match (car (car al)) (downcase fname))
383           (progn
384             (setq news
385                   (concat news (if dropit (downcase (cdr (car al)))
386                                  (cdr (car al)))))
387             (setq al nil)))
388       (setq al (cdr al)))
389     ;; add tailers to names which are obviously returning something.
390     (if tailit
391         (progn
392           (setq al document-autocomment-return-last-alist)
393           (while al
394             (if (string-match (car (car al)) (downcase retval))
395                 (progn
396                   (setq news
397                         (concat news " "
398                                 ;; this one may use parts of the return value.
399                                 (format (cdr (car al))
400                                         (document-programmer->english
401                                          (substring retval (match-beginning 1)
402                                                     (match-end 1))))))
403                   (setq al nil)))
404             (setq al (cdr al)))))
405     news))
406
407 (defun document-insert-return (returnval)
408   "Take the return value, and return a string which is ready to be commented.
409 Argument RETURNVAL is the string representing the type to be returned."
410   (if (not returnval)
411       ""
412     (if (string-match "^\\(static +\\|STATIC +\\)?\\(void\\|VOID\\)" returnval)
413         "Nothing"
414       (if (= (length returnval) 0)
415           "int - "
416         (concat returnval " - ")))))
417   
418 (defun document-insert-parameters (params &optional commentlist)
419   "Convert a parameter list PARAMS into a vertical list separated by -es.
420 Optional COMMENTLIST is a list of previously known parts with comments."
421
422   (let* ((col (if Sformat-formatting (Sformat-column) (current-column)))
423          (newl params)
424          ;; returns is local to the caller
425          (longest (document-longest-name newl))
426          (numdfs 0)
427          (newp ""))
428     (while newl
429       (let* ((n (car newl))
430              (nn (if (stringp n) n (semantic-tag-name n)))
431              (al (if (stringp n) nil (semantic-tag-modifiers n)))
432              (nt (if (stringp n) "" (semantic-tag-type n))))
433         (if (listp nt)
434             ;; make sure this is a string.
435             (setq nt (car nt)))
436         (setq numdfs (1+ numdfs))
437         (let ((nextp (Sformat
438                       (list (list ?P
439                                   (substring (concat
440                                               nn
441                                               "                   ")
442                                              0 longest))
443                             (list ?p n)
444                             (list ?R nt)
445                             (list ?D (document-parameter-comment
446                                       n
447                                       commentlist)))
448                       document-param-element)))
449           (setq newp
450                 (concat
451                  newp nextp
452                  ;; the following always assumes that there is
453                  ;; always a comment starting with SPC * on
454                  ;; every line.  Mabee fix, but this is what I
455                  ;; use, so tough noogies as of right now.
456                  (concat "\n" (document-comment-line-prefix)
457                          (make-string
458                           (- col (length (document-comment-line-prefix)))
459                           ? ))))))
460       (setq newl (cdr newl)))
461     (if (= (length newp) 0) (setq newp "None"))
462     (if (and document-extra-line-after-short-parameters (<= numdfs 1))
463         (setq newp (concat newp "\n *")))
464     newp)
465   )
466
467 (defun document-parameter-comment (param &optional commentlist)
468   "Convert tag or string PARAM into a name,comment pair.
469 Optional COMMENTLIST is list of previously existing comments to
470 use instead in alist form.  If the name doesn't appear in the list of
471 standard names, then englishify it instead."
472   (let ((cmt "")
473         (aso document-autocomment-param-alist)
474         (fnd nil)
475         (name (if (stringp param) param (semantic-tag-name param)))
476         (tt (if (stringp param) nil (semantic-tag-type param))))
477     ;; Make sure the type is a string.
478     (if (listp tt)
479         (setq tt (semantic-tag-name tt)))
480     ;; Find name description parts.
481     (while aso
482       (if (string-match (car (car aso)) name)
483           (progn
484             (setq fnd t)
485             (setq cmt (concat cmt (cdr (car aso))))))
486       (setq aso (cdr aso)))
487     (if (/= (length cmt) 0)
488         nil
489       ;; finally check for array parts
490       (if (and (not (stringp param)) (semantic-tag-modifiers param))
491           (setq cmt (concat cmt "array of ")))
492       (setq aso document-autocomment-param-type-alist)
493       (while (and aso tt)
494         (if (string-match (car (car aso)) tt)
495             (setq cmt (concat cmt (cdr (car aso)))))
496         (setq aso (cdr aso))))
497     ;; Convert from programmer to english.
498     (if (not fnd)
499         (setq cmt (concat cmt " "
500                           (document-programmer->english name))))
501     cmt))
502
503
504 (defun document-get-history-elt (changes)
505   "Return the history element with the change elt set to CHANGES."
506   (Sformat (list '(?U document-my-initials)
507                  (list ?D (document-get-date))
508                  '(?S document-change-number)
509                  '(?C changes))
510            document-history-element))
511
512 (defun document-get-date-time-string (form)
513   "Return a string matching the format of `document-date-element'.
514 Argument FORM is the format string to use."
515   (let* ((date (current-time-string))
516          (garbage
517           (string-match
518            (concat "^\\([A-Z][a-z]*\\) *\\([A-Z][a-z]*\\) *\\([0-9]*\\)"
519            " \\([0-9]*\\):\\([0-9]*\\):\\([0-9]*\\)"
520            " \\([0-9]*\\)$")
521            date))
522          (wkdy (substring date (match-beginning 1) (match-end 1)))
523          (hour (string-to-number
524                 (substring date (match-beginning 4) (match-end 4))))
525          (min (substring date (match-beginning 5) (match-end 5)))
526          (sec (substring date (match-beginning 6) (match-end 6)))
527          (month
528           (cdr (assoc (substring date (match-beginning 2) (match-end 2))
529                       '(("Jan" . 1) ("Feb" . 2) ("Mar" . 3) ("Apr" . 4)
530                         ("May" . 5) ("Jun" . 6) ("Jul" . 7) ("Aug" . 8)
531                         ("Sep" . 9) ("Oct" . 10) ("Nov" . 11) ("Dec" . 12)))))
532          (ms (substring date (match-beginning 2) (match-end 2)))
533          (day (substring date (match-beginning 3) (match-end 3)))
534          (year (substring date (match-beginning 7) (match-end 7))))
535     (Sformat (list (list ?H (% hour 12))
536                    (list ?h hour)
537                    (list ?a (if (> hour 12) "pm" "am"))
538                    (list ?I min)
539                    (list ?S sec)
540                    (list ?D day)
541                    (list ?M month)
542                    (list ?m ms)
543                    (list ?Y year)
544                    (list ?y (substring year 2))
545                    (list ?w wkdy))
546              form)))
547
548 (defun document-get-date ()
549   "Return a string which is the current date."
550   (document-get-date-time-string document-date-element))
551
552 ;;; Updating utilities
553 ;;
554 (defun document-update-history (comment history)
555   "Update COMMENT with the text HISTORY.
556 COMMENT is a `semantic-lex' token."
557   (let ((endpos 0))
558     (save-excursion
559       (goto-char (semantic-lex-token-end comment))
560       (if (not (re-search-backward (regexp-quote (document-comment-start))
561                                    (semantic-lex-token-start comment) t))
562           (error "Comment confuses me"))
563       (let ((s (document-just-after-token-regexp ?H document-function-comment)))
564         (if (not s) (error "Can't find where to enter new history element"))
565         (if (re-search-forward (concat "\\(" s "\\)")
566                                (1+ (semantic-lex-token-end comment)) t)
567             (progn
568               (goto-char (match-beginning 1))
569               (insert (concat "\n" (document-comment-line-prefix) " "))
570               (insert history)))
571         (setq endpos (point))))
572     (goto-char endpos)
573     (while document-runflags
574       (let ((p (assoc (car (car document-runflags))
575                       document-autocomment-modify-alist)))
576         (if p (insert (format (cdr p) (cdr (car document-runflags))))))
577       (setq document-runflags (cdr document-runflags)))))
578
579 (defun document-argument-name (arg)
580   "Return a string representing the name of ARG.
581 Arguments can be semantic tokens, or strings."
582   (cond ((semantic-tag-p arg)
583          (semantic-tag-name arg))
584         ((stringp arg)
585          arg)
586         (t (format "%s" arg))))
587
588 (defun document-update-paramlist (tag comment)
589   "Update TAG's comment found in the `semantic-lex' token COMMENT."
590   (let ((endpos 0) st en (il nil)
591         (case-fold-search nil)
592         (l (semantic-tag-function-arguments tag)))
593     (save-excursion
594       (goto-char (semantic-lex-token-start comment))
595       (let ((s (document-just-after-token-regexp ?P document-function-comment))
596             (s2 (document-just-before-token-regexp ?P document-function-comment)))
597         (if (or (not s) (not s2))
598             (error "Cannot break format string into findable begin and end tokens"))
599         (if (not (re-search-forward (concat "\\(" s "\\)")
600                                     (1+ (semantic-lex-token-end comment)) t))
601             (error "Comment is not formatted correctly for param check"))
602         (goto-char (match-beginning 1))
603         (setq en (point))
604         (goto-char (semantic-lex-token-start comment))
605         (if (not (re-search-forward s2 (semantic-lex-token-end comment) t))
606             (error "Comment is not formatted correctly for param check"))
607         (setq st (point))
608         ;; At this point we have the beginning and end of the
609         ;; parameter list in the comment.  Now lets search through
610         ;; it and generate a list (name . commentpart) so we can
611         ;; re-build it if it doesn't match L
612         (while (re-search-forward
613                 (concat "\\(\\(\\sw\\|\\s_+\\)+\\)\\s-*-[ \t]*")
614                 en t)
615           (let ((n (buffer-substring (match-beginning 1) (match-end 1)))
616                 (c nil))
617             (setq c (point))
618             (re-search-forward "$" (semantic-lex-token-end comment) t)
619             (setq c (buffer-substring c (point)))
620             (setq il (cons (cons n c) il))))
621         ;; run verify on two lists of parameters to make sure they
622         ;; are the same.
623         (let ((tl l) (stop nil))
624           (while (and tl (not stop))
625             (if (not (assoc (document-argument-name (car tl)) il))
626                 (setq stop t))
627             (setq tl (cdr tl)))
628           (if (not stop)
629               (setq il nil)))
630         ;; check if we want to modify the parameter list.
631         (if (not (and il (y-or-n-p "Parameter list changed.  Fix? ")))
632             (message "Not fixing.")
633           ;; delete what was there, and insert the new stuff.
634           (let ((ntl l)
635                 (cs1 nil)
636                 (num 0))
637             (while ntl
638               (if (not (assoc (document-argument-name (car ntl)) il))
639                   (progn
640                     (setq num (1+ num))
641                     (setq cs1 (concat cs1 (if cs1 ", ")
642                                       (document-argument-name (car ntl))))))
643               (setq ntl (cdr ntl)))
644             (if cs1
645                 (if (= num 1)
646                     (setq cs1 (concat "Added parameter " cs1))
647                   (setq cs1 (concat "Added parameters " cs1)))
648               (setq cs1 "Removed parameters."))
649             (setq document-runflags (cons (cons 'document-newparam cs1)
650                                           document-runflags)))
651           (let ((dif (- en st))
652                 (newc nil))
653             (delete-region st en)
654             (setq newc (document-insert-parameters l il))
655             (setq dif (- (length newc) dif))
656             (insert newc)))))
657     (goto-char endpos)))
658
659 ;;; Conversion utilities
660 ;;
661 (defun document-longest-name (list)
662   "Go through LIST, and return the length of the longest name."
663   (let ((longest 1)
664         (nn nil))
665     (while list
666       (setq nn (if (stringp (car list)) (car list)
667                  (semantic-tag-name (car list))))
668       (if (< longest (length nn))
669           (setq longest (length nn)))
670       (setq list (cdr list)))
671     longest))
672
673 (defun document-programmer->english (programmer)
674   "Takes PROGRAMMER and converts it into English.
675 Works with the following rules:
676   1) convert all _ into spaces.
677   2) inserts spaces in front of all lowerUpper case combos
678   3) expands noun names based on common programmer nouns.
679   
680   This function is designed for variables, not functions.  This does
681 not account for verb parts."
682   (let ((ind 0)                         ;index in string
683         (llow nil)                      ;lower/upper case flag
684         (wlist nil)                     ;list of words after breaking
685         (newstr nil)                    ;new string being generated
686         (al nil))                       ;autocomment list
687     ;;
688     ;; 1) Convert underscores
689     ;;
690     (while (< ind (length programmer))
691       (setq newstr (concat newstr
692                            (if (= (aref programmer ind) ?_)
693                                " " (char-to-string (aref programmer ind)))))
694       (setq ind (1+ ind)))
695     (setq programmer newstr
696           newstr nil
697           ind 0)
698     ;;
699     ;; 2) Find word brakes between case changes
700     ;;
701     (while (< ind (length programmer))
702       (setq newstr
703             (concat newstr
704                     (let ((tc (aref programmer ind)))
705                       (if (and (>= tc ?a) (<= tc ?z))
706                           (progn
707                             (setq llow t)
708                             (char-to-string tc))
709                         (if llow
710                             (progn
711                               (setq llow nil)
712                               (concat " " (char-to-string tc)))
713                           (char-to-string tc))))))
714       (setq ind (1+ ind)))
715     ;;
716     ;; 3) Expand the words if possible
717     ;;
718     (setq llow nil
719           ind 0
720           programmer newstr
721           newstr nil)
722     (while (string-match (concat "^\\s-*\\([^ \t\n]+\\)") programmer)
723       (let ((ts (substring programmer (match-beginning 1) (match-end 1)))
724             (end (match-end 1)))
725         (setq al document-autocomment-common-nouns-abbrevs)
726         (setq llow nil)
727         (while al
728           (if (string-match (car (car al)) (downcase ts))
729               (progn
730                 (setq newstr (concat newstr (cdr (car al))))
731                 ;; don't terminate because we may actuall have 2 words
732                 ;; next to eachother we didn't identify before
733                 (setq llow t)))
734           (setq al (cdr al)))
735         (if (not llow) (setq newstr (concat newstr ts)))
736         (setq newstr (concat newstr " "))
737         (setq programmer (substring programmer end))))
738     newstr))
739
740 \f
741 ;;; Sformat string managers
742 ;;
743 ;; These two routines find the string between different % tokens, and
744 ;; returns them as regular expressions vie regexp-quote.  The result
745 ;; will allow a program to find text surrounding major parts within a
746 ;; comment, thus, the parts in a comment that need to be changed.
747
748 (defun document-just-before-token-regexp (token format)
749   "Return a search expression for text before TOKEN in FORMAT.
750 This search string can be used to find the text residing in TOKEN
751 if it were inserted with FORMAT in the past."
752   (setq format (document-format-for-native-comments format))
753   (sformat-just-before-token-regexp token format))
754
755 (defun document-just-after-token-regexp (token format)
756   "Return a search expression for text after TOKEN in FORMAT.
757 This search string can be used to find the text residing in TOKEN
758 if it were inserted with FORMAT in the past."
759   (setq format (document-format-for-native-comments format))
760   (sformat-just-after-token-regexp token format))
761
762 ;; This function adds in the comment thingies so that the above
763 ;; functions can work some magic.
764 (defun document-format-for-native-comments (formatstr)
765   "Return FORMATSTR with the comment formatters filled in.
766 Leaves other formatting elements the way they are."
767   (Sformat (list (list ?b (document-comment-start))
768                  (list ?m (document-comment-line-prefix))
769                  (list ?e (document-comment-end)))
770            formatstr))
771
772 \f
773 ;;; Texinfo mangling.
774 ;;
775 (defun document-massage-to-texinfo (tag buffer string)
776   "Massage TAG's documentation from BUFFER as STRING.
777 This is to take advantage of TeXinfo's markup symbols."
778   (let ((mode (with-current-buffer buffer (semantic-tag-mode tag))))
779     (when (eq mode 'emacs-lisp-mode)
780       ;; Elisp has a few advantages.  Hack it in.
781       (setq string (document-texify-elisp-docstring string)))
782     ;; Else, other languages are simpler.  Also, might as well
783     ;; run the elisp version through also.
784     (let ((case-fold-search nil)
785           (start 0))
786       (while (string-match
787               "\\(^\\|[^{]\\)\\<\\([A-Z0-9_-]+\\)\\>\\($\\|[^}]\\)"
788               string start)
789         (let ((ms (match-string 2 string)))
790           (when (eq mode 'emacs-lisp-mode)
791             (setq ms (downcase ms)))
792         
793           (when (not (or (string= ms "A")
794                          (string= ms "a")
795                          ))
796             (setq string (concat (substring string 0 (match-beginning 2))
797                                  "@var{"
798                                  ms
799                                  "}"
800                                  (substring string (match-end 2))))))
801         (setq start (match-end 2)))
802       )
803     string))
804
805 ;; This FN was taken from EIEIO and modified.  Maybe convert later.
806 (defun document-texify-elisp-docstring (string)
807   "Take STRING, (a normal doc string), and convert it into a texinfo string.
808 For instances where CLASS is the class being referenced, do not Xref
809 that class.
810
811  `function' => @dfn{function}
812  `variable' => @code{variable}
813  `class'    => @code{class} @xref{class}
814  `unknown'  => @code{unknonwn}
815  \"text\"     => ``text''
816  'quoteme   => @code{quoteme}
817  non-nil    => non-@code{nil}
818  t          => @code{t}
819  :tag       => @code{:tag}
820  [ stuff ]  => @code{[ stuff ]}
821  Key        => @kbd{Key}     (key is C\\-h, M\\-h, SPC, RET, TAB and the like)
822  ...        => @dots{}"
823   (while (string-match "`\\([-a-zA-Z0-9<>.]+\\)'" string)
824     (let* ((vs (substring string (match-beginning 1) (match-end 1)))
825            (v (intern-soft vs)))
826       (setq string
827             (concat
828              (replace-match (concat
829                              (if (fboundp v)
830                                  "@dfn{" "@code{")
831                              vs "}")
832                     nil t string)))))
833   (while (string-match "\\( \\|^\\)\\(nil\\|t\\|'[-a-zA-Z0-9]+\\|:[-a-zA-Z0-9]+\\)\\([. ,]\\|$\\)" string)
834     (setq string (replace-match "@code{\\2}" t nil string 2)))
835   (while (string-match "\\( \\|^\\)\\(\\(non-\\)\\(nil\\)\\)\\([. ,]\\|$\\)" string)
836     (setq string (replace-match "\\3@code{\\4}" t nil string 2)))
837   (while (string-match "\\( \\|^\\)\\(\\[[^]]+\\]\\)\\( \\|$\\)" string)
838     (setq string (replace-match "@code{\\2}" t nil string 2)))
839   (while (string-match "\\( \\|^\\)\\(\\(\\(C-\\|M-\\|S-\\)+\\([^ \t\n]\\|RET\\|SPC\\|TAB\\)\\)\\|\\(RET\\|SPC\\|TAB\\)\\)\\( \\|\\s.\\|$\\)" string)
840     (setq string (replace-match "@kbd{\\2}" t nil string 2)))
841   (while (string-match "\"\\(.+\\)\"" string)
842     (setq string (replace-match "``\\1''" t nil string 0)))
843   (while (string-match "\\.\\.\\." string)
844     (setq string (replace-match "@dots{}" t nil string 0)))
845   string)
846
847 ;;; Buffer finding and managing
848 ;;
849 (defun document-find-file (file)
850   "Load up the document file FILE.
851 Make it current, and return a marker for the location of newly inserted
852 documentation."
853   (set-buffer (find-file-noselect file))
854   ;; Theoretically, we should add some smarts here for positioning
855   ;; the cursor.  For now, do some simple stuff.
856   (if (eq (point) (point-min))
857       (progn
858         (switch-to-buffer (current-buffer))
859         (error "Position cursor in %s, and try inserting documentation again"
860                file))
861     (point-marker)))
862
863 (defun document-locate-file (buffer &optional override)
864   "Return a file in which documentation belonging to BUFFER should be placed.
865 Optional argument OVERRIDE indicates to override the last used location."
866   (if (and document-current-output-file (not override))
867       document-current-output-file
868     ;; Else, perform some default behaviors
869     (let ((files (if (and (fboundp 'ede-documentation-files) ede-minor-mode)
870                      (save-excursion
871                        (set-buffer buffer)
872                        (ede-documentation-files))
873                    ))
874           (choice nil))
875       (while files
876         (setq choice (cons (list (car files)) choice)
877               files (cdr files)))
878       (setq choice
879             (if choice
880                 (completing-read "Documentation File: "
881                                  choice
882                                  nil t (car choice))
883               (read-file-name "Documentation File: "
884                               default-directory)))
885       (setq document-current-output-file (document-find-file choice)))))
886       
887
888 (provide 'document)
889
890 ;;; document.el ends here