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