insert.el 36 KB

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