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