Fix require error when using srecode-insert.
[bpt/emacs.git] / lisp / cedet / srecode / insert.el
1 ;;; srecode/insert.el --- Insert srecode templates to an output stream.
2
3 ;; Copyright (C) 2005, 2007-2012 Free Software Foundation, Inc.
4
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs 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 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs 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. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23 ;;
24 ;; Define and implements specific inserter objects.
25 ;;
26 ;; Manage the insertion process for a template.
27 ;;
28
29 (eval-when-compile
30 (require 'cl)) ;; for `lexical-let'
31
32 (require 'srecode/compile)
33 (require 'srecode/find)
34 (require 'srecode/dictionary)
35 (require 'srecode/args)
36 (require 'srecode/filters)
37
38 (defvar srecode-template-inserter-point)
39 (declare-function srecode-overlaid-activate "srecode/fields")
40 (declare-function srecode-template-inserted-region "srecode/fields")
41
42 ;;; Code:
43
44 (defcustom srecode-insert-ask-variable-method 'ask
45 "Determine how to ask for a dictionary value when inserting a template.
46 Only the ASK style inserter will query the user for a value.
47 Dictionary value references that ask begin with the ? character.
48 Possible values are:
49 'ask - Prompt in the minibuffer as the value is inserted.
50 'field - Use the dictionary macro name as the inserted value,
51 and place a field there. Matched fields change together.
52
53 NOTE: The field feature does not yet work with XEmacs."
54 :group 'srecode
55 :type '(choice (const :tag "Ask" ask)
56 (const :tag "Field" field)))
57
58 (defvar srecode-insert-with-fields-in-progress nil
59 "Non-nil means that we are actively inserting a template with fields.")
60
61 ;;; INSERTION COMMANDS
62 ;;
63 ;; User level commands for inserting stuff.
64 (defvar srecode-insertion-start-context nil
65 "The context that was at point at the beginning of the template insertion.")
66
67 (defun srecode-insert-again ()
68 "Insert the previously inserted template (by name) again."
69 (interactive)
70 (let ((prev (car srecode-read-template-name-history)))
71 (if prev
72 (srecode-insert prev)
73 (call-interactively 'srecode-insert))))
74
75 ;;;###autoload
76 (defun srecode-insert (template-name &rest dict-entries)
77 "Insert the template TEMPLATE-NAME into the current buffer at point.
78 DICT-ENTRIES are additional dictionary values to add."
79 (interactive (list (srecode-read-template-name "Template Name: ")))
80 (if (not (srecode-table))
81 (error "No template table found for mode %s" major-mode))
82 (let ((newdict (srecode-create-dictionary))
83 (temp (srecode-template-get-table (srecode-table) template-name))
84 (srecode-insertion-start-context (srecode-calculate-context))
85 )
86 (if (not temp)
87 (error "No Template named %s" template-name))
88 (while dict-entries
89 (srecode-dictionary-set-value newdict
90 (car dict-entries)
91 (car (cdr dict-entries)))
92 (setq dict-entries (cdr (cdr dict-entries))))
93 (srecode-insert-fcn temp newdict)
94 ;; Don't put code here. We need to return the end-mark
95 ;; for this insertion step.
96 ))
97
98 (defun srecode-insert-fcn (template dictionary &optional stream skipresolver)
99 "Insert TEMPLATE using DICTIONARY into STREAM.
100 Optional SKIPRESOLVER means to avoid refreshing the tag list,
101 or resolving any template arguments. It is assumed the caller
102 has set everything up already."
103 ;; Perform the insertion.
104 (let ((standard-output (or stream (current-buffer)))
105 (end-mark nil))
106 ;; Merge any template entries into the input dictionary.
107 (when (slot-boundp template 'dictionary)
108 (srecode-dictionary-merge dictionary (oref template dictionary)))
109
110 (unless skipresolver
111 ;; Make sure the semantic tags are up to date.
112 (semantic-fetch-tags)
113 ;; Resolve the arguments
114 (srecode-resolve-arguments template dictionary))
115 ;; Insert
116 (if (bufferp standard-output)
117 ;; If there is a buffer, turn off various hooks. This will cause
118 ;; the mod hooks to be buffered up during the insert, but
119 ;; prevent tools like font-lock from fontifying mid-template.
120 ;; Especially important during insertion of complex comments that
121 ;; cause the new font-lock to comment-color stuff after the inserted
122 ;; comment.
123 ;;
124 ;; I'm not sure about the motion hooks. It seems like a good
125 ;; idea though.
126 ;;
127 ;; Borrowed these concepts out of font-lock.
128 ;;
129 ;; I tried `combine-after-change-calls', but it did not have
130 ;; the effect I wanted.
131 (let ((start (point)))
132 (let ((inhibit-point-motion-hooks t)
133 (inhibit-modification-hooks t)
134 )
135 (srecode--insert-into-buffer template dictionary)
136 )
137 ;; Now call those after change functions.
138 (run-hook-with-args 'after-change-functions
139 start (point) 0)
140 )
141 (srecode-insert-method template dictionary))
142 ;; Handle specialization of the POINT inserter.
143 (when (and (bufferp standard-output)
144 (slot-boundp 'srecode-template-inserter-point 'point)
145 )
146 (set-buffer standard-output)
147 (setq end-mark (point-marker))
148 (goto-char (oref srecode-template-inserter-point point)))
149 (oset-default 'srecode-template-inserter-point point eieio-unbound)
150
151 ;; Return the end-mark.
152 (or end-mark (point)))
153 )
154
155 (defun srecode--insert-into-buffer (template dictionary)
156 "Insert a TEMPLATE with DICTIONARY into a buffer.
157 Do not call this function yourself. Instead use:
158 `srecode-insert' - Inserts by name.
159 `srecode-insert-fcn' - Insert with objects.
160 This function handles the case from one of the above functions when
161 the template is inserted into a buffer. It looks
162 at `srecode-insert-ask-variable-method' to decide if unbound dictionary
163 entries ask questions or insert editable fields.
164
165 Buffer based features related to change hooks is handled one level up."
166 ;; This line prevents the field archive from being let bound
167 ;; while the field insert tool is loaded via autoloads during
168 ;; the insert.
169 (when (eq srecode-insert-ask-variable-method 'field)
170 (require 'srecode/fields))
171
172 (let ((srecode-field-archive nil) ; Prevent field leaks during insert
173 (start (point)) ; Beginning of the region.
174 )
175 ;; This sub-let scopes the 'in-progress' piece so we know
176 ;; when to setup the end-template.
177 (let ((srecode-insert-with-fields-in-progress
178 (if (eq srecode-insert-ask-variable-method 'field) t nil))
179 )
180 (srecode-insert-method template dictionary)
181 )
182 ;; If we are not in-progress, and we insert fields, then
183 ;; create the end-template with fields editable area.
184 (when (and (not srecode-insert-with-fields-in-progress)
185 (eq srecode-insert-ask-variable-method 'field) ; Only if user asked
186 srecode-field-archive ; Only if there were fields created
187 )
188 (let ((reg
189 ;; Create the field-driven editable area.
190 (srecode-template-inserted-region
191 "TEMPLATE" :start start :end (point))))
192 (srecode-overlaid-activate reg))
193 )
194 ;; We return with 'point being the end of the template insertion
195 ;; area. Return value is not important.
196 ))
197
198 ;;; TEMPLATE ARGUMENTS
199 ;;
200 ;; Some templates have arguments. Each argument is associated with
201 ;; a function that can resolve the inputs needed.
202 (defun srecode-resolve-arguments (temp dict)
203 "Resolve all the arguments needed by the template TEMP.
204 Apply anything learned to the dictionary DICT."
205 (srecode-resolve-argument-list (oref temp args) dict temp))
206
207 (defun srecode-resolve-argument-list (args dict &optional temp)
208 "Resolve arguments in the argument list ARGS.
209 ARGS is a list of symbols, such as :blank, or :file.
210 Apply values to DICT.
211 Optional argument TEMP is the template that is getting its arguments resolved."
212 (let ((fcn nil))
213 (while args
214 (setq fcn (intern-soft (concat "srecode-semantic-handle-"
215 (symbol-name (car args)))))
216 (if (not fcn)
217 (error "Error resolving template argument %S" (car args)))
218 (if temp
219 (condition-case nil
220 ;; Allow some to accept a 2nd argument optionally.
221 ;; They throw an error if not available, so try again.
222 (funcall fcn dict temp)
223 (wrong-number-of-arguments (funcall fcn dict)))
224 (funcall fcn dict))
225 (setq args (cdr args)))
226 ))
227
228 ;;; INSERTION STACK & METHOD
229 ;;
230 ;; Code managing the top-level insert method and the current
231 ;; insertion stack.
232 ;;
233 (defmethod srecode-push ((st srecode-template))
234 "Push the srecoder template ST onto the active stack."
235 (oset st active (cons st (oref st active))))
236
237 (defmethod srecode-pop :STATIC ((st srecode-template))
238 "Pop the srecoder template ST onto the active stack.
239 ST can be a class, or an object."
240 (oset st active (cdr (oref st active))))
241
242 (defmethod srecode-peek :STATIC ((st srecode-template))
243 "Fetch the topmost active template record. ST can be a class."
244 (car (oref st active)))
245
246 (defmethod srecode-insert-method ((st srecode-template) dictionary)
247 "Insert the srecoder template ST."
248 ;; Merge any template entries into the input dictionary.
249 ;; This may happen twice since some templates arguments need
250 ;; these dictionary values earlier, but these values always
251 ;; need merging for template inserting in other templates.
252 (when (slot-boundp st 'dictionary)
253 (srecode-dictionary-merge dictionary (oref st dictionary)))
254 ;; Do an insertion.
255 (unwind-protect
256 (let ((c (oref st code)))
257 (srecode-push st)
258 (srecode-insert-code-stream c dictionary))
259 ;; Popping the stack is protected.
260 (srecode-pop st)))
261
262 (defun srecode-insert-code-stream (code dictionary)
263 "Insert the CODE from a template into `standard-output'.
264 Use DICTIONARY to resolve any macros."
265 (while code
266 (cond ((stringp (car code))
267 (princ (car code)))
268 (t
269 (srecode-insert-method (car code) dictionary)))
270 (setq code (cdr code))))
271
272 ;;; INSERTERS
273 ;;
274 ;; Specific srecode inserters.
275 ;; The base class is from srecode-compile.
276 ;;
277 ;; Each inserter handles various macro codes from the template.
278 ;; The `code' slot specifies a character used to identify which
279 ;; inserter is to be created.
280 ;;
281 (defclass srecode-template-inserter-newline (srecode-template-inserter)
282 ((key :initform "\n"
283 :allocation :class
284 :documentation
285 "The character code used to identify inserters of this style.")
286 (hard :initform nil
287 :initarg :hard
288 :documentation
289 "Is this a hard newline (always inserted) or optional?
290 Optional newlines don't insert themselves if they are on a blank line
291 by themselves.")
292 )
293 "Insert a newline, and possibly do indenting.
294 Specify the :indent argument to enable automatic indentation when newlines
295 occur in your template.")
296
297 (defmethod srecode-insert-method ((sti srecode-template-inserter-newline)
298 dictionary)
299 "Insert the STI inserter."
300 ;; To be safe, indent the previous line since the template will
301 ;; change what is there to indent
302 (let ((i (srecode-dictionary-lookup-name dictionary "INDENT"))
303 (inbuff (bufferp standard-output))
304 (doit t)
305 (pm (point-marker)))
306 (when (and inbuff (not (oref sti hard)))
307 ;; If this is not a hard newline, we need do the calculation
308 ;; and set "doit" to nil.
309 (beginning-of-line)
310 (save-restriction
311 (narrow-to-region (point) pm)
312 (when (looking-at "\\s-*$")
313 (setq doit nil)))
314 (goto-char pm)
315 )
316 ;; Do indentation regardless of the newline.
317 (when (and (eq i t) inbuff)
318 (indent-according-to-mode)
319 (goto-char pm))
320
321 (when doit
322 (princ "\n")
323 ;; Indent after the newline, particularly for numeric indents.
324 (cond ((and (eq i t) (bufferp standard-output))
325 ;; WARNING - indent according to mode requires that standard-output
326 ;; is a buffer!
327 ;; @todo - how to indent in a string???
328 (setq pm (point-marker))
329 (indent-according-to-mode)
330 (goto-char pm))
331 ((numberp i)
332 (princ (make-string i " ")))
333 ((stringp i)
334 (princ i))))))
335
336 (defmethod srecode-dump ((ins srecode-template-inserter-newline) indent)
337 "Dump the state of the SRecode template inserter INS."
338 (call-next-method)
339 (when (oref ins hard)
340 (princ " : hard")
341 ))
342
343 (defclass srecode-template-inserter-blank (srecode-template-inserter)
344 ((key :initform "\r"
345 :allocation :class
346 :documentation
347 "The character representing this inserter style.
348 Can't be blank, or it might be used by regular variable insertion.")
349 (where :initform 'begin
350 :initarg :where
351 :documentation
352 "This should be 'begin or 'end, indicating where to insert a CR.
353 When set to 'begin, it will insert a CR if we are not at 'bol'.
354 When set to 'end it will insert a CR if we are not at 'eol'.")
355 ;; @TODO - Add slot and control for the number of blank
356 ;; lines before and after point.
357 )
358 "Insert a newline before and after a template, and possibly do indenting.
359 Specify the :blank argument to enable this inserter.")
360
361 (defmethod srecode-insert-method ((sti srecode-template-inserter-blank)
362 dictionary)
363 "Make sure there is no text before or after point."
364 (let ((i (srecode-dictionary-lookup-name dictionary "INDENT"))
365 (inbuff (bufferp standard-output))
366 (pm (point-marker)))
367 (when (and inbuff
368 ;; Don't do this if we are not the active template.
369 (= (length (oref srecode-template active)) 1))
370
371 (when (and (eq i t) inbuff (not (eq (oref sti where) 'begin)))
372 (indent-according-to-mode)
373 (goto-char pm))
374
375 (cond ((and (eq (oref sti where) 'begin) (not (bolp)))
376 (princ "\n"))
377 ((eq (oref sti where) 'end)
378 ;; If there is whitespace after pnt, then clear it out.
379 (when (looking-at "\\s-*$")
380 (delete-region (point) (point-at-eol)))
381 (when (not (eolp))
382 (princ "\n")))
383 )
384 (setq pm (point-marker))
385 (when (and (eq i t) inbuff (not (eq (oref sti where) 'end)))
386 (indent-according-to-mode)
387 (goto-char pm))
388 )))
389
390 (defclass srecode-template-inserter-comment (srecode-template-inserter)
391 ((key :initform ?!
392 :allocation :class
393 :documentation
394 "The character code used to identify inserters of this style.")
395 )
396 "Allow comments within template coding. This inserts nothing.")
397
398 (defmethod srecode-inserter-prin-example :STATIC ((ins srecode-template-inserter-comment)
399 escape-start escape-end)
400 "Insert an example using inserter INS.
401 Arguments ESCAPE-START and ESCAPE-END are the current escape sequences in use."
402 (princ " ")
403 (princ escape-start)
404 (princ "! Miscellaneous text commenting in your template. ")
405 (princ escape-end)
406 (terpri)
407 )
408
409 (defmethod srecode-insert-method ((sti srecode-template-inserter-comment)
410 dictionary)
411 "Don't insert anything for comment macros in STI."
412 nil)
413
414
415 (defclass srecode-template-inserter-variable (srecode-template-inserter)
416 ((key :initform nil
417 :allocation :class
418 :documentation
419 "The character code used to identify inserters of this style."))
420 "Insert the value of a dictionary entry.
421 If there is no entry, insert nothing.")
422
423 (defvar srecode-inserter-variable-current-dictionary nil
424 "The active dictionary when calling a variable filter.")
425
426 (defmethod srecode-insert-variable-secondname-handler
427 ((sti srecode-template-inserter-variable) dictionary value secondname)
428 "For VALUE handle SECONDNAME behaviors for this variable inserter.
429 Return the result as a string.
430 By default, treat as a function name.
431 If SECONDNAME is nil, return VALUE."
432 (if secondname
433 (let ((fcnpart (read secondname)))
434 (if (fboundp fcnpart)
435 (let ((srecode-inserter-variable-current-dictionary dictionary))
436 (funcall fcnpart value))
437 ;; Else, warn.
438 (error "Variable insertion second arg %s is not a function"
439 secondname)))
440 value))
441
442 (defmethod srecode-insert-method ((sti srecode-template-inserter-variable)
443 dictionary)
444 "Insert the STI inserter."
445 ;; Convert the name into a name/fcn pair
446 (let* ((name (oref sti :object-name))
447 (fcnpart (oref sti :secondname))
448 (val (srecode-dictionary-lookup-name
449 dictionary name))
450 (do-princ t)
451 )
452 ;; Alert if a macro wasn't found.
453 (when (not val)
454 (message "Warning: macro %S was not found in the dictionary." name)
455 (setq val ""))
456 ;; If there was a functional part, call that function.
457 (cond ;; Strings
458 ((stringp val)
459 (setq val (srecode-insert-variable-secondname-handler
460 sti dictionary val fcnpart)))
461 ;; Compound data value
462 ((srecode-dictionary-compound-value-child-p val)
463 ;; Force FCN to be a symbol
464 (when fcnpart (setq fcnpart (read fcnpart)))
465 ;; Convert compound value to a string with the fcn.
466 (setq val (srecode-compound-toString val fcnpart dictionary))
467 ;; If the value returned is nil, then it may be a special
468 ;; field inserter that requires us to set do-princ to nil.
469 (when (not val)
470 (setq do-princ nil)
471 )
472 )
473 ;; Dictionaries... not allowed in this style
474 ((srecode-dictionary-child-p val)
475 (error "Macro %s cannot insert a dictionary - use section macros instead"
476 name))
477 ;; Other stuff... convert
478 (t
479 (error "Macro %s cannot insert arbitrary data" name)
480 ;;(if (and val (not (stringp val)))
481 ;; (setq val (format "%S" val))))
482 ))
483 ;; Output the dumb thing unless the type of thing specifically
484 ;; did the inserting for us.
485 (when do-princ
486 (princ val))))
487
488 (defclass srecode-template-inserter-ask (srecode-template-inserter-variable)
489 ((key :initform ??
490 :allocation :class
491 :documentation
492 "The character code used to identify inserters of this style.")
493 (prompt :initarg :prompt
494 :initform nil
495 :documentation
496 "The prompt used to query for this dictionary value.")
497 (defaultfcn :initarg :defaultfcn
498 :initform nil
499 :documentation
500 "The function which can calculate a default value.")
501 (read-fcn :initarg :read-fcn
502 :initform 'read-string
503 :documentation
504 "The function used to read in the text for this prompt.")
505 )
506 "Insert the value of a dictionary entry.
507 If there is no entry, prompt the user for the value to use.
508 The prompt text used is derived from the previous PROMPT command in the
509 template file.")
510
511 (defmethod srecode-inserter-apply-state
512 ((ins srecode-template-inserter-ask) STATE)
513 "For the template inserter INS, apply information from STATE.
514 Loop over the prompts to see if we have a match."
515 (let ((prompts (oref STATE prompts))
516 )
517 (while prompts
518 (when (string= (semantic-tag-name (car prompts))
519 (oref ins :object-name))
520 (oset ins :prompt
521 (semantic-tag-get-attribute (car prompts) :text))
522 (oset ins :defaultfcn
523 (semantic-tag-get-attribute (car prompts) :default))
524 (oset ins :read-fcn
525 (or (semantic-tag-get-attribute (car prompts) :read)
526 'read-string))
527 )
528 (setq prompts (cdr prompts)))
529 ))
530
531 (defmethod srecode-insert-method ((sti srecode-template-inserter-ask)
532 dictionary)
533 "Insert the STI inserter."
534 (let ((val (srecode-dictionary-lookup-name
535 dictionary (oref sti :object-name))))
536 (if val
537 ;; Does some extra work. Oh well.
538 (call-next-method)
539
540 ;; How is our -ask value determined?
541 (if srecode-insert-with-fields-in-progress
542 ;; Setup editable fields.
543 (setq val (srecode-insert-method-field sti dictionary))
544 ;; Ask the question...
545 (setq val (srecode-insert-method-ask sti dictionary)))
546
547 ;; After asking, save in the dictionary so that
548 ;; the user can use the same name again later.
549 (srecode-dictionary-set-value
550 (srecode-root-dictionary dictionary)
551 (oref sti :object-name) val)
552
553 ;; Now that this value is safely stowed in the dictionary,
554 ;; we can do what regular inserters do.
555 (call-next-method))))
556
557 (defmethod srecode-insert-ask-default ((sti srecode-template-inserter-ask)
558 dictionary)
559 "Derive the default value for an askable inserter STI.
560 DICTIONARY is used to derive some values."
561 (let ((defaultfcn (oref sti :defaultfcn)))
562 (cond ((stringp defaultfcn)
563 defaultfcn)
564 ((functionp defaultfcn)
565 (funcall defaultfcn))
566 ((and (listp defaultfcn)
567 (eq (car defaultfcn) 'macro))
568 (srecode-dictionary-lookup-name
569 dictionary (cdr defaultfcn)))
570 ((null defaultfcn)
571 "")
572 (t
573 (error "Unknown default for prompt: %S"
574 defaultfcn)))))
575
576 (defmethod srecode-insert-method-ask ((sti srecode-template-inserter-ask)
577 dictionary)
578 "Do the \"asking\" for the template inserter STI.
579 Use DICTIONARY to resolve values."
580 (let* ((prompt (oref sti prompt))
581 (default (srecode-insert-ask-default sti dictionary))
582 (reader (oref sti :read-fcn))
583 (val nil)
584 )
585 (cond ((eq reader 'y-or-n-p)
586 (if (y-or-n-p (or prompt
587 (format "%s? "
588 (oref sti :object-name))))
589 (setq val default)
590 (setq val "")))
591 ((eq reader 'read-char)
592 (setq val (format
593 "%c"
594 (read-char (or prompt
595 (format "Char for %s: "
596 (oref sti :object-name))))))
597 )
598 (t
599 (save-excursion
600 (setq val (funcall reader
601 (or prompt
602 (format "Specify %s: "
603 (oref sti :object-name)))
604 default
605 )))))
606 ;; Return our derived value.
607 val)
608 )
609
610 (defmethod srecode-insert-method-field ((sti srecode-template-inserter-ask)
611 dictionary)
612 "Create an editable field for the template inserter STI.
613 Use DICTIONARY to resolve values."
614 (let* ((default (srecode-insert-ask-default sti dictionary))
615 (compound-value
616 (srecode-field-value (oref sti :object-name)
617 :firstinserter sti
618 :defaultvalue default))
619 )
620 ;; Return this special compound value as the thing to insert.
621 ;; This special compound value will repeat our asked question
622 ;; across multiple locations.
623 compound-value))
624
625 (defmethod srecode-dump ((ins srecode-template-inserter-ask) indent)
626 "Dump the state of the SRecode template inserter INS."
627 (call-next-method)
628 (princ " : \"")
629 (princ (oref ins prompt))
630 (princ "\"")
631 )
632
633 (defclass srecode-template-inserter-width (srecode-template-inserter-variable)
634 ((key :initform ?|
635 :allocation :class
636 :documentation
637 "The character code used to identify inserters of this style.")
638 )
639 "Inserts the value of a dictionary variable with a specific width.
640 The second argument specifies the width, and a pad, separated by a colon.
641 Thus a specification of `10:left' will insert the value of A
642 to 10 characters, with spaces added to the left. Use `right' for adding
643 spaces to the right.")
644
645 (defmethod srecode-insert-variable-secondname-handler
646 ((sti srecode-template-inserter-width) dictionary value width)
647 "For VALUE handle WIDTH behaviors for this variable inserter.
648 Return the result as a string.
649 By default, treat as a function name."
650 (if width
651 ;; Trim or pad to new length
652 (let* ((split (split-string width ":"))
653 (width (string-to-number (nth 0 split)))
654 (second (nth 1 split))
655 (pad (cond ((or (null second) (string= "right" second))
656 'right)
657 ((string= "left" second)
658 'left)
659 (t
660 (error "Unknown pad type %s" second)))))
661 (if (>= (length value) width)
662 ;; Simple case - too long.
663 (substring value 0 width)
664 ;; We need to pad on one side or the other.
665 (let ((padchars (make-string (- width (length value)) ? )))
666 (if (eq pad 'left)
667 (concat padchars value)
668 (concat value padchars)))))
669 (error "Width not specified for variable/width inserter")))
670
671 (defmethod srecode-inserter-prin-example :STATIC ((ins srecode-template-inserter-width)
672 escape-start escape-end)
673 "Insert an example using inserter INS.
674 Arguments ESCAPE-START and ESCAPE-END are the current escape sequences in use."
675 (princ " ")
676 (princ escape-start)
677 (princ "|A:10:right")
678 (princ escape-end)
679 (terpri)
680 )
681
682 (defvar srecode-template-inserter-point-override nil
683 "Point-positioning method for the SRecode template inserter.
684 When nil, perform normal point-positioning behavior.
685 When the value is a cons cell (DEPTH . FUNCTION), call FUNCTION
686 instead, unless the template nesting depth, measured
687 by (length (oref srecode-template active)), is greater than
688 DEPTH.")
689
690
691 (defclass srecode-template-inserter-point (srecode-template-inserter)
692 ((key :initform ?^
693 :allocation :class
694 :documentation
695 "The character code used to identify inserters of this style.")
696 (point :type (or null marker)
697 :allocation :class
698 :documentation
699 "Record the value of (point) in this class slot.
700 It is the responsibility of the inserter algorithm to clear this
701 after a successful insertion."))
702 "Record the value of (point) when inserted.
703 The cursor is placed at the ^ macro after insertion.
704 Some inserter macros, such as `srecode-template-inserter-include-wrap'
705 will place text at the ^ macro from the included macro.")
706
707 (defmethod srecode-inserter-prin-example :STATIC ((ins srecode-template-inserter-point)
708 escape-start escape-end)
709 "Insert an example using inserter INS.
710 Arguments ESCAPE-START and ESCAPE-END are the current escape sequences in use."
711 (princ " ")
712 (princ escape-start)
713 (princ "^")
714 (princ escape-end)
715 (terpri)
716 )
717
718 (defmethod srecode-insert-method ((sti srecode-template-inserter-point)
719 dictionary)
720 "Insert the STI inserter.
721 Save point in the class allocated 'point' slot.
722 If `srecode-template-inserter-point-override' non-nil then this
723 generalized marker will do something else. See
724 `srecode-template-inserter-include-wrap' as an example."
725 ;; If `srecode-template-inserter-point-override' is non-nil, its car
726 ;; is the maximum template nesting depth for which the override is
727 ;; valid. Compare this to the actual template nesting depth and
728 ;; maybe use the override function which is stored in the cdr.
729 (if (and srecode-template-inserter-point-override
730 (<= (length (oref srecode-template active))
731 (car srecode-template-inserter-point-override)))
732 ;; Disable the old override while we do this.
733 (let ((over (cdr srecode-template-inserter-point-override))
734 (srecode-template-inserter-point-override nil))
735 (funcall over dictionary))
736 (oset sti point (point-marker))
737 ))
738
739 (defclass srecode-template-inserter-subtemplate (srecode-template-inserter)
740 ()
741 "Wrap a section of a template under the control of a macro."
742 :abstract t)
743
744 (defmethod srecode-inserter-prin-example :STATIC ((ins srecode-template-inserter-subtemplate)
745 escape-start escape-end)
746 "Insert an example using inserter INS.
747 Arguments ESCAPE-START and ESCAPE-END are the current escape sequences in use."
748 (call-next-method)
749 (princ " Template Text to control")
750 (terpri)
751 (princ " ")
752 (princ escape-start)
753 (princ "/VARNAME")
754 (princ escape-end)
755 (terpri)
756 )
757
758 (defmethod srecode-insert-subtemplate ((sti srecode-template-inserter-subtemplate)
759 dict slot)
760 "Insert a subtemplate for the inserter STI with dictionary DICT."
761 ;; make sure that only dictionaries are used.
762 (when (not (srecode-dictionary-child-p dict))
763 (error "Only section dictionaries allowed for %s"
764 (object-name-string sti)))
765 ;; Output the code from the sub-template.
766 (srecode-insert-method (slot-value sti slot) dict)
767 )
768
769 (defmethod srecode-insert-method-helper ((sti srecode-template-inserter-subtemplate)
770 dictionary slot)
771 "Do the work for inserting the STI inserter.
772 Loops over the embedded CODE which was saved here during compilation.
773 The template to insert is stored in SLOT."
774 (let ((dicts (srecode-dictionary-lookup-name
775 dictionary (oref sti :object-name))))
776 (when (not (listp dicts))
777 (error "Cannot insert section %S from non-section variable."
778 (oref sti :object-name)))
779 ;; If there is no section dictionary, then don't output anything
780 ;; from this section.
781 (while dicts
782 (when (not (srecode-dictionary-p (car dicts)))
783 (error "Cannot insert section %S from non-section variable."
784 (oref sti :object-name)))
785 (srecode-insert-subtemplate sti (car dicts) slot)
786 (setq dicts (cdr dicts)))))
787
788 (defmethod srecode-insert-method ((sti srecode-template-inserter-subtemplate)
789 dictionary)
790 "Insert the STI inserter.
791 Calls back to `srecode-insert-method-helper' for this class."
792 (srecode-insert-method-helper sti dictionary 'template))
793
794
795 (defclass srecode-template-inserter-section-start (srecode-template-inserter-subtemplate)
796 ((key :initform ?#
797 :allocation :class
798 :documentation
799 "The character code used to identify inserters of this style.")
800 (template :initarg :template
801 :documentation
802 "A template used to frame the codes from this inserter.")
803 )
804 "Apply values from a sub-dictionary to a template section.
805 The dictionary saved at the named dictionary entry will be
806 applied to the text between the section start and the
807 `srecode-template-inserter-section-end' macro.")
808
809 (defmethod srecode-parse-input ((ins srecode-template-inserter-section-start)
810 tag input STATE)
811 "For the section inserter INS, parse INPUT.
812 Shorten input until the END token is found.
813 Return the remains of INPUT."
814 (let* ((out (srecode-compile-split-code tag input STATE
815 (oref ins :object-name))))
816 (oset ins template (srecode-template
817 (object-name-string ins)
818 :context nil
819 :args nil
820 :code (cdr out)))
821 (car out)))
822
823 (defmethod srecode-dump ((ins srecode-template-inserter-section-start) indent)
824 "Dump the state of the SRecode template inserter INS."
825 (call-next-method)
826 (princ "\n")
827 (srecode-dump-code-list (oref (oref ins template) code)
828 (concat indent " "))
829 )
830
831 (defclass srecode-template-inserter-section-end (srecode-template-inserter)
832 ((key :initform ?/
833 :allocation :class
834 :documentation
835 "The character code used to identify inserters of this style.")
836 )
837 "All template segments between the section-start and section-end
838 are treated specially.")
839
840 (defmethod srecode-insert-method ((sti srecode-template-inserter-section-end)
841 dictionary)
842 "Insert the STI inserter."
843 )
844
845 (defmethod srecode-match-end ((ins srecode-template-inserter-section-end) name)
846
847 "For the template inserter INS, do I end a section called NAME?"
848 (string= name (oref ins :object-name)))
849
850 (defclass srecode-template-inserter-include (srecode-template-inserter-subtemplate)
851 ((key :initform ?>
852 :allocation :class
853 :documentation
854 "The character code used to identify inserters of this style.")
855 (includedtemplate
856 :initarg :includedtemplate
857 :documentation
858 "The template included for this inserter."))
859 "Include a different template into this one.
860 The included template will have additional dictionary entries from the subdictionary
861 stored specified by this macro.")
862
863 (defmethod srecode-inserter-prin-example :STATIC ((ins srecode-template-inserter-include)
864 escape-start escape-end)
865 "Insert an example using inserter INS.
866 Arguments ESCAPE-START and ESCAPE-END are the current escape sequences in use."
867 (princ " ")
868 (princ escape-start)
869 (princ ">DICTNAME:contextname:templatename")
870 (princ escape-end)
871 (terpri)
872 )
873
874 (defmethod srecode-insert-include-lookup ((sti srecode-template-inserter-include)
875 dictionary)
876 "For the template inserter STI, lookup the template to include.
877 Finds the template with this macro function part and stores it in
878 this template instance."
879 (let* ((templatenamepart (oref sti :secondname))
880 )
881 ;; If there was no template name, throw an error
882 (if (not templatenamepart)
883 (error "Include macro %s needs a template name" (oref sti :object-name)))
884
885 ;; NOTE: We used to cache the template and not look it up a second time,
886 ;; but changes in the template tables can change which template is
887 ;; eventually discovered, so now we always lookup that template.
888
889 ;; Calculate and store the discovered template
890 (let ((tmpl (srecode-template-get-table (srecode-table)
891 templatenamepart))
892 (active (oref srecode-template active))
893 ctxt)
894 (when (not tmpl)
895 ;; If it isn't just available, scan back through
896 ;; the active template stack, searching for a matching
897 ;; context.
898 (while (and (not tmpl) active)
899 (setq ctxt (oref (car active) context))
900 (setq tmpl (srecode-template-get-table (srecode-table)
901 templatenamepart
902 ctxt))
903 (when (not tmpl)
904 (when (slot-boundp (car active) 'table)
905 (let ((app (oref (oref (car active) table) application)))
906 (when app
907 (setq tmpl (srecode-template-get-table
908 (srecode-table)
909 templatenamepart
910 ctxt app)))
911 )))
912 (setq active (cdr active)))
913 (when (not tmpl)
914 ;; If it wasn't in this context, look to see if it
915 ;; defines its own context
916 (setq tmpl (srecode-template-get-table (srecode-table)
917 templatenamepart)))
918 )
919
920 ;; Store the found template into this object for later use.
921 (oset sti :includedtemplate tmpl))
922
923 (if (not (oref sti includedtemplate))
924 ;; @todo - Call into a debugger to help find the template in question.
925 (error "No template \"%s\" found for include macro `%s'"
926 templatenamepart (oref sti :object-name)))
927 ))
928
929 (defmethod srecode-insert-method ((sti srecode-template-inserter-include)
930 dictionary)
931 "Insert the STI inserter.
932 Finds the template with this macro function part, and inserts it
933 with the dictionaries found in the dictionary."
934 (srecode-insert-include-lookup sti dictionary)
935 ;; Insert the template.
936 ;; Our baseclass has a simple way to do this.
937 (if (srecode-dictionary-lookup-name dictionary (oref sti :object-name))
938 ;; If we have a value, then call the next method
939 (srecode-insert-method-helper sti dictionary 'includedtemplate)
940 ;; If we don't have a special dictionary, then just insert with the
941 ;; current dictionary.
942 (srecode-insert-subtemplate sti dictionary 'includedtemplate))
943 )
944
945 ;;
946 ;; This template combines the include template and the sectional template.
947 ;; It will first insert the included template, then insert the embedded
948 ;; template wherever the $^$ in the included template was.
949 ;;
950 ;; Since it uses dual inheritance, it will magically get the end-matching
951 ;; behavior of #, with the including feature of >.
952 ;;
953 (defclass srecode-template-inserter-include-wrap (srecode-template-inserter-include srecode-template-inserter-section-start)
954 ((key :initform ?<
955 :allocation :class
956 :documentation
957 "The character code used to identify inserters of this style.")
958 )
959 "Include a different template into this one, and add text at the ^ macro.
960 The included template will have additional dictionary entries from the subdictionary
961 stored specified by this macro. If the included macro includes a ^ macro,
962 then the text between this macro and the end macro will be inserted at
963 the ^ macro.")
964
965 (defmethod srecode-inserter-prin-example :STATIC ((ins srecode-template-inserter-include-wrap)
966 escape-start escape-end)
967 "Insert an example using inserter INS.
968 Arguments ESCAPE-START and ESCAPE-END are the current escape sequences in use."
969 (princ " ")
970 (princ escape-start)
971 (princ "<DICTNAME:contextname:templatename")
972 (princ escape-end)
973 (terpri)
974 (princ " Template Text to insert at ^ macro")
975 (terpri)
976 (princ " ")
977 (princ escape-start)
978 (princ "/DICTNAME")
979 (princ escape-end)
980 (terpri)
981 )
982
983 (defmethod srecode-insert-method ((sti srecode-template-inserter-include-wrap)
984 dictionary)
985 "Insert the template STI.
986 This will first insert the include part via inheritance, then
987 insert the section it wraps into the location in the included
988 template where a ^ inserter occurs."
989 ;; Step 1: Look up the included inserter
990 (srecode-insert-include-lookup sti dictionary)
991 ;; Step 2: Temporarily override the point inserter.
992 ;; We bind `srecode-template-inserter-point-override' to a cons cell
993 ;; (DEPTH . FUNCTION) that has the maximum template nesting depth,
994 ;; for which the override is valid, in DEPTH and a lambda function
995 ;; which implements the wrap insertion behavior in FUNCTION. The
996 ;; maximum valid nesting depth is just the current depth + 1.
997 (let ((srecode-template-inserter-point-override
998 (lexical-let ((inserter1 sti))
999 (cons
1000 ;; DEPTH
1001 (+ (length (oref srecode-template active)) 1)
1002 ;; FUNCTION
1003 (lambda (dict)
1004 (let ((srecode-template-inserter-point-override nil))
1005 (if (srecode-dictionary-lookup-name
1006 dict (oref inserter1 :object-name))
1007 ;; Insert our sectional part with looping.
1008 (srecode-insert-method-helper
1009 inserter1 dict 'template)
1010 ;; Insert our sectional part just once.
1011 (srecode-insert-subtemplate
1012 inserter1 dict 'template))))))))
1013 ;; Do a regular insertion for an include, but with our override in
1014 ;; place.
1015 (call-next-method)))
1016
1017 (provide 'srecode/insert)
1018
1019 ;; Local variables:
1020 ;; generated-autoload-file: "loaddefs.el"
1021 ;; generated-autoload-load-name: "srecode/insert"
1022 ;; End:
1023
1024 ;;; srecode/insert.el ends here