ob-core.el 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176
  1. ;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2018 Free Software Foundation, Inc.
  3. ;; Authors: Eric Schulte
  4. ;; Dan Davison
  5. ;; Keywords: literate programming, reproducible research
  6. ;; Homepage: https://orgmode.org
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  18. ;;; Code:
  19. (require 'cl-lib)
  20. (require 'ob-eval)
  21. (require 'org-macs)
  22. (require 'org-compat)
  23. (defconst org-babel-exeext
  24. (if (memq system-type '(windows-nt cygwin))
  25. ".exe"
  26. nil))
  27. (defvar org-babel-library-of-babel)
  28. (defvar org-edit-src-content-indentation)
  29. (defvar org-link-file-path-type)
  30. (defvar org-src-lang-modes)
  31. (defvar org-src-preserve-indentation)
  32. (declare-function org-at-item-p "org-list" ())
  33. (declare-function org-at-table-p "org" (&optional table-type))
  34. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  35. (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
  36. (declare-function org-babel-ref-headline-body "ob-ref" ())
  37. (declare-function org-babel-ref-parse "ob-ref" (assignment))
  38. (declare-function org-babel-ref-resolve "ob-ref" (ref))
  39. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  40. (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
  41. (declare-function org-completing-read "org" (&rest args))
  42. (declare-function org-current-level "org" ())
  43. (declare-function org-cycle "org" (&optional arg))
  44. (declare-function org-do-remove-indentation "org" (&optional n))
  45. (declare-function org-edit-src-code "org-src" (&optional code edit-buffer-name))
  46. (declare-function org-edit-src-exit "org-src" ())
  47. (declare-function org-element-at-point "org-element" ())
  48. (declare-function org-element-context "org-element" (&optional element))
  49. (declare-function org-element-normalize-string "org-element" (s))
  50. (declare-function org-element-property "org-element" (property element))
  51. (declare-function org-element-type "org-element" (element))
  52. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  53. (declare-function org-escape-code-in-region "org-src" (beg end))
  54. (declare-function org-get-indentation "org" (&optional line))
  55. (declare-function org-get-indentation "org" (&optional line))
  56. (declare-function org-in-regexp "org" (regexp &optional nlines visually))
  57. (declare-function org-indent-line "org" ())
  58. (declare-function org-list-get-list-end "org-list" (item struct prevs))
  59. (declare-function org-list-prevs-alist "org-list" (struct))
  60. (declare-function org-list-struct "org-list" ())
  61. (declare-function org-list-to-generic "org-list" (LIST PARAMS))
  62. (declare-function org-list-to-lisp "org-list" (&optional delete))
  63. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  64. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  65. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  66. (declare-function org-narrow-to-subtree "org" ())
  67. (declare-function org-next-block "org" (arg &optional backward block-regexp))
  68. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  69. (declare-function org-previous-block "org" (arg &optional block-regexp))
  70. (declare-function org-remove-indentation "org" (code &optional n))
  71. (declare-function org-reverse-string "org" (string))
  72. (declare-function org-show-context "org" (&optional key))
  73. (declare-function org-src-coderef-format "org-src" (&optional element))
  74. (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
  75. (declare-function org-table-align "org-table" ())
  76. (declare-function org-table-end "org-table" (&optional table-type))
  77. (declare-function org-table-import "org-table" (file arg))
  78. (declare-function org-table-to-lisp "org-table" (&optional txt))
  79. (declare-function org-trim "org" (s &optional keep-lead))
  80. (declare-function org-unescape-code-in-string "org-src" (s))
  81. (declare-function org-uniquify "org" (list))
  82. (declare-function orgtbl-to-generic "org-table" (table params))
  83. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  84. (declare-function tramp-compat-make-temp-file "tramp-compat" (filename &optional dir-flag))
  85. (defgroup org-babel nil
  86. "Code block evaluation and management in `org-mode' documents."
  87. :tag "Babel"
  88. :group 'org)
  89. (defcustom org-confirm-babel-evaluate t
  90. "Confirm before evaluation.
  91. \\<org-mode-map>\
  92. Require confirmation before interactively evaluating code
  93. blocks in Org buffers. The default value of this variable is t,
  94. meaning confirmation is required for any code block evaluation.
  95. This variable can be set to nil to inhibit any future
  96. confirmation requests. This variable can also be set to a
  97. function which takes two arguments the language of the code block
  98. and the body of the code block. Such a function should then
  99. return a non-nil value if the user should be prompted for
  100. execution or nil if no prompt is required.
  101. Warning: Disabling confirmation may result in accidental
  102. evaluation of potentially harmful code. It may be advisable
  103. remove code block execution from `\\[org-ctrl-c-ctrl-c]' \
  104. as further protection
  105. against accidental code block evaluation. The
  106. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  107. remove code block execution from the `\\[org-ctrl-c-ctrl-c]' keybinding."
  108. :group 'org-babel
  109. :version "24.1"
  110. :type '(choice boolean function))
  111. ;; don't allow this variable to be changed through file settings
  112. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  113. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  114. "\\<org-mode-map>\
  115. Remove code block evaluation from the `\\[org-ctrl-c-ctrl-c]' key binding."
  116. :group 'org-babel
  117. :version "24.1"
  118. :type 'boolean)
  119. (defcustom org-babel-results-keyword "RESULTS"
  120. "Keyword used to name results generated by code blocks.
  121. It should be \"RESULTS\". However any capitalization may be
  122. used."
  123. :group 'org-babel
  124. :version "24.4"
  125. :package-version '(Org . "8.0")
  126. :type 'string
  127. :safe (lambda (v)
  128. (and (stringp v)
  129. (eq (compare-strings "RESULTS" nil nil v nil nil t)
  130. t))))
  131. (defcustom org-babel-noweb-wrap-start "<<"
  132. "String used to begin a noweb reference in a code block.
  133. See also `org-babel-noweb-wrap-end'."
  134. :group 'org-babel
  135. :type 'string)
  136. (defcustom org-babel-noweb-wrap-end ">>"
  137. "String used to end a noweb reference in a code block.
  138. See also `org-babel-noweb-wrap-start'."
  139. :group 'org-babel
  140. :type 'string)
  141. (defcustom org-babel-inline-result-wrap "=%s="
  142. "Format string used to wrap inline results.
  143. This string must include a \"%s\" which will be replaced by the results."
  144. :group 'org-babel
  145. :type 'string)
  146. (put 'org-babel-inline-result-wrap
  147. 'safe-local-variable
  148. (lambda (value)
  149. (and (stringp value)
  150. (string-match-p "%s" value))))
  151. (defcustom org-babel-hash-show-time nil
  152. "Non-nil means show the time the code block was evaluated in the result hash."
  153. :group 'org-babel
  154. :type 'boolean
  155. :version "26.1"
  156. :package-version '(Org . "9.0")
  157. :safe #'booleanp)
  158. (defcustom org-babel-uppercase-example-markers nil
  159. "When non-nil, begin/end example markers will be inserted in upper case."
  160. :group 'org-babel
  161. :type 'boolean
  162. :version "26.1"
  163. :package-version '(Org . "9.1")
  164. :safe #'booleanp)
  165. (defun org-babel-noweb-wrap (&optional regexp)
  166. (concat org-babel-noweb-wrap-start
  167. (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
  168. org-babel-noweb-wrap-end))
  169. (defvar org-babel-src-name-regexp
  170. "^[ \t]*#\\+name:[ \t]*"
  171. "Regular expression used to match a source name line.")
  172. (defvar org-babel-multi-line-header-regexp
  173. "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
  174. "Regular expression used to match multi-line header arguments.")
  175. (defvar org-babel-src-block-regexp
  176. (concat
  177. ;; (1) indentation (2) lang
  178. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  179. ;; (3) switches
  180. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  181. ;; (4) header arguments
  182. "\\([^\n]*\\)\n"
  183. ;; (5) body
  184. "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
  185. "Regexp used to identify code blocks.")
  186. (defun org-babel--get-vars (params)
  187. "Return the babel variable assignments in PARAMS.
  188. PARAMS is a quasi-alist of header args, which may contain
  189. multiple entries for the key `:var'. This function returns a
  190. list of the cdr of all the `:var' entries."
  191. (mapcar #'cdr
  192. (cl-remove-if-not (lambda (x) (eq (car x) :var)) params)))
  193. (defvar org-babel-exp-reference-buffer nil
  194. "Buffer containing original contents of the exported buffer.
  195. This is used by Babel to resolve references in source blocks.
  196. Its value is dynamically bound during export.")
  197. (defun org-babel-check-confirm-evaluate (info)
  198. "Check whether INFO allows code block evaluation.
  199. Returns nil if evaluation is disallowed, t if it is
  200. unconditionally allowed, and the symbol `query' if the user
  201. should be asked whether to allow evaluation."
  202. (let* ((headers (nth 2 info))
  203. (eval (or (cdr (assq :eval headers))
  204. (when (assq :noeval headers) "no")))
  205. (eval-no (member eval '("no" "never")))
  206. (export org-babel-exp-reference-buffer)
  207. (eval-no-export (and export (member eval '("no-export" "never-export"))))
  208. (noeval (or eval-no eval-no-export))
  209. (query (or (equal eval "query")
  210. (and export (equal eval "query-export"))
  211. (if (functionp org-confirm-babel-evaluate)
  212. (funcall org-confirm-babel-evaluate
  213. ;; Language, code block body.
  214. (nth 0 info) (nth 1 info))
  215. org-confirm-babel-evaluate))))
  216. (cond
  217. (noeval nil)
  218. (query 'query)
  219. (t t))))
  220. (defun org-babel-check-evaluate (info)
  221. "Check if code block INFO should be evaluated.
  222. Do not query the user, but do display an informative message if
  223. evaluation is blocked. Returns non-nil if evaluation is not blocked."
  224. (let ((confirmed (org-babel-check-confirm-evaluate info)))
  225. (unless confirmed
  226. (message "Evaluation of this %s code block%sis disabled."
  227. (nth 0 info)
  228. (let ((name (nth 4 info)))
  229. (if name (format " (%s) " name) " "))))
  230. confirmed))
  231. ;; Dynamically scoped for asynchronous export.
  232. (defvar org-babel-confirm-evaluate-answer-no)
  233. (defun org-babel-confirm-evaluate (info)
  234. "Confirm evaluation of the code block INFO.
  235. This query can also be suppressed by setting the value of
  236. `org-confirm-babel-evaluate' to nil, in which case all future
  237. interactive code block evaluations will proceed without any
  238. confirmation from the user.
  239. Note disabling confirmation may result in accidental evaluation
  240. of potentially harmful code.
  241. The variable `org-babel-confirm-evaluate-answer-no' is used by
  242. the async export process, which requires a non-interactive
  243. environment, to override this check."
  244. (let* ((evalp (org-babel-check-confirm-evaluate info))
  245. (lang (nth 0 info))
  246. (name (nth 4 info))
  247. (name-string (if name (format " (%s) " name) " ")))
  248. (pcase evalp
  249. (`nil nil)
  250. (`t t)
  251. (`query (or
  252. (and (not (bound-and-true-p
  253. org-babel-confirm-evaluate-answer-no))
  254. (yes-or-no-p
  255. (format "Evaluate this %s code block%son your system? "
  256. lang name-string)))
  257. (progn
  258. (message "Evaluation of this %s code block%sis aborted."
  259. lang name-string)
  260. nil)))
  261. (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x)))))
  262. ;;;###autoload
  263. (defun org-babel-execute-safely-maybe ()
  264. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  265. (org-babel-execute-maybe)))
  266. ;;;###autoload
  267. (defun org-babel-execute-maybe ()
  268. (interactive)
  269. (or (org-babel-execute-src-block-maybe)
  270. (org-babel-lob-execute-maybe)))
  271. (defmacro org-babel-when-in-src-block (&rest body)
  272. "Execute BODY if point is in a source block and return t.
  273. Otherwise do nothing and return nil."
  274. `(if (memq (org-element-type (org-element-context))
  275. '(inline-src-block src-block))
  276. (progn
  277. ,@body
  278. t)
  279. nil))
  280. (defun org-babel-execute-src-block-maybe ()
  281. "Conditionally execute a source block.
  282. Detect if this is context for a Babel src-block and if so
  283. then run `org-babel-execute-src-block'."
  284. (interactive)
  285. (org-babel-when-in-src-block
  286. (org-babel-eval-wipe-error-buffer)
  287. (org-babel-execute-src-block current-prefix-arg)))
  288. ;;;###autoload
  289. (defun org-babel-view-src-block-info ()
  290. "Display information on the current source block.
  291. This includes header arguments, language and name, and is largely
  292. a window into the `org-babel-get-src-block-info' function."
  293. (interactive)
  294. (let ((info (org-babel-get-src-block-info 'light))
  295. (full (lambda (it) (> (length it) 0)))
  296. (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
  297. (when info
  298. (with-help-window (help-buffer)
  299. (let ((name (nth 4 info))
  300. (lang (nth 0 info))
  301. (switches (nth 3 info))
  302. (header-args (nth 2 info)))
  303. (when name (funcall printf "Name: %s\n" name))
  304. (when lang (funcall printf "Lang: %s\n" lang))
  305. (funcall printf "Properties:\n")
  306. (funcall printf "\t:header-args \t%s\n" (org-entry-get (point) "header-args" t))
  307. (funcall printf "\t:header-args:%s \t%s\n" lang (org-entry-get (point) (concat "header-args:" lang) t))
  308. (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
  309. (funcall printf "Header Arguments:\n")
  310. (dolist (pair (sort header-args
  311. (lambda (a b) (string< (symbol-name (car a))
  312. (symbol-name (car b))))))
  313. (when (funcall full (format "%s" (cdr pair)))
  314. (funcall printf "\t%S%s\t%s\n"
  315. (car pair)
  316. (if (> (length (format "%S" (car pair))) 7) "" "\t")
  317. (cdr pair)))))))))
  318. ;;;###autoload
  319. (defun org-babel-expand-src-block-maybe ()
  320. "Conditionally expand a source block.
  321. Detect if this is context for an org-babel src-block and if so
  322. then run `org-babel-expand-src-block'."
  323. (interactive)
  324. (org-babel-when-in-src-block
  325. (org-babel-expand-src-block current-prefix-arg)))
  326. ;;;###autoload
  327. (defun org-babel-load-in-session-maybe ()
  328. "Conditionally load a source block in a session.
  329. Detect if this is context for an org-babel src-block and if so
  330. then run `org-babel-load-in-session'."
  331. (interactive)
  332. (org-babel-when-in-src-block
  333. (org-babel-load-in-session current-prefix-arg)))
  334. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  335. ;;;###autoload
  336. (defun org-babel-pop-to-session-maybe ()
  337. "Conditionally pop to a session.
  338. Detect if this is context for an org-babel src-block and if so
  339. then run `org-babel-switch-to-session'."
  340. (interactive)
  341. (org-babel-when-in-src-block
  342. (org-babel-switch-to-session current-prefix-arg)))
  343. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  344. (defconst org-babel-common-header-args-w-values
  345. '((cache . ((no yes)))
  346. (cmdline . :any)
  347. (colnames . ((nil no yes)))
  348. (comments . ((no link yes org both noweb)))
  349. (dir . :any)
  350. (eval . ((yes no no-export strip-export never-export eval never
  351. query)))
  352. (exports . ((code results both none)))
  353. (epilogue . :any)
  354. (file . :any)
  355. (file-desc . :any)
  356. (file-ext . :any)
  357. (hlines . ((no yes)))
  358. (mkdirp . ((yes no)))
  359. (no-expand)
  360. (noeval)
  361. (noweb . ((yes no tangle no-export strip-export)))
  362. (noweb-ref . :any)
  363. (noweb-sep . :any)
  364. (output-dir . :any)
  365. (padline . ((yes no)))
  366. (post . :any)
  367. (prologue . :any)
  368. (results . ((file list vector table scalar verbatim)
  369. (raw html latex org code pp drawer link graphics)
  370. (replace silent none append prepend)
  371. (output value)))
  372. (rownames . ((no yes)))
  373. (sep . :any)
  374. (session . :any)
  375. (shebang . :any)
  376. (tangle . ((tangle yes no :any)))
  377. (tangle-mode . ((#o755 #o555 #o444 :any)))
  378. (var . :any)
  379. (wrap . :any)))
  380. (defconst org-babel-header-arg-names
  381. (mapcar #'car org-babel-common-header-args-w-values)
  382. "Common header arguments used by org-babel.
  383. Note that individual languages may define their own language
  384. specific header arguments as well.")
  385. (defconst org-babel-safe-header-args
  386. '(:cache :colnames :comments :exports :epilogue :hlines :noeval
  387. :noweb :noweb-ref :noweb-sep :padline :prologue :rownames
  388. :sep :session :tangle :wrap
  389. (:eval . ("never" "query"))
  390. (:results . (lambda (str) (not (string-match "file" str)))))
  391. "A list of safe header arguments for babel source blocks.
  392. The list can have entries of the following forms:
  393. - :ARG -> :ARG is always a safe header arg
  394. - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
  395. `equal' to one of the VALs.
  396. - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
  397. returns non-nil. FN is passed one
  398. argument, the value of the header arg
  399. (as a string).")
  400. (defmacro org-babel-header-args-safe-fn (safe-list)
  401. "Return a function that determines whether a list of header args are safe.
  402. Intended usage is:
  403. \(put \\='org-babel-default-header-args \\='safe-local-variable
  404. (org-babel-header-args-safe-p org-babel-safe-header-args)
  405. This allows org-babel languages to extend the list of safe values for
  406. their `org-babel-default-header-args:foo' variable.
  407. For the format of SAFE-LIST, see `org-babel-safe-header-args'."
  408. `(lambda (value)
  409. (and (listp value)
  410. (cl-every
  411. (lambda (pair)
  412. (and (consp pair)
  413. (org-babel-one-header-arg-safe-p pair ,safe-list)))
  414. value))))
  415. (defvar org-babel-default-header-args
  416. '((:session . "none") (:results . "replace") (:exports . "code")
  417. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
  418. "Default arguments to use when evaluating a source block.")
  419. (put 'org-babel-default-header-args 'safe-local-variable
  420. (org-babel-header-args-safe-fn org-babel-safe-header-args))
  421. (defvar org-babel-default-inline-header-args
  422. '((:session . "none") (:results . "replace")
  423. (:exports . "results") (:hlines . "yes"))
  424. "Default arguments to use when evaluating an inline source block.")
  425. (put 'org-babel-default-inline-header-args 'safe-local-variable
  426. (org-babel-header-args-safe-fn org-babel-safe-header-args))
  427. (defconst org-babel-name-regexp
  428. (format "^[ \t]*#\\+%s:[ \t]*"
  429. ;; FIXME: TBLNAME is for backward compatibility.
  430. (regexp-opt '("NAME" "TBLNAME")))
  431. "Regexp matching a NAME keyword.")
  432. (defconst org-babel-result-regexp
  433. (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%s \\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*"
  434. org-babel-results-keyword
  435. ;; <%Y-%m-%d %H:%M:%S>
  436. "<\\(?:[0-9]\\{4\\}-[0-1][0-9]-[0-3][0-9] \
  437. [0-2][0-9]\\(?::[0-5][0-9]\\)\\{2\\}\\)>")
  438. "Regular expression used to match result lines.
  439. If the results are associated with a hash key then the hash will
  440. be saved in match group 1.")
  441. (defconst org-babel-result-w-name-regexp
  442. (concat org-babel-result-regexp "\\(?9:[^ \t\n\r\v\f]+\\)")
  443. "Regexp matching a RESULTS keyword with a name.
  444. Name is saved in match group 9.")
  445. (defvar org-babel-min-lines-for-block-output 10
  446. "The minimum number of lines for block output.
  447. If number of lines of output is equal to or exceeds this
  448. value, the output is placed in a #+begin_example...#+end_example
  449. block. Otherwise the output is marked as literal by inserting
  450. colons at the starts of the lines. This variable only takes
  451. effect if the :results output option is in effect.")
  452. (defvar org-babel-noweb-error-all-langs nil
  453. "Raise errors when noweb references don't resolve.
  454. Also see `org-babel-noweb-error-langs' to control noweb errors on
  455. a language by language bases.")
  456. (defvar org-babel-noweb-error-langs nil
  457. "Languages for which Babel will raise literate programming errors.
  458. List of languages for which errors should be raised when the
  459. source code block satisfying a noweb reference in this language
  460. can not be resolved. Also see `org-babel-noweb-error-all-langs'
  461. to raise errors for all languages.")
  462. (defvar org-babel-hash-show 4
  463. "Number of initial characters to show of a hidden results hash.")
  464. (defvar org-babel-after-execute-hook nil
  465. "Hook for functions to be called after `org-babel-execute-src-block'")
  466. (defun org-babel-named-src-block-regexp-for-name (&optional name)
  467. "This generates a regexp used to match a src block named NAME.
  468. If NAME is nil, match any name. Matched name is then put in
  469. match group 9. Other match groups are defined in
  470. `org-babel-src-block-regexp'."
  471. (concat org-babel-src-name-regexp
  472. (concat (if name (regexp-quote name) "\\(?9:.*?\\)") "[ \t]*" )
  473. "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
  474. "\n"
  475. (substring org-babel-src-block-regexp 1)))
  476. (defun org-babel-named-data-regexp-for-name (name)
  477. "This generates a regexp used to match data named NAME."
  478. (concat org-babel-name-regexp (regexp-quote name) "[ \t]*$"))
  479. (defun org-babel--normalize-body (datum)
  480. "Normalize body for element or object DATUM.
  481. DATUM is a source block element or an inline source block object.
  482. Remove final newline character and spurious indentation."
  483. (let* ((value (org-element-property :value datum))
  484. (body (if (string-suffix-p "\n" value)
  485. (substring value 0 -1)
  486. value)))
  487. (cond ((eq (org-element-type datum) 'inline-src-block)
  488. ;; Newline characters and indentation in an inline
  489. ;; src-block are not meaningful, since they could come from
  490. ;; some paragraph filling. Treat them as a white space.
  491. (replace-regexp-in-string "\n[ \t]*" " " body))
  492. ((or org-src-preserve-indentation
  493. (org-element-property :preserve-indent datum))
  494. body)
  495. (t (org-remove-indentation body)))))
  496. ;;; functions
  497. (defvar org-babel-current-src-block-location nil
  498. "Marker pointing to the src block currently being executed.
  499. This may also point to a call line or an inline code block. If
  500. multiple blocks are being executed (e.g., in chained execution
  501. through use of the :var header argument) this marker points to
  502. the outer-most code block.")
  503. (defvar *this*)
  504. (defun org-babel-get-src-block-info (&optional light datum)
  505. "Extract information from a source block or inline source block.
  506. When optional argument LIGHT is non-nil, Babel does not resolve
  507. remote variable references; a process which could likely result
  508. in the execution of other code blocks, and do not evaluate Lisp
  509. values in parameters.
  510. By default, consider the block at point. However, when optional
  511. argument DATUM is provided, extract information from that parsed
  512. object instead.
  513. Return nil if point is not on a source block. Otherwise, return
  514. a list with the following pattern:
  515. (language body arguments switches name start coderef)"
  516. (let* ((datum (or datum (org-element-context)))
  517. (type (org-element-type datum))
  518. (inline (eq type 'inline-src-block)))
  519. (when (memq type '(inline-src-block src-block))
  520. (let* ((lang (org-element-property :language datum))
  521. (lang-headers (intern
  522. (concat "org-babel-default-header-args:" lang)))
  523. (name (org-element-property :name datum))
  524. (info
  525. (list
  526. lang
  527. (org-babel--normalize-body datum)
  528. (apply #'org-babel-merge-params
  529. (if inline org-babel-default-inline-header-args
  530. org-babel-default-header-args)
  531. (and (boundp lang-headers) (eval lang-headers t))
  532. (append
  533. ;; If DATUM is provided, make sure we get node
  534. ;; properties applicable to its location within
  535. ;; the document.
  536. (org-with-point-at (org-element-property :begin datum)
  537. (org-babel-params-from-properties lang light))
  538. (mapcar (lambda (h)
  539. (org-babel-parse-header-arguments h light))
  540. (cons (org-element-property :parameters datum)
  541. (org-element-property :header datum)))))
  542. (or (org-element-property :switches datum) "")
  543. name
  544. (org-element-property (if inline :begin :post-affiliated)
  545. datum)
  546. (and (not inline) (org-src-coderef-format datum)))))
  547. (unless light
  548. (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
  549. (setf (nth 2 info) (org-babel-generate-file-param name (nth 2 info)))
  550. info))))
  551. ;;;###autoload
  552. (defun org-babel-execute-src-block (&optional arg info params)
  553. "Execute the current source code block.
  554. Insert the results of execution into the buffer. Source code
  555. execution and the collection and formatting of results can be
  556. controlled through a variety of header arguments.
  557. With prefix argument ARG, force re-execution even if an existing
  558. result cached in the buffer would otherwise have been returned.
  559. Optionally supply a value for INFO in the form returned by
  560. `org-babel-get-src-block-info'.
  561. Optionally supply a value for PARAMS which will be merged with
  562. the header arguments specified at the front of the source code
  563. block."
  564. (interactive)
  565. (let* ((org-babel-current-src-block-location
  566. (or org-babel-current-src-block-location
  567. (nth 5 info)
  568. (org-babel-where-is-src-block-head)))
  569. (info (if info (copy-tree info) (org-babel-get-src-block-info))))
  570. ;; Merge PARAMS with INFO before considering source block
  571. ;; evaluation since both could disagree.
  572. (cl-callf org-babel-merge-params (nth 2 info) params)
  573. (when (org-babel-check-evaluate info)
  574. (cl-callf org-babel-process-params (nth 2 info))
  575. (let* ((params (nth 2 info))
  576. (cache (let ((c (cdr (assq :cache params))))
  577. (and (not arg) c (string= "yes" c))))
  578. (new-hash (and cache (org-babel-sha1-hash info)))
  579. (old-hash (and cache (org-babel-current-result-hash)))
  580. (current-cache (and new-hash (equal new-hash old-hash))))
  581. (cond
  582. (current-cache
  583. (save-excursion ;Return cached result.
  584. (goto-char (org-babel-where-is-src-block-result nil info))
  585. (forward-line)
  586. (skip-chars-forward " \t")
  587. (let ((result (org-babel-read-result)))
  588. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  589. result)))
  590. ((org-babel-confirm-evaluate info)
  591. (let* ((lang (nth 0 info))
  592. (result-params (cdr (assq :result-params params)))
  593. ;; Expand noweb references in BODY and remove any
  594. ;; coderef.
  595. (body
  596. (let ((coderef (nth 6 info))
  597. (expand
  598. (if (org-babel-noweb-p params :eval)
  599. (org-babel-expand-noweb-references info)
  600. (nth 1 info))))
  601. (if (not coderef) expand
  602. (replace-regexp-in-string
  603. (org-src-coderef-regexp coderef) "" expand nil nil 1))))
  604. (dir (cdr (assq :dir params)))
  605. (default-directory
  606. (or (and dir (file-name-as-directory (expand-file-name dir)))
  607. default-directory))
  608. (cmd (intern (concat "org-babel-execute:" lang)))
  609. result)
  610. (unless (fboundp cmd)
  611. (error "No org-babel-execute function for %s!" lang))
  612. (message "executing %s code block%s..."
  613. (capitalize lang)
  614. (let ((name (nth 4 info)))
  615. (if name (format " (%s)" name) "")))
  616. (if (member "none" result-params)
  617. (progn (funcall cmd body params)
  618. (message "result silenced"))
  619. (setq result
  620. (let ((r (funcall cmd body params)))
  621. (if (and (eq (cdr (assq :result-type params)) 'value)
  622. (or (member "vector" result-params)
  623. (member "table" result-params))
  624. (not (listp r)))
  625. (list (list r))
  626. r)))
  627. (let ((file (cdr (assq :file params))))
  628. ;; If non-empty result and :file then write to :file.
  629. (when file
  630. ;; If `:results' are special types like `link' or
  631. ;; `graphics', don't write result to `:file'. Only
  632. ;; insert a link to `:file'.
  633. (when (and result
  634. (not (or (member "link" result-params)
  635. (member "graphics" result-params))))
  636. (with-temp-file file
  637. (insert (org-babel-format-result
  638. result
  639. (cdr (assq :sep params))))))
  640. (setq result file))
  641. ;; Possibly perform post process provided its
  642. ;; appropriate. Dynamically bind "*this*" to the
  643. ;; actual results of the block.
  644. (let ((post (cdr (assq :post params))))
  645. (when post
  646. (let ((*this* (if (not file) result
  647. (org-babel-result-to-file
  648. file
  649. (let ((desc (assq :file-desc params)))
  650. (and desc (or (cdr desc) result)))))))
  651. (setq result (org-babel-ref-resolve post))
  652. (when file
  653. (setq result-params (remove "file" result-params))))))
  654. (org-babel-insert-result
  655. result result-params info new-hash lang)))
  656. (run-hooks 'org-babel-after-execute-hook)
  657. result)))))))
  658. (defun org-babel-expand-body:generic (body params &optional var-lines)
  659. "Expand BODY with PARAMS.
  660. Expand a block of code with org-babel according to its header
  661. arguments. This generic implementation of body expansion is
  662. called for languages which have not defined their own specific
  663. org-babel-expand-body:lang function."
  664. (let ((pro (cdr (assq :prologue params)))
  665. (epi (cdr (assq :epilogue params))))
  666. (mapconcat #'identity
  667. (append (when pro (list pro))
  668. var-lines
  669. (list body)
  670. (when epi (list epi)))
  671. "\n")))
  672. ;;;###autoload
  673. (defun org-babel-expand-src-block (&optional _arg info params)
  674. "Expand the current source code block.
  675. Expand according to the source code block's header
  676. arguments and pop open the results in a preview buffer."
  677. (interactive)
  678. (let* ((info (or info (org-babel-get-src-block-info)))
  679. (lang (nth 0 info))
  680. (params (setf (nth 2 info)
  681. (sort (org-babel-merge-params (nth 2 info) params)
  682. (lambda (el1 el2) (string< (symbol-name (car el1))
  683. (symbol-name (car el2)))))))
  684. (body (setf (nth 1 info)
  685. (if (org-babel-noweb-p params :eval)
  686. (org-babel-expand-noweb-references info) (nth 1 info))))
  687. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  688. (assignments-cmd (intern (concat "org-babel-variable-assignments:"
  689. lang)))
  690. (expanded
  691. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  692. (org-babel-expand-body:generic
  693. body params (and (fboundp assignments-cmd)
  694. (funcall assignments-cmd params))))))
  695. (if (called-interactively-p 'any)
  696. (org-edit-src-code
  697. expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
  698. expanded)))
  699. (defun org-babel-edit-distance (s1 s2)
  700. "Return the edit (levenshtein) distance between strings S1 S2."
  701. (let* ((l1 (length s1))
  702. (l2 (length s2))
  703. (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
  704. (number-sequence 1 (1+ l1)))))
  705. (in (lambda (i j) (aref (aref dist i) j))))
  706. (setf (aref (aref dist 0) 0) 0)
  707. (dolist (j (number-sequence 1 l2))
  708. (setf (aref (aref dist 0) j) j))
  709. (dolist (i (number-sequence 1 l1))
  710. (setf (aref (aref dist i) 0) i)
  711. (dolist (j (number-sequence 1 l2))
  712. (setf (aref (aref dist i) j)
  713. (min
  714. (1+ (funcall in (1- i) j))
  715. (1+ (funcall in i (1- j)))
  716. (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
  717. (funcall in (1- i) (1- j)))))))
  718. (funcall in l1 l2)))
  719. (defun org-babel-combine-header-arg-lists (original &rest others)
  720. "Combine a number of lists of header argument names and arguments."
  721. (let ((results (copy-sequence original)))
  722. (dolist (new-list others)
  723. (dolist (arg-pair new-list)
  724. (let ((header (car arg-pair)))
  725. (setq results
  726. (cons arg-pair (cl-remove-if
  727. (lambda (pair) (equal header (car pair)))
  728. results))))))
  729. results))
  730. ;;;###autoload
  731. (defun org-babel-check-src-block ()
  732. "Check for misspelled header arguments in the current code block."
  733. (interactive)
  734. ;; TODO: report malformed code block
  735. ;; TODO: report incompatible combinations of header arguments
  736. ;; TODO: report uninitialized variables
  737. (let ((too-close 2) ;; <- control closeness to report potential match
  738. (names (mapcar #'symbol-name org-babel-header-arg-names)))
  739. (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
  740. (and (org-babel-where-is-src-block-head)
  741. (org-babel-parse-header-arguments
  742. (org-no-properties
  743. (match-string 4))))))
  744. (dolist (name names)
  745. (when (and (not (string= header name))
  746. (<= (org-babel-edit-distance header name) too-close)
  747. (not (member header names)))
  748. (error "Supplied header \"%S\" is suspiciously close to \"%S\""
  749. header name))))
  750. (message "No suspicious header arguments found.")))
  751. ;;;###autoload
  752. (defun org-babel-insert-header-arg (&optional header-arg value)
  753. "Insert a header argument selecting from lists of common args and values."
  754. (interactive)
  755. (let* ((info (org-babel-get-src-block-info 'light))
  756. (lang (car info))
  757. (begin (nth 5 info))
  758. (lang-headers (intern (concat "org-babel-header-args:" lang)))
  759. (headers (org-babel-combine-header-arg-lists
  760. org-babel-common-header-args-w-values
  761. (when (boundp lang-headers) (eval lang-headers t))))
  762. (header-arg (or header-arg
  763. (completing-read
  764. "Header Arg: "
  765. (mapcar
  766. (lambda (header-spec) (symbol-name (car header-spec)))
  767. headers))))
  768. (vals (cdr (assoc (intern header-arg) headers)))
  769. (value (or value
  770. (cond
  771. ((eq vals :any)
  772. (read-from-minibuffer "value: "))
  773. ((listp vals)
  774. (mapconcat
  775. (lambda (group)
  776. (let ((arg (completing-read
  777. "Value: "
  778. (cons "default"
  779. (mapcar #'symbol-name group)))))
  780. (if (and arg (not (string= "default" arg)))
  781. (concat arg " ")
  782. "")))
  783. vals ""))))))
  784. (save-excursion
  785. (goto-char begin)
  786. (goto-char (point-at-eol))
  787. (unless (= (char-before (point)) ?\ ) (insert " "))
  788. (insert ":" header-arg) (when value (insert " " value)))))
  789. ;; Add support for completing-read insertion of header arguments after ":"
  790. (defun org-babel-header-arg-expand ()
  791. "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
  792. (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
  793. (org-babel-enter-header-arg-w-completion (match-string 2))))
  794. (defun org-babel-enter-header-arg-w-completion (&optional lang)
  795. "Insert header argument appropriate for LANG with completion."
  796. (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
  797. (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var t)))
  798. (headers-w-values (org-babel-combine-header-arg-lists
  799. org-babel-common-header-args-w-values lang-headers))
  800. (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
  801. (header (org-completing-read "Header Arg: " headers))
  802. (args (cdr (assoc (intern header) headers-w-values)))
  803. (arg (when (and args (listp args))
  804. (org-completing-read
  805. (format "%s: " header)
  806. (mapcar #'symbol-name (apply #'append args))))))
  807. (insert (concat header " " (or arg "")))
  808. (cons header arg)))
  809. (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
  810. ;;;###autoload
  811. (defun org-babel-load-in-session (&optional _arg info)
  812. "Load the body of the current source-code block.
  813. Evaluate the header arguments for the source block before
  814. entering the session. After loading the body this pops open the
  815. session."
  816. (interactive)
  817. (let* ((info (or info (org-babel-get-src-block-info)))
  818. (lang (nth 0 info))
  819. (params (nth 2 info))
  820. (body (if (not info)
  821. (user-error "No src code block at point")
  822. (setf (nth 1 info)
  823. (if (org-babel-noweb-p params :eval)
  824. (org-babel-expand-noweb-references info)
  825. (nth 1 info)))))
  826. (session (cdr (assq :session params)))
  827. (dir (cdr (assq :dir params)))
  828. (default-directory
  829. (or (and dir (file-name-as-directory dir)) default-directory))
  830. (cmd (intern (concat "org-babel-load-session:" lang))))
  831. (unless (fboundp cmd)
  832. (error "No org-babel-load-session function for %s!" lang))
  833. (pop-to-buffer (funcall cmd session body params))
  834. (end-of-line 1)))
  835. ;;;###autoload
  836. (defun org-babel-initiate-session (&optional arg info)
  837. "Initiate session for current code block.
  838. If called with a prefix argument then resolve any variable
  839. references in the header arguments and assign these variables in
  840. the session. Copy the body of the code block to the kill ring."
  841. (interactive "P")
  842. (let* ((info (or info (org-babel-get-src-block-info (not arg))))
  843. (lang (nth 0 info))
  844. (body (nth 1 info))
  845. (params (nth 2 info))
  846. (session (cdr (assq :session params)))
  847. (dir (cdr (assq :dir params)))
  848. (default-directory
  849. (or (and dir (file-name-as-directory dir)) default-directory))
  850. (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
  851. (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
  852. (when (and (stringp session) (string= session "none"))
  853. (error "This block is not using a session!"))
  854. (unless (fboundp init-cmd)
  855. (error "No org-babel-initiate-session function for %s!" lang))
  856. (with-temp-buffer (insert (org-trim body))
  857. (copy-region-as-kill (point-min) (point-max)))
  858. (when arg
  859. (unless (fboundp prep-cmd)
  860. (error "No org-babel-prep-session function for %s!" lang))
  861. (funcall prep-cmd session params))
  862. (funcall init-cmd session params)))
  863. ;;;###autoload
  864. (defun org-babel-switch-to-session (&optional arg info)
  865. "Switch to the session of the current code block.
  866. Uses `org-babel-initiate-session' to start the session. If called
  867. with a prefix argument then this is passed on to
  868. `org-babel-initiate-session'."
  869. (interactive "P")
  870. (pop-to-buffer (org-babel-initiate-session arg info))
  871. (end-of-line 1))
  872. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  873. (defvar org-src-window-setup)
  874. ;;;###autoload
  875. (defun org-babel-switch-to-session-with-code (&optional arg _info)
  876. "Switch to code buffer and display session."
  877. (interactive "P")
  878. (let ((swap-windows
  879. (lambda ()
  880. (let ((other-window-buffer (window-buffer (next-window))))
  881. (set-window-buffer (next-window) (current-buffer))
  882. (set-window-buffer (selected-window) other-window-buffer))
  883. (other-window 1)))
  884. (info (org-babel-get-src-block-info))
  885. (org-src-window-setup 'reorganize-frame))
  886. (save-excursion
  887. (org-babel-switch-to-session arg info))
  888. (org-edit-src-code)
  889. (funcall swap-windows)))
  890. ;;;###autoload
  891. (defmacro org-babel-do-in-edit-buffer (&rest body)
  892. "Evaluate BODY in edit buffer if there is a code block at point.
  893. Return t if a code block was found at point, nil otherwise."
  894. (declare (debug (body)))
  895. `(let* ((element (org-element-at-point))
  896. ;; This function is not supposed to move point. However,
  897. ;; `org-edit-src-code' always moves point back into the
  898. ;; source block. It is problematic if the point was before
  899. ;; the code, e.g., on block's opening line. In this case,
  900. ;; we want to restore this location after executing BODY.
  901. (outside-position
  902. (and (<= (line-beginning-position)
  903. (org-element-property :post-affiliated element))
  904. (point-marker)))
  905. (org-src-window-setup 'switch-invisibly))
  906. (when (and (org-babel-where-is-src-block-head element)
  907. (org-edit-src-code))
  908. (unwind-protect (progn ,@body)
  909. (org-edit-src-exit)
  910. (when outside-position (goto-char outside-position)))
  911. t)))
  912. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  913. "Read key sequence and execute the command in edit buffer.
  914. Enter a key sequence to be executed in the language major-mode
  915. edit buffer. For example, TAB will alter the contents of the
  916. Org code block according to the effect of TAB in the language
  917. major mode buffer. For languages that support interactive
  918. sessions, this can be used to send code from the Org buffer
  919. to the session for evaluation using the native major mode
  920. evaluation mechanisms."
  921. (interactive "kEnter key-sequence to execute in edit buffer: ")
  922. (org-babel-do-in-edit-buffer
  923. (call-interactively
  924. (key-binding (or key (read-key-sequence nil))))))
  925. (defvar org-bracket-link-regexp)
  926. (defun org-babel-active-location-p ()
  927. (memq (org-element-type (save-match-data (org-element-context)))
  928. '(babel-call inline-babel-call inline-src-block src-block)))
  929. ;;;###autoload
  930. (defun org-babel-open-src-block-result (&optional re-run)
  931. "If `point' is on a src block then open the results of the
  932. source code block, otherwise return nil. With optional prefix
  933. argument RE-RUN the source-code block is evaluated even if
  934. results already exist."
  935. (interactive "P")
  936. (let ((info (org-babel-get-src-block-info 'light)))
  937. (when info
  938. (save-excursion
  939. ;; go to the results, if there aren't any then run the block
  940. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  941. (progn (org-babel-execute-src-block)
  942. (org-babel-where-is-src-block-result))))
  943. (end-of-line 1)
  944. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  945. ;; open the results
  946. (if (looking-at org-bracket-link-regexp)
  947. ;; file results
  948. (org-open-at-point)
  949. (let ((r (org-babel-format-result
  950. (org-babel-read-result) (cdr (assq :sep (nth 2 info))))))
  951. (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
  952. (delete-region (point-min) (point-max))
  953. (insert r)))
  954. t))))
  955. ;;;###autoload
  956. (defmacro org-babel-map-src-blocks (file &rest body)
  957. "Evaluate BODY forms on each source-block in FILE.
  958. If FILE is nil evaluate BODY forms on source blocks in current
  959. buffer. During evaluation of BODY the following local variables
  960. are set relative to the currently matched code block.
  961. full-block ------- string holding the entirety of the code block
  962. beg-block -------- point at the beginning of the code block
  963. end-block -------- point at the end of the matched code block
  964. lang ------------- string holding the language of the code block
  965. beg-lang --------- point at the beginning of the lang
  966. end-lang --------- point at the end of the lang
  967. switches --------- string holding the switches
  968. beg-switches ----- point at the beginning of the switches
  969. end-switches ----- point at the end of the switches
  970. header-args ------ string holding the header-args
  971. beg-header-args -- point at the beginning of the header-args
  972. end-header-args -- point at the end of the header-args
  973. body ------------- string holding the body of the code block
  974. beg-body --------- point at the beginning of the body
  975. end-body --------- point at the end of the body"
  976. (declare (indent 1))
  977. (let ((tempvar (make-symbol "file")))
  978. `(let* ((case-fold-search t)
  979. (,tempvar ,file)
  980. (visited-p (or (null ,tempvar)
  981. (get-file-buffer (expand-file-name ,tempvar))))
  982. (point (point)) to-be-removed)
  983. (save-window-excursion
  984. (when ,tempvar (find-file ,tempvar))
  985. (setq to-be-removed (current-buffer))
  986. (goto-char (point-min))
  987. (while (re-search-forward org-babel-src-block-regexp nil t)
  988. (when (org-babel-active-location-p)
  989. (goto-char (match-beginning 0))
  990. (let ((full-block (match-string 0))
  991. (beg-block (match-beginning 0))
  992. (end-block (match-end 0))
  993. (lang (match-string 2))
  994. (beg-lang (match-beginning 2))
  995. (end-lang (match-end 2))
  996. (switches (match-string 3))
  997. (beg-switches (match-beginning 3))
  998. (end-switches (match-end 3))
  999. (header-args (match-string 4))
  1000. (beg-header-args (match-beginning 4))
  1001. (end-header-args (match-end 4))
  1002. (body (match-string 5))
  1003. (beg-body (match-beginning 5))
  1004. (end-body (match-end 5)))
  1005. ;; Silence byte-compiler in case `body' doesn't use all
  1006. ;; those variables.
  1007. (ignore full-block beg-block end-block lang
  1008. beg-lang end-lang switches beg-switches
  1009. end-switches header-args beg-header-args
  1010. end-header-args body beg-body end-body)
  1011. ,@body
  1012. (goto-char end-block)))))
  1013. (unless visited-p (kill-buffer to-be-removed))
  1014. (goto-char point))))
  1015. (def-edebug-spec org-babel-map-src-blocks (form body))
  1016. ;;;###autoload
  1017. (defmacro org-babel-map-inline-src-blocks (file &rest body)
  1018. "Evaluate BODY forms on each inline source block in FILE.
  1019. If FILE is nil evaluate BODY forms on source blocks in current
  1020. buffer."
  1021. (declare (indent 1) (debug (form body)))
  1022. (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
  1023. `(let* ((case-fold-search t)
  1024. (,tempvar ,file)
  1025. (,visitedp (or (null ,tempvar)
  1026. (get-file-buffer (expand-file-name ,tempvar))))
  1027. (,point (point))
  1028. ,to-be-removed)
  1029. (save-window-excursion
  1030. (when ,tempvar (find-file ,tempvar))
  1031. (setq ,to-be-removed (current-buffer))
  1032. (goto-char (point-min))
  1033. (while (re-search-forward "src_\\S-" nil t)
  1034. (let ((,datum (save-match-data (org-element-context))))
  1035. (when (eq (org-element-type ,datum) 'inline-src-block)
  1036. (goto-char (match-beginning 0))
  1037. (let ((,end (copy-marker (org-element-property :end ,datum))))
  1038. ,@body
  1039. (goto-char ,end)
  1040. (set-marker ,end nil))))))
  1041. (unless ,visitedp (kill-buffer ,to-be-removed))
  1042. (goto-char ,point))))
  1043. ;;;###autoload
  1044. (defmacro org-babel-map-call-lines (file &rest body)
  1045. "Evaluate BODY forms on each call line in FILE.
  1046. If FILE is nil evaluate BODY forms on source blocks in current
  1047. buffer."
  1048. (declare (indent 1) (debug (form body)))
  1049. (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
  1050. `(let* ((case-fold-search t)
  1051. (,tempvar ,file)
  1052. (,visitedp (or (null ,tempvar)
  1053. (get-file-buffer (expand-file-name ,tempvar))))
  1054. (,point (point))
  1055. ,to-be-removed)
  1056. (save-window-excursion
  1057. (when ,tempvar (find-file ,tempvar))
  1058. (setq ,to-be-removed (current-buffer))
  1059. (goto-char (point-min))
  1060. (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t)
  1061. (let ((,datum (save-match-data (org-element-context))))
  1062. (when (memq (org-element-type ,datum)
  1063. '(babel-call inline-babel-call))
  1064. (goto-char (match-beginning 0))
  1065. (let ((,end (copy-marker (org-element-property :end ,datum))))
  1066. ,@body
  1067. (goto-char ,end)
  1068. (set-marker ,end nil))))))
  1069. (unless ,visitedp (kill-buffer ,to-be-removed))
  1070. (goto-char ,point))))
  1071. ;;;###autoload
  1072. (defmacro org-babel-map-executables (file &rest body)
  1073. "Evaluate BODY forms on each active Babel code in FILE.
  1074. If FILE is nil evaluate BODY forms on source blocks in current
  1075. buffer."
  1076. (declare (indent 1) (debug (form body)))
  1077. (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
  1078. `(let* ((case-fold-search t)
  1079. (,tempvar ,file)
  1080. (,visitedp (or (null ,tempvar)
  1081. (get-file-buffer (expand-file-name ,tempvar))))
  1082. (,point (point))
  1083. ,to-be-removed)
  1084. (save-window-excursion
  1085. (when ,tempvar (find-file ,tempvar))
  1086. (setq ,to-be-removed (current-buffer))
  1087. (goto-char (point-min))
  1088. (while (re-search-forward
  1089. "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t)
  1090. (let ((,datum (save-match-data (org-element-context))))
  1091. (when (memq (org-element-type ,datum)
  1092. '(babel-call inline-babel-call inline-src-block
  1093. src-block))
  1094. (goto-char (match-beginning 0))
  1095. (let ((,end (copy-marker (org-element-property :end ,datum))))
  1096. ,@body
  1097. (goto-char ,end)
  1098. (set-marker ,end nil))))))
  1099. (unless ,visitedp (kill-buffer ,to-be-removed))
  1100. (goto-char ,point))))
  1101. ;;;###autoload
  1102. (defun org-babel-execute-buffer (&optional arg)
  1103. "Execute source code blocks in a buffer.
  1104. Call `org-babel-execute-src-block' on every source block in
  1105. the current buffer."
  1106. (interactive "P")
  1107. (org-babel-eval-wipe-error-buffer)
  1108. (org-save-outline-visibility t
  1109. (org-babel-map-executables nil
  1110. (if (memq (org-element-type (org-element-context))
  1111. '(babel-call inline-babel-call))
  1112. (org-babel-lob-execute-maybe)
  1113. (org-babel-execute-src-block arg)))))
  1114. ;;;###autoload
  1115. (defun org-babel-execute-subtree (&optional arg)
  1116. "Execute source code blocks in a subtree.
  1117. Call `org-babel-execute-src-block' on every source block in
  1118. the current subtree."
  1119. (interactive "P")
  1120. (save-restriction
  1121. (save-excursion
  1122. (org-narrow-to-subtree)
  1123. (org-babel-execute-buffer arg)
  1124. (widen))))
  1125. ;;;###autoload
  1126. (defun org-babel-sha1-hash (&optional info)
  1127. "Generate an sha1 hash based on the value of info."
  1128. (interactive)
  1129. (let ((print-level nil)
  1130. (info (or info (org-babel-get-src-block-info))))
  1131. (setf (nth 2 info)
  1132. (sort (copy-sequence (nth 2 info))
  1133. (lambda (a b) (string< (car a) (car b)))))
  1134. (let* ((rm (lambda (lst)
  1135. (dolist (p '("replace" "silent" "none"
  1136. "append" "prepend"))
  1137. (setq lst (remove p lst)))
  1138. lst))
  1139. (norm (lambda (arg)
  1140. (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
  1141. (copy-sequence (cdr arg))
  1142. (cdr arg))))
  1143. (when (and v (not (and (sequencep v)
  1144. (not (consp v))
  1145. (= (length v) 0))))
  1146. (cond
  1147. ((and (listp v) ; lists are sorted
  1148. (member (car arg) '(:result-params)))
  1149. (sort (funcall rm v) #'string<))
  1150. ((and (stringp v) ; strings are sorted
  1151. (member (car arg) '(:results :exports)))
  1152. (mapconcat #'identity (sort (funcall rm (split-string v))
  1153. #'string<) " "))
  1154. (t v))))))
  1155. ;; expanded body
  1156. (lang (nth 0 info))
  1157. (params (nth 2 info))
  1158. (body (if (org-babel-noweb-p params :eval)
  1159. (org-babel-expand-noweb-references info) (nth 1 info)))
  1160. (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
  1161. (assignments-cmd (intern (concat "org-babel-variable-assignments:"
  1162. lang)))
  1163. (expanded
  1164. (if (fboundp expand-cmd) (funcall expand-cmd body params)
  1165. (org-babel-expand-body:generic
  1166. body params (and (fboundp assignments-cmd)
  1167. (funcall assignments-cmd params))))))
  1168. (let* ((it (format "%s-%s"
  1169. (mapconcat
  1170. #'identity
  1171. (delq nil (mapcar (lambda (arg)
  1172. (let ((normalized (funcall norm arg)))
  1173. (when normalized
  1174. (format "%S" normalized))))
  1175. (nth 2 info))) ":")
  1176. expanded))
  1177. (hash (sha1 it)))
  1178. (when (called-interactively-p 'interactive) (message hash))
  1179. hash))))
  1180. (defun org-babel-current-result-hash (&optional info)
  1181. "Return the current in-buffer hash."
  1182. (let ((result (org-babel-where-is-src-block-result nil info)))
  1183. (when result
  1184. (org-with-wide-buffer
  1185. (goto-char result)
  1186. (looking-at org-babel-result-regexp)
  1187. (match-string-no-properties 1)))))
  1188. (defun org-babel-set-current-result-hash (hash info)
  1189. "Set the current in-buffer hash to HASH."
  1190. (org-with-wide-buffer
  1191. (goto-char (org-babel-where-is-src-block-result nil info))
  1192. (looking-at org-babel-result-regexp)
  1193. (goto-char (match-beginning 1))
  1194. (mapc #'delete-overlay (overlays-at (point)))
  1195. (forward-char org-babel-hash-show)
  1196. (mapc #'delete-overlay (overlays-at (point)))
  1197. (replace-match hash nil nil nil 1)
  1198. (beginning-of-line)
  1199. (org-babel-hide-hash)))
  1200. (defun org-babel-hide-hash ()
  1201. "Hide the hash in the current results line.
  1202. Only the initial `org-babel-hash-show' characters of the hash
  1203. will remain visible."
  1204. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  1205. (save-excursion
  1206. (when (and (re-search-forward org-babel-result-regexp nil t)
  1207. (match-string 1))
  1208. (let* ((start (match-beginning 1))
  1209. (hide-start (+ org-babel-hash-show start))
  1210. (end (match-end 1))
  1211. (hash (match-string 1))
  1212. ov1 ov2)
  1213. (setq ov1 (make-overlay start hide-start))
  1214. (setq ov2 (make-overlay hide-start end))
  1215. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  1216. (overlay-put ov1 'babel-hash hash)))))
  1217. (defun org-babel-hide-all-hashes ()
  1218. "Hide the hash in the current buffer.
  1219. Only the initial `org-babel-hash-show' characters of each hash
  1220. will remain visible. This function should be called as part of
  1221. the `org-mode-hook'."
  1222. (save-excursion
  1223. (while (and (not org-babel-hash-show-time)
  1224. (re-search-forward org-babel-result-regexp nil t))
  1225. (goto-char (match-beginning 0))
  1226. (org-babel-hide-hash)
  1227. (goto-char (match-end 0)))))
  1228. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  1229. (defun org-babel-hash-at-point (&optional point)
  1230. "Return the value of the hash at POINT.
  1231. \\<org-mode-map>\
  1232. The hash is also added as the last element of the kill ring.
  1233. This can be called with `\\[org-ctrl-c-ctrl-c]'."
  1234. (interactive)
  1235. (let ((hash (car (delq nil (mapcar
  1236. (lambda (ol) (overlay-get ol 'babel-hash))
  1237. (overlays-at (or point (point))))))))
  1238. (when hash (kill-new hash) (message hash))))
  1239. (defun org-babel-result-hide-spec ()
  1240. "Hide portions of results lines.
  1241. Add `org-babel-hide-result' as an invisibility spec for hiding
  1242. portions of results lines."
  1243. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  1244. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  1245. (defvar org-babel-hide-result-overlays nil
  1246. "Overlays hiding results.")
  1247. (defun org-babel-result-hide-all ()
  1248. "Fold all results in the current buffer."
  1249. (interactive)
  1250. (org-babel-show-result-all)
  1251. (save-excursion
  1252. (while (re-search-forward org-babel-result-regexp nil t)
  1253. (save-excursion (goto-char (match-beginning 0))
  1254. (org-babel-hide-result-toggle-maybe)))))
  1255. (defun org-babel-show-result-all ()
  1256. "Unfold all results in the current buffer."
  1257. (mapc 'delete-overlay org-babel-hide-result-overlays)
  1258. (setq org-babel-hide-result-overlays nil))
  1259. ;;;###autoload
  1260. (defun org-babel-hide-result-toggle-maybe ()
  1261. "Toggle visibility of result at point."
  1262. (interactive)
  1263. (let ((case-fold-search t))
  1264. (if (save-excursion
  1265. (beginning-of-line 1)
  1266. (looking-at org-babel-result-regexp))
  1267. (progn (org-babel-hide-result-toggle)
  1268. t) ;; to signal that we took action
  1269. nil))) ;; to signal that we did not
  1270. (defun org-babel-hide-result-toggle (&optional force)
  1271. "Toggle the visibility of the current result."
  1272. (interactive)
  1273. (save-excursion
  1274. (beginning-of-line)
  1275. (if (re-search-forward org-babel-result-regexp nil t)
  1276. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  1277. (end (progn
  1278. (while (looking-at org-babel-multi-line-header-regexp)
  1279. (forward-line 1))
  1280. (goto-char (- (org-babel-result-end) 1)) (point)))
  1281. ov)
  1282. (if (memq t (mapcar (lambda (overlay)
  1283. (eq (overlay-get overlay 'invisible)
  1284. 'org-babel-hide-result))
  1285. (overlays-at start)))
  1286. (when (or (not force) (eq force 'off))
  1287. (mapc (lambda (ov)
  1288. (when (member ov org-babel-hide-result-overlays)
  1289. (setq org-babel-hide-result-overlays
  1290. (delq ov org-babel-hide-result-overlays)))
  1291. (when (eq (overlay-get ov 'invisible)
  1292. 'org-babel-hide-result)
  1293. (delete-overlay ov)))
  1294. (overlays-at start)))
  1295. (setq ov (make-overlay start end))
  1296. (overlay-put ov 'invisible 'org-babel-hide-result)
  1297. ;; make the block accessible to isearch
  1298. (overlay-put
  1299. ov 'isearch-open-invisible
  1300. (lambda (ov)
  1301. (when (member ov org-babel-hide-result-overlays)
  1302. (setq org-babel-hide-result-overlays
  1303. (delq ov org-babel-hide-result-overlays)))
  1304. (when (eq (overlay-get ov 'invisible)
  1305. 'org-babel-hide-result)
  1306. (delete-overlay ov))))
  1307. (push ov org-babel-hide-result-overlays)))
  1308. (error "Not looking at a result line"))))
  1309. ;; org-tab-after-check-for-cycling-hook
  1310. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  1311. ;; Remove overlays when changing major mode
  1312. (add-hook 'org-mode-hook
  1313. (lambda () (add-hook 'change-major-mode-hook
  1314. 'org-babel-show-result-all 'append 'local)))
  1315. (defun org-babel-params-from-properties (&optional lang no-eval)
  1316. "Retrieve source block parameters specified as properties.
  1317. LANG is the language of the source block, as a string. When
  1318. optional argument NO-EVAL is non-nil, do not evaluate Lisp values
  1319. in parameters.
  1320. Return a list of association lists of source block parameters
  1321. specified in the properties of the current outline entry."
  1322. (save-match-data
  1323. (list
  1324. ;; Header arguments specified with the header-args property at
  1325. ;; point of call.
  1326. (org-babel-parse-header-arguments
  1327. (org-entry-get (point) "header-args" 'inherit)
  1328. no-eval)
  1329. ;; Language-specific header arguments at point of call.
  1330. (and lang
  1331. (org-babel-parse-header-arguments
  1332. (org-entry-get (point) (concat "header-args:" lang) 'inherit)
  1333. no-eval)))))
  1334. (defun org-babel-balanced-split (string alts)
  1335. "Split STRING on instances of ALTS.
  1336. ALTS is a character, or cons of two character options where each
  1337. option may be either the numeric code of a single character or
  1338. a list of character alternatives. For example, to split on
  1339. balanced instances of \"[ \t]:\", set ALTS to ((32 9) . 58)."
  1340. (with-temp-buffer
  1341. (insert string)
  1342. (goto-char (point-min))
  1343. (let ((splitp (lambda (past next)
  1344. ;; Non-nil when there should be a split after NEXT
  1345. ;; character. PAST is the character before NEXT.
  1346. (pcase alts
  1347. (`(,(and first (pred consp)) . ,(and second (pred consp)))
  1348. (and (memq past first) (memq next second)))
  1349. (`(,first . ,(and second (pred consp)))
  1350. (and (eq past first) (memq next second)))
  1351. (`(,(and first (pred consp)) . ,second)
  1352. (and (memq past first) (eq next second)))
  1353. (`(,first . ,second)
  1354. (and (eq past first) (eq next second)))
  1355. ((pred (eq next)) t)
  1356. (_ nil))))
  1357. (partial nil)
  1358. (result nil))
  1359. (while (not (eobp))
  1360. (cond
  1361. ((funcall splitp (char-before) (char-after))
  1362. ;; There is a split after point. If ALTS is two-folds,
  1363. ;; remove last parsed character as it belongs to ALTS.
  1364. (when (consp alts) (pop partial))
  1365. ;; Include elements parsed so far in RESULTS and flush
  1366. ;; partial parsing.
  1367. (when partial
  1368. (push (apply #'string (nreverse partial)) result)
  1369. (setq partial nil))
  1370. (forward-char))
  1371. ((memq (char-after) '(?\( ?\[))
  1372. ;; Include everything between balanced brackets.
  1373. (let* ((origin (point))
  1374. (after (char-after))
  1375. (openings (list after)))
  1376. (forward-char)
  1377. (while (and openings (re-search-forward "[]()]" nil t))
  1378. (pcase (char-before)
  1379. ((and match (or ?\[ ?\()) (push match openings))
  1380. (?\] (when (eq ?\[ (car openings)) (pop openings)))
  1381. (_ (when (eq ?\( (car openings)) (pop openings)))))
  1382. (if (null openings)
  1383. (setq partial
  1384. (nconc (nreverse (string-to-list
  1385. (buffer-substring origin (point))))
  1386. partial))
  1387. ;; Un-balanced bracket. Backtrack.
  1388. (push after partial)
  1389. (goto-char (1+ origin)))))
  1390. ((and (eq ?\" (char-after)) (not (eq ?\\ (char-before))))
  1391. ;; Include everything from current double quote to next
  1392. ;; non-escaped double quote.
  1393. (let ((origin (point)))
  1394. (if (re-search-forward "[^\\]\"" nil t)
  1395. (setq partial
  1396. (nconc (nreverse (string-to-list
  1397. (buffer-substring origin (point))))
  1398. partial))
  1399. ;; No closing double quote. Backtrack.
  1400. (push ?\" partial)
  1401. (forward-char))))
  1402. (t (push (char-after) partial)
  1403. (forward-char))))
  1404. ;; Add pending parsing and return result.
  1405. (when partial (push (apply #'string (nreverse partial)) result))
  1406. (nreverse result))))
  1407. (defun org-babel-join-splits-near-ch (ch list)
  1408. "Join splits where \"=\" is on either end of the split."
  1409. (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
  1410. (first= (lambda (str) (= ch (aref str 0)))))
  1411. (reverse
  1412. (cl-reduce (lambda (acc el)
  1413. (let ((head (car acc)))
  1414. (if (and head (or (funcall last= head) (funcall first= el)))
  1415. (cons (concat head el) (cdr acc))
  1416. (cons el acc))))
  1417. list :initial-value nil))))
  1418. (defun org-babel-parse-header-arguments (string &optional no-eval)
  1419. "Parse header arguments in STRING.
  1420. When optional argument NO-EVAL is non-nil, do not evaluate Lisp
  1421. in parameters. Return an alist."
  1422. (when (org-string-nw-p string)
  1423. (org-babel-parse-multiple-vars
  1424. (delq nil
  1425. (mapcar
  1426. (lambda (arg)
  1427. (if (string-match
  1428. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  1429. arg)
  1430. (cons (intern (match-string 1 arg))
  1431. (org-babel-read (org-babel-chomp (match-string 2 arg))
  1432. no-eval))
  1433. (cons (intern (org-babel-chomp arg)) nil)))
  1434. (let ((raw (org-babel-balanced-split string '((32 9) . 58))))
  1435. (cons (car raw)
  1436. (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
  1437. (defun org-babel-parse-multiple-vars (header-arguments)
  1438. "Expand multiple variable assignments behind a single :var keyword.
  1439. This allows expression of multiple variables with one :var as
  1440. shown below.
  1441. #+PROPERTY: var foo=1, bar=2"
  1442. (let (results)
  1443. (mapc (lambda (pair)
  1444. (if (eq (car pair) :var)
  1445. (mapcar (lambda (v) (push (cons :var (org-trim v)) results))
  1446. (org-babel-join-splits-near-ch
  1447. 61 (org-babel-balanced-split (cdr pair) 32)))
  1448. (push pair results)))
  1449. header-arguments)
  1450. (nreverse results)))
  1451. (defun org-babel-process-params (params)
  1452. "Expand variables in PARAMS and add summary parameters."
  1453. (let* ((processed-vars (mapcar (lambda (el)
  1454. (if (consp el)
  1455. el
  1456. (org-babel-ref-parse el)))
  1457. (org-babel--get-vars params)))
  1458. (vars-and-names (if (and (assq :colname-names params)
  1459. (assq :rowname-names params))
  1460. (list processed-vars)
  1461. (org-babel-disassemble-tables
  1462. processed-vars
  1463. (cdr (assq :hlines params))
  1464. (cdr (assq :colnames params))
  1465. (cdr (assq :rownames params)))))
  1466. (raw-result (or (cdr (assq :results params)) ""))
  1467. (result-params (delete-dups
  1468. (append
  1469. (split-string (if (stringp raw-result)
  1470. raw-result
  1471. (eval raw-result t)))
  1472. (cdr (assq :result-params params))))))
  1473. (append
  1474. (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
  1475. (list
  1476. (cons :colname-names (or (cdr (assq :colname-names params))
  1477. (cadr vars-and-names)))
  1478. (cons :rowname-names (or (cdr (assq :rowname-names params))
  1479. (cl-caddr vars-and-names)))
  1480. (cons :result-params result-params)
  1481. (cons :result-type (cond ((member "output" result-params) 'output)
  1482. ((member "value" result-params) 'value)
  1483. (t 'value))))
  1484. (cl-remove-if
  1485. (lambda (x) (memq (car x) '(:colname-names :rowname-names :result-params
  1486. :result-type :var)))
  1487. params))))
  1488. ;; row and column names
  1489. (defun org-babel-del-hlines (table)
  1490. "Remove all `hline's from TABLE."
  1491. (remq 'hline table))
  1492. (defun org-babel-get-colnames (table)
  1493. "Return the column names of TABLE.
  1494. Return a cons cell, the `car' of which contains the TABLE less
  1495. colnames, and the `cdr' of which contains a list of the column
  1496. names."
  1497. (if (eq 'hline (nth 1 table))
  1498. (cons (cddr table) (car table))
  1499. (cons (cdr table) (car table))))
  1500. (defun org-babel-get-rownames (table)
  1501. "Return the row names of TABLE.
  1502. Return a cons cell, the `car' of which contains the TABLE less
  1503. rownames, and the `cdr' of which contains a list of the rownames.
  1504. Note: this function removes any hlines in TABLE."
  1505. (let* ((table (org-babel-del-hlines table))
  1506. (rownames (funcall (lambda ()
  1507. (let ((tp table))
  1508. (mapcar
  1509. (lambda (_row)
  1510. (prog1
  1511. (pop (car tp))
  1512. (setq tp (cdr tp))))
  1513. table))))))
  1514. (cons table rownames)))
  1515. (defun org-babel-put-colnames (table colnames)
  1516. "Add COLNAMES to TABLE if they exist."
  1517. (if colnames (apply 'list colnames 'hline table) table))
  1518. (defun org-babel-put-rownames (table rownames)
  1519. "Add ROWNAMES to TABLE if they exist."
  1520. (if rownames
  1521. (mapcar (lambda (row)
  1522. (if (listp row)
  1523. (cons (or (pop rownames) "") row)
  1524. row)) table)
  1525. table))
  1526. (defun org-babel-pick-name (names selector)
  1527. "Select one out of an alist of row or column names.
  1528. SELECTOR can be either a list of names in which case those names
  1529. will be returned directly, or an index into the list NAMES in
  1530. which case the indexed names will be return."
  1531. (if (listp selector)
  1532. selector
  1533. (when names
  1534. (if (and selector (symbolp selector) (not (equal t selector)))
  1535. (cdr (assoc selector names))
  1536. (if (integerp selector)
  1537. (nth (- selector 1) names)
  1538. (cdr (car (last names))))))))
  1539. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  1540. "Parse tables for further processing.
  1541. Process the variables in VARS according to the HLINES,
  1542. ROWNAMES and COLNAMES header arguments. Return a list consisting
  1543. of the vars, cnames and rnames."
  1544. (let (cnames rnames)
  1545. (list
  1546. (mapcar
  1547. (lambda (var)
  1548. (when (listp (cdr var))
  1549. (when (and (not (equal colnames "no"))
  1550. (or colnames (and (eq (nth 1 (cdr var)) 'hline)
  1551. (not (member 'hline (cddr (cdr var)))))))
  1552. (let ((both (org-babel-get-colnames (cdr var))))
  1553. (setq cnames (cons (cons (car var) (cdr both))
  1554. cnames))
  1555. (setq var (cons (car var) (car both)))))
  1556. (when (and rownames (not (equal rownames "no")))
  1557. (let ((both (org-babel-get-rownames (cdr var))))
  1558. (setq rnames (cons (cons (car var) (cdr both))
  1559. rnames))
  1560. (setq var (cons (car var) (car both)))))
  1561. (when (and hlines (not (equal hlines "yes")))
  1562. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  1563. var)
  1564. vars)
  1565. (reverse cnames) (reverse rnames))))
  1566. (defun org-babel-reassemble-table (table colnames rownames)
  1567. "Add column and row names to a table.
  1568. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  1569. to the table for reinsertion to org-mode."
  1570. (if (listp table)
  1571. (let ((table (if (and rownames (= (length table) (length rownames)))
  1572. (org-babel-put-rownames table rownames) table)))
  1573. (if (and colnames (listp (car table)) (= (length (car table))
  1574. (length colnames)))
  1575. (org-babel-put-colnames table colnames) table))
  1576. table))
  1577. (defun org-babel-where-is-src-block-head (&optional src-block)
  1578. "Find where the current source block begins.
  1579. If optional argument SRC-BLOCK is `src-block' type element, find
  1580. its current beginning instead.
  1581. Return the point at the beginning of the current source block.
  1582. Specifically at the beginning of the #+BEGIN_SRC line. Also set
  1583. match-data relatively to `org-babel-src-block-regexp', which see.
  1584. If the point is not on a source block then return nil."
  1585. (let ((element (or src-block (org-element-at-point))))
  1586. (when (eq (org-element-type element) 'src-block)
  1587. (let ((end (org-element-property :end element)))
  1588. (org-with-wide-buffer
  1589. ;; Ensure point is not on a blank line after the block.
  1590. (beginning-of-line)
  1591. (skip-chars-forward " \r\t\n" end)
  1592. (when (< (point) end)
  1593. (prog1 (goto-char (org-element-property :post-affiliated element))
  1594. (looking-at org-babel-src-block-regexp))))))))
  1595. ;;;###autoload
  1596. (defun org-babel-goto-src-block-head ()
  1597. "Go to the beginning of the current code block."
  1598. (interactive)
  1599. (let ((head (org-babel-where-is-src-block-head)))
  1600. (if head (goto-char head) (error "Not currently in a code block"))))
  1601. ;;;###autoload
  1602. (defun org-babel-goto-named-src-block (name)
  1603. "Go to a named source-code block."
  1604. (interactive
  1605. (let ((completion-ignore-case t)
  1606. (case-fold-search t)
  1607. (all-block-names (org-babel-src-block-names)))
  1608. (list (completing-read
  1609. "source-block name: " all-block-names nil t
  1610. (let* ((context (org-element-context))
  1611. (type (org-element-type context))
  1612. (noweb-ref
  1613. (and (memq type '(inline-src-block src-block))
  1614. (org-in-regexp (org-babel-noweb-wrap)))))
  1615. (cond
  1616. (noweb-ref
  1617. (buffer-substring
  1618. (+ (car noweb-ref) (length org-babel-noweb-wrap-start))
  1619. (- (cdr noweb-ref) (length org-babel-noweb-wrap-end))))
  1620. ((memq type '(babel-call inline-babel-call)) ;#+CALL:
  1621. (org-element-property :call context))
  1622. ((car (org-element-property :results context))) ;#+RESULTS:
  1623. ((let ((symbol (thing-at-point 'symbol))) ;Symbol.
  1624. (and symbol
  1625. (member-ignore-case symbol all-block-names)
  1626. symbol)))
  1627. (t "")))))))
  1628. (let ((point (org-babel-find-named-block name)))
  1629. (if point
  1630. ;; Taken from `org-open-at-point'.
  1631. (progn (org-mark-ring-push) (goto-char point) (org-show-context))
  1632. (message "source-code block `%s' not found in this buffer" name))))
  1633. (defun org-babel-find-named-block (name)
  1634. "Find a named source-code block.
  1635. Return the location of the source block identified by source
  1636. NAME, or nil if no such block exists. Set match data according
  1637. to `org-babel-named-src-block-regexp'."
  1638. (save-excursion
  1639. (goto-char (point-min))
  1640. (let ((regexp (org-babel-named-src-block-regexp-for-name name)))
  1641. (or (and (looking-at regexp)
  1642. (progn (goto-char (match-beginning 1))
  1643. (line-beginning-position)))
  1644. (ignore-errors (org-next-block 1 nil regexp))))))
  1645. (defun org-babel-src-block-names (&optional file)
  1646. "Returns the names of source blocks in FILE or the current buffer."
  1647. (with-current-buffer (if file (find-file-noselect file) (current-buffer))
  1648. (org-with-point-at 1
  1649. (let ((regexp "^[ \t]*#\\+begin_src ")
  1650. (case-fold-search t)
  1651. (names nil))
  1652. (while (re-search-forward regexp nil t)
  1653. (let ((element (org-element-at-point)))
  1654. (when (eq 'src-block (org-element-type element))
  1655. (let ((name (org-element-property :name element)))
  1656. (when name (push name names))))))
  1657. names))))
  1658. ;;;###autoload
  1659. (defun org-babel-goto-named-result (name)
  1660. "Go to a named result."
  1661. (interactive
  1662. (let ((completion-ignore-case t))
  1663. (list (completing-read "Source-block name: "
  1664. (org-babel-result-names) nil t))))
  1665. (let ((point (org-babel-find-named-result name)))
  1666. (if point
  1667. ;; taken from `org-open-at-point'
  1668. (progn (goto-char point) (org-show-context))
  1669. (message "result `%s' not found in this buffer" name))))
  1670. (defun org-babel-find-named-result (name)
  1671. "Find a named result.
  1672. Return the location of the result named NAME in the current
  1673. buffer or nil if no such result exists."
  1674. (save-excursion
  1675. (goto-char (point-min))
  1676. (let ((case-fold-search t)
  1677. (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
  1678. org-babel-results-keyword
  1679. (regexp-quote name))))
  1680. (catch :found
  1681. (while (re-search-forward re nil t)
  1682. (let ((element (org-element-at-point)))
  1683. (when (or (eq (org-element-type element) 'keyword)
  1684. (< (point)
  1685. (org-element-property :post-affiliated element)))
  1686. (throw :found (line-beginning-position)))))))))
  1687. (defun org-babel-result-names (&optional file)
  1688. "Returns the names of results in FILE or the current buffer."
  1689. (save-excursion
  1690. (when file (find-file file)) (goto-char (point-min))
  1691. (let ((case-fold-search t) names)
  1692. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1693. (setq names (cons (match-string-no-properties 9) names)))
  1694. names)))
  1695. ;;;###autoload
  1696. (defun org-babel-next-src-block (&optional arg)
  1697. "Jump to the next source block.
  1698. With optional prefix argument ARG, jump forward ARG many source blocks."
  1699. (interactive "p")
  1700. (org-next-block arg nil org-babel-src-block-regexp))
  1701. ;;;###autoload
  1702. (defun org-babel-previous-src-block (&optional arg)
  1703. "Jump to the previous source block.
  1704. With optional prefix argument ARG, jump backward ARG many source blocks."
  1705. (interactive "p")
  1706. (org-previous-block arg org-babel-src-block-regexp))
  1707. (defvar org-babel-load-languages)
  1708. ;;;###autoload
  1709. (defun org-babel-mark-block ()
  1710. "Mark current src block."
  1711. (interactive)
  1712. (let ((head (org-babel-where-is-src-block-head)))
  1713. (when head
  1714. (save-excursion
  1715. (goto-char head)
  1716. (looking-at org-babel-src-block-regexp))
  1717. (push-mark (match-end 5) nil t)
  1718. (goto-char (match-beginning 5)))))
  1719. (defun org-babel-demarcate-block (&optional arg)
  1720. "Wrap or split the code in the region or on the point.
  1721. When called from inside of a code block the current block is
  1722. split. When called from outside of a code block a new code block
  1723. is created. In both cases if the region is demarcated and if the
  1724. region is not active then the point is demarcated."
  1725. (interactive "P")
  1726. (let* ((info (org-babel-get-src-block-info 'light))
  1727. (start (org-babel-where-is-src-block-head))
  1728. (block (and start (match-string 0)))
  1729. (headers (and start (match-string 4)))
  1730. (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
  1731. (lower-case-p (and block
  1732. (let (case-fold-search)
  1733. (string-match-p "#\\+begin_src" block)))))
  1734. (if info
  1735. (mapc
  1736. (lambda (place)
  1737. (save-excursion
  1738. (goto-char place)
  1739. (let ((lang (nth 0 info))
  1740. (indent (make-string (org-get-indentation) ?\s)))
  1741. (when (string-match "^[[:space:]]*$"
  1742. (buffer-substring (point-at-bol)
  1743. (point-at-eol)))
  1744. (delete-region (point-at-bol) (point-at-eol)))
  1745. (insert (concat
  1746. (if (looking-at "^") "" "\n")
  1747. indent (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")
  1748. (if arg stars indent) "\n"
  1749. indent (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
  1750. lang
  1751. (if (> (length headers) 1)
  1752. (concat " " headers) headers)
  1753. (if (looking-at "[\n\r]")
  1754. ""
  1755. (concat "\n" (make-string (current-column) ? )))))))
  1756. (move-end-of-line 2))
  1757. (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
  1758. (let ((start (point))
  1759. (lang (completing-read
  1760. "Lang: "
  1761. (mapcar #'symbol-name
  1762. (delete-dups
  1763. (append (mapcar #'car org-babel-load-languages)
  1764. (mapcar (lambda (el) (intern (car el)))
  1765. org-src-lang-modes))))))
  1766. (body (delete-and-extract-region
  1767. (if (org-region-active-p) (mark) (point)) (point))))
  1768. (insert (concat (if (looking-at "^") "" "\n")
  1769. (if arg (concat stars "\n") "")
  1770. (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
  1771. lang "\n"
  1772. body
  1773. (if (or (= (length body) 0)
  1774. (string-suffix-p "\r" body)
  1775. (string-suffix-p "\n" body)) "" "\n")
  1776. (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")))
  1777. (goto-char start) (move-end-of-line 1)))))
  1778. (defun org-babel--insert-results-keyword (name hash)
  1779. "Insert RESULTS keyword with NAME value at point.
  1780. If NAME is nil, results are anonymous. HASH is a string used as
  1781. the results hash, or nil. Leave point before the keyword."
  1782. (save-excursion (insert "\n")) ;open line to indent.
  1783. (org-indent-line)
  1784. (delete-char 1)
  1785. (insert (concat "#+" org-babel-results-keyword
  1786. (cond ((not hash) nil)
  1787. (org-babel-hash-show-time
  1788. (format "[%s %s]"
  1789. (format-time-string "<%F %T>")
  1790. hash))
  1791. (t (format "[%s]" hash)))
  1792. ":"
  1793. (when name (concat " " name))
  1794. "\n"))
  1795. ;; Make sure results are going to be followed by at least one blank
  1796. ;; line so they do not get merged with the next element, e.g.,
  1797. ;;
  1798. ;; #+results:
  1799. ;; : 1
  1800. ;;
  1801. ;; : fixed-width area, unrelated to the above.
  1802. (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n")))
  1803. (beginning-of-line 0)
  1804. (when hash (org-babel-hide-hash)))
  1805. (defun org-babel--clear-results-maybe (hash)
  1806. "Clear results when hash doesn't match HASH.
  1807. When results hash does not match HASH, remove RESULTS keyword at
  1808. point, along with related contents. Do nothing if HASH is nil.
  1809. Return a non-nil value if results were cleared. In this case,
  1810. leave point where new results should be inserted."
  1811. (when hash
  1812. (looking-at org-babel-result-regexp)
  1813. (unless (string= (match-string 1) hash)
  1814. (let* ((e (org-element-at-point))
  1815. (post (copy-marker (org-element-property :post-affiliated e))))
  1816. ;; Delete contents.
  1817. (delete-region post
  1818. (save-excursion
  1819. (goto-char (org-element-property :end e))
  1820. (skip-chars-backward " \t\n")
  1821. (line-beginning-position 2)))
  1822. ;; Delete RESULT keyword. However, if RESULTS keyword is
  1823. ;; orphaned, ignore this part. The deletion above already
  1824. ;; took care of it.
  1825. (unless (= (point) post)
  1826. (delete-region (line-beginning-position)
  1827. (line-beginning-position 2)))
  1828. (goto-char post)
  1829. (set-marker post nil)
  1830. t))))
  1831. (defun org-babel-where-is-src-block-result (&optional insert _info hash)
  1832. "Find where the current source block results begin.
  1833. Return the point at the beginning of the result of the current
  1834. source block, specifically at the beginning of the results line.
  1835. If no result exists for this block return nil, unless optional
  1836. argument INSERT is non-nil. In this case, create a results line
  1837. following the source block and return the position at its
  1838. beginning. In the case of inline code, remove the results part
  1839. instead.
  1840. If optional argument HASH is a string, remove contents related to
  1841. RESULTS keyword if its hash is different. Then update the latter
  1842. to HASH."
  1843. (let ((context (org-element-context)))
  1844. (catch :found
  1845. (org-with-wide-buffer
  1846. (pcase (org-element-type context)
  1847. ((or `inline-babel-call `inline-src-block)
  1848. ;; Results for inline objects are located right after them.
  1849. ;; There is no RESULTS line to insert either.
  1850. (let ((limit (org-element-property
  1851. :contents-end (org-element-property :parent context))))
  1852. (goto-char (org-element-property :end context))
  1853. (skip-chars-forward " \t\n" limit)
  1854. (throw :found
  1855. (and
  1856. (< (point) limit)
  1857. (let ((result (org-element-context)))
  1858. (and (eq (org-element-type result) 'macro)
  1859. (string= (org-element-property :key result)
  1860. "results")
  1861. (if (not insert) (point)
  1862. (delete-region
  1863. (point)
  1864. (progn
  1865. (goto-char (org-element-property :end result))
  1866. (skip-chars-backward " \t")
  1867. (point)))
  1868. (point))))))))
  1869. ((or `babel-call `src-block)
  1870. (let* ((name (org-element-property :name context))
  1871. (named-results (and name (org-babel-find-named-result name))))
  1872. (goto-char (or named-results (org-element-property :end context)))
  1873. (cond
  1874. ;; Existing results named after the current source.
  1875. (named-results
  1876. (when (org-babel--clear-results-maybe hash)
  1877. (org-babel--insert-results-keyword name hash))
  1878. (throw :found (point)))
  1879. ;; Named results expect but none to be found.
  1880. (name)
  1881. ;; No possible anonymous results at the very end of
  1882. ;; buffer or outside CONTEXT parent.
  1883. ((eq (point)
  1884. (or (org-element-property
  1885. :contents-end (org-element-property :parent context))
  1886. (point-max))))
  1887. ;; Check if next element is an anonymous result below
  1888. ;; the current block.
  1889. ((let* ((next (org-element-at-point))
  1890. (end (save-excursion
  1891. (goto-char
  1892. (org-element-property :post-affiliated next))
  1893. (line-end-position)))
  1894. (empty-result-re (concat org-babel-result-regexp "$"))
  1895. (case-fold-search t))
  1896. (re-search-forward empty-result-re end t))
  1897. (beginning-of-line)
  1898. (when (org-babel--clear-results-maybe hash)
  1899. (org-babel--insert-results-keyword nil hash))
  1900. (throw :found (point))))))
  1901. ;; Ignore other elements.
  1902. (_ (throw :found nil))))
  1903. ;; No result found. Insert a RESULTS keyword below element, if
  1904. ;; appropriate. In this case, ensure there is an empty line
  1905. ;; after the previous element.
  1906. (when insert
  1907. (save-excursion
  1908. (goto-char (min (org-element-property :end context) (point-max)))
  1909. (skip-chars-backward " \t\n")
  1910. (forward-line)
  1911. (unless (bolp) (insert "\n"))
  1912. (insert "\n")
  1913. (org-babel--insert-results-keyword
  1914. (org-element-property :name context) hash)
  1915. (point))))))
  1916. (defun org-babel-read-element (element)
  1917. "Read ELEMENT into emacs-lisp.
  1918. Return nil if ELEMENT cannot be read."
  1919. (org-with-wide-buffer
  1920. (goto-char (org-element-property :post-affiliated element))
  1921. (pcase (org-element-type element)
  1922. (`fixed-width
  1923. (let ((v (org-trim (org-element-property :value element))))
  1924. (or (org-babel--string-to-number v) v)))
  1925. (`table (org-babel-read-table))
  1926. (`plain-list (org-babel-read-list))
  1927. (`example-block
  1928. (let ((v (org-element-property :value element)))
  1929. (if (or org-src-preserve-indentation
  1930. (org-element-property :preserve-indent element))
  1931. v
  1932. (org-remove-indentation v))))
  1933. (`export-block
  1934. (org-remove-indentation (org-element-property :value element)))
  1935. (`paragraph
  1936. ;; Treat paragraphs containing a single link specially.
  1937. (skip-chars-forward " \t")
  1938. (if (and (looking-at org-bracket-link-regexp)
  1939. (save-excursion
  1940. (goto-char (match-end 0))
  1941. (skip-chars-forward " \r\t\n")
  1942. (<= (org-element-property :end element)
  1943. (point))))
  1944. (org-babel-read-link)
  1945. (buffer-substring-no-properties
  1946. (org-element-property :contents-begin element)
  1947. (org-element-property :contents-end element))))
  1948. ((or `center-block `quote-block `verse-block `special-block)
  1949. (org-remove-indentation
  1950. (buffer-substring-no-properties
  1951. (org-element-property :contents-begin element)
  1952. (org-element-property :contents-end element))))
  1953. (_ nil))))
  1954. (defun org-babel-read-result ()
  1955. "Read the result at point into emacs-lisp."
  1956. (and (not (save-excursion
  1957. (beginning-of-line)
  1958. (looking-at-p "[ \t]*$")))
  1959. (org-babel-read-element (org-element-at-point))))
  1960. (defun org-babel-read-table ()
  1961. "Read the table at point into emacs-lisp."
  1962. (mapcar (lambda (row)
  1963. (if (and (symbolp row) (equal row 'hline)) row
  1964. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
  1965. (org-table-to-lisp)))
  1966. (defun org-babel-read-list ()
  1967. "Read the list at point into emacs-lisp."
  1968. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
  1969. (cdr (org-list-to-lisp))))
  1970. (defvar org-link-types-re)
  1971. (defun org-babel-read-link ()
  1972. "Read the link at point into emacs-lisp.
  1973. If the path of the link is a file path it is expanded using
  1974. `expand-file-name'."
  1975. (let* ((case-fold-search t)
  1976. (raw (and (looking-at org-bracket-link-regexp)
  1977. (org-no-properties (match-string 1))))
  1978. (type (and (string-match org-link-types-re raw)
  1979. (match-string 1 raw))))
  1980. (cond
  1981. ((not type) (expand-file-name raw))
  1982. ((string= type "file")
  1983. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1984. (expand-file-name (match-string 2 raw))))
  1985. (t raw))))
  1986. (defun org-babel-format-result (result &optional sep)
  1987. "Format RESULT for writing to file."
  1988. (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
  1989. (if (listp result)
  1990. ;; table result
  1991. (orgtbl-to-generic
  1992. result (list :sep (or sep "\t") :fmt echo-res))
  1993. ;; scalar result
  1994. (funcall echo-res result))))
  1995. (defun org-babel-insert-result (result &optional result-params info hash lang)
  1996. "Insert RESULT into the current buffer.
  1997. By default RESULT is inserted after the end of the current source
  1998. block. The RESULT of an inline source block usually will be
  1999. wrapped inside a `results' macro and placed on the same line as
  2000. the inline source block. The macro is stripped upon export.
  2001. Multiline and non-scalar RESULTS from inline source blocks are
  2002. not allowed. With optional argument RESULT-PARAMS controls
  2003. insertion of results in the Org mode file. RESULT-PARAMS can
  2004. take the following values:
  2005. replace - (default option) insert results after the source block
  2006. or inline source block replacing any previously
  2007. inserted results.
  2008. silent -- no results are inserted into the Org buffer but
  2009. the results are echoed to the minibuffer and are
  2010. ingested by Emacs (a potentially time consuming
  2011. process).
  2012. file ---- the results are interpreted as a file path, and are
  2013. inserted into the buffer using the Org file syntax.
  2014. list ---- the results are interpreted as an Org list.
  2015. raw ----- results are added directly to the Org file. This is
  2016. a good option if you code block will output Org
  2017. formatted text.
  2018. drawer -- results are added directly to the Org file as with
  2019. \"raw\", but are wrapped in a RESULTS drawer or results
  2020. macro, allowing them to later be replaced or removed
  2021. automatically.
  2022. org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
  2023. org\" block depending on whether the current source block is
  2024. inline or not. They are not comma-escaped when inserted,
  2025. but Org syntax here will be discarded when exporting the
  2026. file.
  2027. html ---- results are added inside of a #+BEGIN_EXPORT HTML block
  2028. or html export snippet depending on whether the current
  2029. source block is inline or not. This is a good option
  2030. if your code block will output html formatted text.
  2031. latex --- results are added inside of a #+BEGIN_EXPORT LATEX
  2032. block or latex export snippet depending on whether the
  2033. current source block is inline or not. This is a good
  2034. option if your code block will output latex formatted
  2035. text.
  2036. code ---- the results are extracted in the syntax of the source
  2037. code of the language being evaluated and are added
  2038. inside of a source block with the source-code language
  2039. set appropriately. Also, source block inlining is
  2040. preserved in this case. Note this relies on the
  2041. optional LANG argument.
  2042. list ---- the results are rendered as a list. This option not
  2043. allowed for inline src blocks.
  2044. table --- the results are rendered as a table. This option not
  2045. allowed for inline src blocks.
  2046. INFO may provide the values of these header arguments (in the
  2047. `header-arguments-alist' see the docstring for
  2048. `org-babel-get-src-block-info'):
  2049. :file --- the name of the file to which output should be written.
  2050. :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
  2051. using the argument supplied to specify the export block
  2052. or snippet type."
  2053. (cond ((stringp result)
  2054. (setq result (org-no-properties result))
  2055. (when (member "file" result-params)
  2056. (setq result (org-babel-result-to-file
  2057. result (when (assq :file-desc (nth 2 info))
  2058. (or (cdr (assq :file-desc (nth 2 info)))
  2059. result))))))
  2060. ((listp result))
  2061. (t (setq result (format "%S" result))))
  2062. (if (and result-params (member "silent" result-params))
  2063. (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  2064. result)
  2065. (let ((inline (let ((context (org-element-context)))
  2066. (and (memq (org-element-type context)
  2067. '(inline-babel-call inline-src-block))
  2068. context))))
  2069. (when inline
  2070. (let ((warning
  2071. (or (and (member "table" result-params) "`:results table'")
  2072. (and (listp result) "list result")
  2073. (and (string-match-p "\n." result) "multiline result")
  2074. (and (member "list" result-params) "`:results list'"))))
  2075. (when warning
  2076. (user-error "Inline error: %s cannot be used" warning))))
  2077. (save-excursion
  2078. (let* ((visible-beg (point-min-marker))
  2079. (visible-end (copy-marker (point-max) t))
  2080. (inline (let ((context (org-element-context)))
  2081. (and (memq (org-element-type context)
  2082. '(inline-babel-call inline-src-block))
  2083. context)))
  2084. (existing-result (org-babel-where-is-src-block-result t nil hash))
  2085. (results-switches (cdr (assq :results_switches (nth 2 info))))
  2086. ;; When results exist outside of the current visible
  2087. ;; region of the buffer, be sure to widen buffer to
  2088. ;; update them.
  2089. (outside-scope (and existing-result
  2090. (buffer-narrowed-p)
  2091. (or (> visible-beg existing-result)
  2092. (<= visible-end existing-result))))
  2093. beg end indent)
  2094. ;; Ensure non-inline results end in a newline.
  2095. (when (and (org-string-nw-p result)
  2096. (not inline)
  2097. (not (string-equal (substring result -1) "\n")))
  2098. (setq result (concat result "\n")))
  2099. (unwind-protect
  2100. (progn
  2101. (when outside-scope (widen))
  2102. (if existing-result (goto-char existing-result)
  2103. (goto-char (org-element-property :end inline))
  2104. (skip-chars-backward " \t"))
  2105. (unless inline
  2106. (setq indent (org-get-indentation))
  2107. (forward-line 1))
  2108. (setq beg (point))
  2109. (cond
  2110. (inline
  2111. ;; Make sure new results are separated from the
  2112. ;; source code by one space.
  2113. (unless existing-result
  2114. (insert " ")
  2115. (setq beg (point))))
  2116. ((member "replace" result-params)
  2117. (delete-region (point) (org-babel-result-end)))
  2118. ((member "append" result-params)
  2119. (goto-char (org-babel-result-end)) (setq beg (point-marker)))
  2120. ((member "prepend" result-params))) ; already there
  2121. (setq results-switches
  2122. (if results-switches (concat " " results-switches) ""))
  2123. (let ((wrap
  2124. (lambda (start finish &optional no-escape no-newlines
  2125. inline-start inline-finish)
  2126. (when inline
  2127. (setq start inline-start)
  2128. (setq finish inline-finish)
  2129. (setq no-newlines t))
  2130. (let ((before-finish (marker-position end)))
  2131. (goto-char end)
  2132. (insert (concat finish (unless no-newlines "\n")))
  2133. (goto-char beg)
  2134. (insert (concat start (unless no-newlines "\n")))
  2135. (unless no-escape
  2136. (org-escape-code-in-region
  2137. (min (point) before-finish) before-finish))
  2138. (goto-char end))))
  2139. (tabulablep
  2140. (lambda (r)
  2141. ;; Non-nil when result R can be turned into
  2142. ;; a table.
  2143. (and (listp r)
  2144. (null (cdr (last r)))
  2145. (cl-every
  2146. (lambda (e) (or (atom e) (null (cdr (last e)))))
  2147. result)))))
  2148. ;; insert results based on type
  2149. (cond
  2150. ;; Do nothing for an empty result.
  2151. ((null result))
  2152. ;; Insert a list if preferred.
  2153. ((member "list" result-params)
  2154. (insert
  2155. (org-trim
  2156. (org-list-to-generic
  2157. (cons 'unordered
  2158. (mapcar
  2159. (lambda (e)
  2160. (list (if (stringp e) e (format "%S" e))))
  2161. (if (listp result) result
  2162. (split-string result "\n" t))))
  2163. '(:splicep nil :istart "- " :iend "\n")))
  2164. "\n"))
  2165. ;; Try hard to print RESULT as a table. Give up if
  2166. ;; it contains an improper list.
  2167. ((funcall tabulablep result)
  2168. (goto-char beg)
  2169. (insert (concat (orgtbl-to-orgtbl
  2170. (if (cl-every
  2171. (lambda (e)
  2172. (or (eq e 'hline) (listp e)))
  2173. result)
  2174. result
  2175. (list result))
  2176. nil)
  2177. "\n"))
  2178. (goto-char beg)
  2179. (when (org-at-table-p) (org-table-align))
  2180. (goto-char (org-table-end)))
  2181. ;; Print verbatim a list that cannot be turned into
  2182. ;; a table.
  2183. ((listp result) (insert (format "%s\n" result)))
  2184. ((member "file" result-params)
  2185. (when inline
  2186. (setq result (org-macro-escape-arguments result)))
  2187. (insert result))
  2188. ((and inline (not (member "raw" result-params)))
  2189. (insert (org-macro-escape-arguments
  2190. (org-babel-chomp result "\n"))))
  2191. (t (goto-char beg) (insert result)))
  2192. (setq end (copy-marker (point) t))
  2193. ;; possibly wrap result
  2194. (cond
  2195. ((assq :wrap (nth 2 info))
  2196. (let ((name (or (cdr (assq :wrap (nth 2 info))) "results")))
  2197. (funcall wrap (concat "#+begin_" name)
  2198. (concat "#+end_" (car (split-string name)))
  2199. nil nil (concat "{{{results(@@" name ":") "@@)}}}")))
  2200. ((member "html" result-params)
  2201. (funcall wrap "#+begin_export html" "#+end_export" nil nil
  2202. "{{{results(@@html:" "@@)}}}"))
  2203. ((member "latex" result-params)
  2204. (funcall wrap "#+begin_export latex" "#+end_export" nil nil
  2205. "{{{results(@@latex:" "@@)}}}"))
  2206. ((member "org" result-params)
  2207. (goto-char beg) (when (org-at-table-p) (org-cycle))
  2208. (funcall wrap "#+begin_src org" "#+end_src" nil nil
  2209. "{{{results(src_org{" "})}}}"))
  2210. ((member "code" result-params)
  2211. (let ((lang (or lang "none")))
  2212. (funcall wrap (format "#+begin_src %s%s" lang results-switches)
  2213. "#+end_src" nil nil
  2214. (format "{{{results(src_%s[%s]{" lang results-switches)
  2215. "})}}}")))
  2216. ((member "raw" result-params)
  2217. (goto-char beg) (when (org-at-table-p) (org-cycle)))
  2218. ((or (member "drawer" result-params)
  2219. ;; Stay backward compatible with <7.9.2
  2220. (member "wrap" result-params))
  2221. (goto-char beg) (when (org-at-table-p) (org-cycle))
  2222. (funcall wrap ":results:" ":end:" 'no-escape nil
  2223. "{{{results(" ")}}}"))
  2224. ((and inline (member "file" result-params))
  2225. (funcall wrap nil nil nil nil "{{{results(" ")}}}"))
  2226. ((and (not (funcall tabulablep result))
  2227. (not (member "file" result-params)))
  2228. (let ((org-babel-inline-result-wrap
  2229. ;; Hard code {{{results(...)}}} on top of
  2230. ;; customization.
  2231. (format "{{{results(%s)}}}"
  2232. org-babel-inline-result-wrap)))
  2233. (org-babel-examplify-region
  2234. beg end results-switches inline)))))
  2235. ;; Possibly indent results in par with #+results line.
  2236. (when (and (not inline) (numberp indent) (> indent 0)
  2237. ;; In this case `table-align' does the work
  2238. ;; for us.
  2239. (not (and (listp result)
  2240. (member "append" result-params))))
  2241. (indent-rigidly beg end indent))
  2242. (if (null result)
  2243. (if (member "value" result-params)
  2244. (message "Code block returned no value.")
  2245. (message "Code block produced no output."))
  2246. (message "Code block evaluation complete.")))
  2247. (set-marker end nil)
  2248. (when outside-scope (narrow-to-region visible-beg visible-end))
  2249. (set-marker visible-beg nil)
  2250. (set-marker visible-end nil)))))))
  2251. (defun org-babel-remove-result (&optional info keep-keyword)
  2252. "Remove the result of the current source block."
  2253. (interactive)
  2254. (let ((location (org-babel-where-is-src-block-result nil info)))
  2255. (when location
  2256. (save-excursion
  2257. (goto-char location)
  2258. (when (looking-at (concat org-babel-result-regexp ".*$"))
  2259. (delete-region
  2260. (if keep-keyword (line-beginning-position 2)
  2261. (save-excursion
  2262. (skip-chars-backward " \r\t\n")
  2263. (line-beginning-position 2)))
  2264. (progn (forward-line) (org-babel-result-end))))))))
  2265. (defun org-babel-remove-inline-result (&optional datum)
  2266. "Remove the result of the current inline-src-block or babel call.
  2267. The result must be wrapped in a `results' macro to be removed.
  2268. Leading white space is trimmed."
  2269. (interactive)
  2270. (let* ((el (or datum (org-element-context))))
  2271. (when (memq (org-element-type el) '(inline-src-block inline-babel-call))
  2272. (org-with-wide-buffer
  2273. (goto-char (org-element-property :end el))
  2274. (skip-chars-backward " \t")
  2275. (let ((result (save-excursion
  2276. (skip-chars-forward
  2277. " \t\n"
  2278. (org-element-property
  2279. :contents-end (org-element-property :parent el)))
  2280. (org-element-context))))
  2281. (when (and (eq (org-element-type result) 'macro)
  2282. (string= (org-element-property :key result) "results"))
  2283. (delete-region ; And leading whitespace.
  2284. (point)
  2285. (progn (goto-char (org-element-property :end result))
  2286. (skip-chars-backward " \t\n")
  2287. (point)))))))))
  2288. (defun org-babel-remove-result-one-or-many (x)
  2289. "Remove the result of the current source block.
  2290. If called with a prefix argument, remove all result blocks
  2291. in the buffer."
  2292. (interactive "P")
  2293. (if x
  2294. (org-babel-map-src-blocks nil (org-babel-remove-result))
  2295. (org-babel-remove-result)))
  2296. (defun org-babel-result-end ()
  2297. "Return the point at the end of the current set of results."
  2298. (cond ((looking-at-p "^[ \t]*$") (point)) ;no result
  2299. ((looking-at-p (format "^[ \t]*%s[ \t]*$" org-bracket-link-regexp))
  2300. (line-beginning-position 2))
  2301. (t
  2302. (let ((element (org-element-at-point)))
  2303. (if (memq (org-element-type element)
  2304. ;; Possible results types.
  2305. '(drawer example-block export-block fixed-width item
  2306. plain-list src-block table))
  2307. (save-excursion
  2308. (goto-char (min (point-max) ;for narrowed buffers
  2309. (org-element-property :end element)))
  2310. (skip-chars-backward " \r\t\n")
  2311. (line-beginning-position 2))
  2312. (point))))))
  2313. (defun org-babel-result-to-file (result &optional description)
  2314. "Convert RESULT into an Org link with optional DESCRIPTION.
  2315. If the `default-directory' is different from the containing
  2316. file's directory then expand relative links."
  2317. (when (stringp result)
  2318. (let ((same-directory?
  2319. (and buffer-file-name
  2320. (not (string= (expand-file-name default-directory)
  2321. (expand-file-name
  2322. (file-name-directory buffer-file-name)))))))
  2323. (format "[[file:%s]%s]"
  2324. (if (and default-directory buffer-file-name same-directory?)
  2325. (if (eq org-link-file-path-type 'adaptive)
  2326. (file-relative-name
  2327. (expand-file-name result default-directory)
  2328. (file-name-directory (buffer-file-name)))
  2329. (expand-file-name result default-directory))
  2330. result)
  2331. (if description (concat "[" description "]") "")))))
  2332. (defun org-babel-examplify-region (beg end &optional results-switches inline)
  2333. "Comment out region using the inline `==' or `: ' org example quote."
  2334. (interactive "*r")
  2335. (let ((maybe-cap
  2336. (lambda (str)
  2337. (if org-babel-uppercase-example-markers (upcase str) str))))
  2338. (if inline
  2339. (save-excursion
  2340. (goto-char beg)
  2341. (insert (format org-babel-inline-result-wrap
  2342. (delete-and-extract-region beg end))))
  2343. (let ((size (count-lines beg end)))
  2344. (save-excursion
  2345. (cond ((= size 0)) ; do nothing for an empty result
  2346. ((< size org-babel-min-lines-for-block-output)
  2347. (goto-char beg)
  2348. (dotimes (_ size)
  2349. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  2350. (t
  2351. (goto-char beg)
  2352. (insert (if results-switches
  2353. (format "%s%s\n"
  2354. (funcall maybe-cap "#+begin_example")
  2355. results-switches)
  2356. (funcall maybe-cap "#+begin_example\n")))
  2357. (let ((p (point)))
  2358. (if (markerp end) (goto-char end) (forward-char (- end beg)))
  2359. (org-escape-code-in-region p (point)))
  2360. (insert (funcall maybe-cap "#+end_example\n")))))))))
  2361. (defun org-babel-update-block-body (new-body)
  2362. "Update the body of the current code block to NEW-BODY."
  2363. (let ((element (org-element-at-point)))
  2364. (unless (eq (org-element-type element) 'src-block)
  2365. (error "Not in a source block"))
  2366. (goto-char (org-babel-where-is-src-block-head element))
  2367. (let* ((ind (org-get-indentation))
  2368. (body-start (line-beginning-position 2))
  2369. (body (org-element-normalize-string
  2370. (if (or org-src-preserve-indentation
  2371. (org-element-property :preserve-indent element))
  2372. new-body
  2373. (with-temp-buffer
  2374. (insert (org-remove-indentation new-body))
  2375. (indent-rigidly
  2376. (point-min)
  2377. (point-max)
  2378. (+ ind org-edit-src-content-indentation))
  2379. (buffer-string))))))
  2380. (delete-region body-start
  2381. (org-with-wide-buffer
  2382. (goto-char (org-element-property :end element))
  2383. (skip-chars-backward " \t\n")
  2384. (line-beginning-position)))
  2385. (goto-char body-start)
  2386. (insert body))))
  2387. (defun org-babel-merge-params (&rest plists)
  2388. "Combine all parameter association lists in PLISTS.
  2389. Later elements of PLISTS override the values of previous elements.
  2390. This takes into account some special considerations for certain
  2391. parameters when merging lists."
  2392. (let* ((results-exclusive-groups
  2393. (mapcar (lambda (group) (mapcar #'symbol-name group))
  2394. (cdr (assq 'results org-babel-common-header-args-w-values))))
  2395. (exports-exclusive-groups
  2396. (mapcar (lambda (group) (mapcar #'symbol-name group))
  2397. (cdr (assq 'exports org-babel-common-header-args-w-values))))
  2398. (merge
  2399. (lambda (exclusive-groups &rest result-params)
  2400. ;; Maintain exclusivity of mutually exclusive parameters,
  2401. ;; as defined in EXCLUSIVE-GROUPS while merging lists in
  2402. ;; RESULT-PARAMS.
  2403. (let (output)
  2404. (dolist (new-params result-params (delete-dups output))
  2405. (dolist (new-param new-params)
  2406. (dolist (exclusive-group exclusive-groups)
  2407. (when (member new-param exclusive-group)
  2408. (setq output (cl-remove-if
  2409. (lambda (o) (member o exclusive-group))
  2410. output))))
  2411. (push new-param output))))))
  2412. (variable-index 0) ;Handle positional arguments.
  2413. clearnames
  2414. params ;Final parameters list.
  2415. ;; Some keywords accept multiple values. We need to treat
  2416. ;; them specially.
  2417. vars results exports)
  2418. (dolist (plist plists)
  2419. (dolist (pair plist)
  2420. (pcase pair
  2421. (`(:var . ,value)
  2422. (let ((name (cond
  2423. ((listp value) (car value))
  2424. ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value)
  2425. (intern (match-string 1 value)))
  2426. (t nil))))
  2427. (cond
  2428. (name
  2429. (setq vars
  2430. (append (if (not (assoc name vars)) vars
  2431. (push name clearnames)
  2432. (cl-remove-if (lambda (p) (equal name (car p)))
  2433. vars))
  2434. (list (cons name pair)))))
  2435. ((and vars (nth variable-index vars))
  2436. ;; If no name is given and we already have named
  2437. ;; variables then assign to named variables in order.
  2438. (let ((name (car (nth variable-index vars))))
  2439. ;; Clear out colnames and rownames for replace vars.
  2440. (push name clearnames)
  2441. (setf (cddr (nth variable-index vars))
  2442. (concat (symbol-name name) "=" value))
  2443. (cl-incf variable-index)))
  2444. (t (error "Variable \"%s\" must be assigned a default value"
  2445. (cdr pair))))))
  2446. (`(:results . ,value)
  2447. (setq results (funcall merge
  2448. results-exclusive-groups
  2449. results
  2450. (split-string
  2451. (if (stringp value) value (eval value t))))))
  2452. (`(,(or :file :file-ext) . ,value)
  2453. ;; `:file' and `:file-ext' are regular keywords but they
  2454. ;; imply a "file" `:results' and a "results" `:exports'.
  2455. (when value
  2456. (setq results
  2457. (funcall merge results-exclusive-groups results '("file")))
  2458. (unless (or (member "both" exports)
  2459. (member "none" exports)
  2460. (member "code" exports))
  2461. (setq exports
  2462. (funcall merge
  2463. exports-exclusive-groups exports '("results"))))
  2464. (push pair params)))
  2465. (`(:exports . ,value)
  2466. (setq exports (funcall merge
  2467. exports-exclusive-groups
  2468. exports
  2469. (split-string (or value "")))))
  2470. ;; Regular keywords: any value overwrites the previous one.
  2471. (_ (setq params (cons pair (assq-delete-all (car pair) params)))))))
  2472. ;; Handle `:var' and clear out colnames and rownames for replaced
  2473. ;; variables.
  2474. (setq params (nconc (mapcar (lambda (v) (cons :var (cddr v))) vars)
  2475. params))
  2476. (dolist (name clearnames)
  2477. (dolist (param '(:colname-names :rowname-names))
  2478. (when (assq param params)
  2479. (setf (cdr (assq param params))
  2480. (cl-remove-if (lambda (pair) (equal name (car pair)))
  2481. (cdr (assq param params))))
  2482. (setq params
  2483. (cl-remove-if (lambda (pair) (and (equal (car pair) param)
  2484. (null (cdr pair))))
  2485. params)))))
  2486. ;; Handle other special keywords, which accept multiple values.
  2487. (setq params (nconc (list (cons :results (mapconcat #'identity results " "))
  2488. (cons :exports (mapconcat #'identity exports " ")))
  2489. params))
  2490. ;; Return merged params.
  2491. params))
  2492. (defun org-babel-noweb-p (params context)
  2493. "Check if PARAMS require expansion in CONTEXT.
  2494. CONTEXT may be one of :tangle, :export or :eval."
  2495. (let ((allowed-values (cl-case context
  2496. (:tangle '("yes" "tangle" "no-export" "strip-export"))
  2497. (:eval '("yes" "no-export" "strip-export" "eval"))
  2498. (:export '("yes")))))
  2499. (cl-some (lambda (v) (member v allowed-values))
  2500. (split-string (or (cdr (assq :noweb params)) "")))))
  2501. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  2502. "Expand Noweb references in the body of the current source code block.
  2503. For example the following reference would be replaced with the
  2504. body of the source-code block named `example-block'.
  2505. <<example-block>>
  2506. Note that any text preceding the <<foo>> construct on a line will
  2507. be interposed between the lines of the replacement text. So for
  2508. example if <<foo>> is placed behind a comment, then the entire
  2509. replacement text will also be commented.
  2510. This function must be called from inside of the buffer containing
  2511. the source-code block which holds BODY.
  2512. In addition the following syntax can be used to insert the
  2513. results of evaluating the source-code block named `example-block'.
  2514. <<example-block()>>
  2515. Any optional arguments can be passed to example-block by placing
  2516. the arguments inside the parenthesis following the convention
  2517. defined by `org-babel-lob'. For example
  2518. <<example-block(a=9)>>
  2519. would set the value of argument \"a\" equal to \"9\". Note that
  2520. these arguments are not evaluated in the current source-code
  2521. block but are passed literally to the \"example-block\"."
  2522. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  2523. (info (or info (org-babel-get-src-block-info 'light)))
  2524. (lang (nth 0 info))
  2525. (body (nth 1 info))
  2526. (ob-nww-start org-babel-noweb-wrap-start)
  2527. (ob-nww-end org-babel-noweb-wrap-end)
  2528. (new-body "")
  2529. (nb-add (lambda (text) (setq new-body (concat new-body text))))
  2530. index source-name evaluate prefix)
  2531. (with-temp-buffer
  2532. (setq-local org-babel-noweb-wrap-start ob-nww-start)
  2533. (setq-local org-babel-noweb-wrap-end ob-nww-end)
  2534. (insert body) (goto-char (point-min))
  2535. (setq index (point))
  2536. (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
  2537. (save-match-data (setf source-name (match-string 1)))
  2538. (save-match-data (setq evaluate (string-match "(.*)" source-name)))
  2539. (save-match-data
  2540. (setq prefix
  2541. (buffer-substring (match-beginning 0)
  2542. (save-excursion
  2543. (beginning-of-line 1) (point)))))
  2544. ;; add interval to new-body (removing noweb reference)
  2545. (goto-char (match-beginning 0))
  2546. (funcall nb-add (buffer-substring index (point)))
  2547. (goto-char (match-end 0))
  2548. (setq index (point))
  2549. (funcall
  2550. nb-add
  2551. (with-current-buffer parent-buffer
  2552. (save-restriction
  2553. (widen)
  2554. (mapconcat ;; Interpose PREFIX between every line.
  2555. #'identity
  2556. (split-string
  2557. (if evaluate
  2558. (let ((raw (org-babel-ref-resolve source-name)))
  2559. (if (stringp raw) raw (format "%S" raw)))
  2560. (or
  2561. ;; Retrieve from the Library of Babel.
  2562. (nth 2 (assoc-string source-name org-babel-library-of-babel))
  2563. ;; Return the contents of headlines literally.
  2564. (save-excursion
  2565. (when (org-babel-ref-goto-headline-id source-name)
  2566. (org-babel-ref-headline-body)))
  2567. ;; Find the expansion of reference in this buffer.
  2568. (save-excursion
  2569. (goto-char (point-min))
  2570. (let* ((name-regexp
  2571. (org-babel-named-src-block-regexp-for-name
  2572. source-name))
  2573. (comment
  2574. (string= "noweb"
  2575. (cdr (assq :comments (nth 2 info)))))
  2576. (c-wrap
  2577. (lambda (s)
  2578. ;; Comment, according to LANG mode,
  2579. ;; string S. Return new string.
  2580. (with-temp-buffer
  2581. (funcall (intern (concat lang "-mode")))
  2582. (comment-region (point)
  2583. (progn (insert s) (point)))
  2584. (org-trim (buffer-string)))))
  2585. (expand-body
  2586. (lambda (i)
  2587. ;; Expand body of code blocked
  2588. ;; represented by block info I.
  2589. (let ((b (if (org-babel-noweb-p (nth 2 i) :eval)
  2590. (org-babel-expand-noweb-references i)
  2591. (nth 1 i))))
  2592. (if (not comment) b
  2593. (let ((cs (org-babel-tangle-comment-links i)))
  2594. (concat (funcall c-wrap (car cs)) "\n"
  2595. b "\n"
  2596. (funcall c-wrap (cadr cs)))))))))
  2597. (if (re-search-forward name-regexp nil t)
  2598. ;; Found a source block named SOURCE-NAME.
  2599. ;; Assume it is unique; do not look after
  2600. ;; `:noweb-ref' header argument.
  2601. (funcall expand-body
  2602. (org-babel-get-src-block-info 'light))
  2603. ;; Though luck. We go into the long process
  2604. ;; of checking each source block and expand
  2605. ;; those with a matching Noweb reference.
  2606. (let ((expansion nil))
  2607. (org-babel-map-src-blocks nil
  2608. (let* ((info (org-babel-get-src-block-info 'light))
  2609. (parameters (nth 2 info)))
  2610. (when (equal source-name
  2611. (cdr (assq :noweb-ref parameters)))
  2612. (push (funcall expand-body info) expansion)
  2613. (push (or (cdr (assq :noweb-sep parameters))
  2614. "\n")
  2615. expansion))))
  2616. (when expansion
  2617. (mapconcat #'identity
  2618. (nreverse (cdr expansion))
  2619. ""))))))
  2620. ;; Possibly raise an error if named block doesn't exist.
  2621. (if (or org-babel-noweb-error-all-langs
  2622. (member lang org-babel-noweb-error-langs))
  2623. (error "%s could not be resolved (see \
  2624. `org-babel-noweb-error-langs')"
  2625. (org-babel-noweb-wrap source-name))
  2626. "")))
  2627. "[\n\r]")
  2628. (concat "\n" prefix))))))
  2629. (funcall nb-add (buffer-substring index (point-max))))
  2630. new-body))
  2631. (defun org-babel--script-escape-inner (str)
  2632. (let (in-single in-double backslash out)
  2633. (mapc
  2634. (lambda (ch)
  2635. (setq
  2636. out
  2637. (if backslash
  2638. (progn
  2639. (setq backslash nil)
  2640. (cond
  2641. ((and in-single (eq ch ?'))
  2642. ;; Escaped single quote inside single quoted string:
  2643. ;; emit just a single quote, since we've changed the
  2644. ;; outer quotes to double.
  2645. (cons ch out))
  2646. ((eq ch ?\")
  2647. ;; Escaped double quote
  2648. (if in-single
  2649. ;; This should be interpreted as backslash+quote,
  2650. ;; not an escape. Emit a three backslashes
  2651. ;; followed by a quote (because one layer of
  2652. ;; quoting will be stripped by `org-babel-read').
  2653. (append (list ch ?\\ ?\\ ?\\) out)
  2654. ;; Otherwise we are in a double-quoted string. Emit
  2655. ;; a single escaped quote
  2656. (append (list ch ?\\) out)))
  2657. ((eq ch ?\\)
  2658. ;; Escaped backslash: emit a single escaped backslash
  2659. (append (list ?\\ ?\\) out))
  2660. ;; Other: emit a quoted backslash followed by whatever
  2661. ;; the character was (because one layer of quoting will
  2662. ;; be stripped by `org-babel-read').
  2663. (t (append (list ch ?\\ ?\\) out))))
  2664. (cl-case ch
  2665. (?\[ (if (or in-double in-single)
  2666. (cons ?\[ out)
  2667. (cons ?\( out)))
  2668. (?\] (if (or in-double in-single)
  2669. (cons ?\] out)
  2670. (cons ?\) out)))
  2671. (?\{ (if (or in-double in-single)
  2672. (cons ?\{ out)
  2673. (cons ?\( out)))
  2674. (?\} (if (or in-double in-single)
  2675. (cons ?\} out)
  2676. (cons ?\) out)))
  2677. (?, (if (or in-double in-single)
  2678. (cons ?, out) (cons ?\s out)))
  2679. (?\' (if in-double
  2680. (cons ?\' out)
  2681. (setq in-single (not in-single)) (cons ?\" out)))
  2682. (?\" (if in-single
  2683. (append (list ?\" ?\\) out)
  2684. (setq in-double (not in-double)) (cons ?\" out)))
  2685. (?\\ (unless (or in-single in-double)
  2686. (error "Can't handle backslash outside string in `org-babel-script-escape'"))
  2687. (setq backslash t)
  2688. out)
  2689. (t (cons ch out))))))
  2690. (string-to-list str))
  2691. (when (or in-single in-double)
  2692. (error "Unterminated string in `org-babel-script-escape'"))
  2693. (apply #'string (reverse out))))
  2694. (defun org-babel-script-escape (str &optional force)
  2695. "Safely convert tables into elisp lists."
  2696. (unless (stringp str)
  2697. (error "`org-babel-script-escape' expects a string"))
  2698. (let ((escaped
  2699. (cond
  2700. ((and (> (length str) 2)
  2701. (or (and (string-equal "[" (substring str 0 1))
  2702. (string-equal "]" (substring str -1)))
  2703. (and (string-equal "{" (substring str 0 1))
  2704. (string-equal "}" (substring str -1)))
  2705. (and (string-equal "(" (substring str 0 1))
  2706. (string-equal ")" (substring str -1)))))
  2707. (concat "'" (org-babel--script-escape-inner str)))
  2708. ((or force
  2709. (and (> (length str) 2)
  2710. (or (and (string-equal "'" (substring str 0 1))
  2711. (string-equal "'" (substring str -1)))
  2712. ;; We need to pass double-quoted strings
  2713. ;; through the backslash-twiddling bits, even
  2714. ;; though we don't need to change their
  2715. ;; delimiters.
  2716. (and (string-equal "\"" (substring str 0 1))
  2717. (string-equal "\"" (substring str -1))))))
  2718. (org-babel--script-escape-inner str))
  2719. (t str))))
  2720. (condition-case nil (org-babel-read escaped) (error escaped))))
  2721. (defun org-babel-read (cell &optional inhibit-lisp-eval)
  2722. "Convert the string value of CELL to a number if appropriate.
  2723. Otherwise if CELL looks like lisp (meaning it starts with a
  2724. \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
  2725. lisp, otherwise return it unmodified as a string. Optional
  2726. argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
  2727. situations in which is it not appropriate."
  2728. (cond ((not (org-string-nw-p cell)) cell)
  2729. ((org-babel--string-to-number cell))
  2730. ((and (not inhibit-lisp-eval)
  2731. (or (memq (string-to-char cell) '(?\( ?' ?` ?\[))
  2732. (string= cell "*this*")))
  2733. (eval (read cell) t))
  2734. ((eq (string-to-char cell) ?\") (read cell))
  2735. (t (org-no-properties cell))))
  2736. (defun org-babel--string-to-number (string)
  2737. "If STRING represents a number return its value.
  2738. Otherwise return nil."
  2739. (and (string-match-p "\\`-?[0-9]*\\.?[0-9]*\\'" string)
  2740. (string-to-number string)))
  2741. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  2742. "Read the results located at FILE-NAME into an elisp table.
  2743. If the table is trivial, then return it as a scalar."
  2744. (let (result)
  2745. (save-window-excursion
  2746. (with-temp-buffer
  2747. (condition-case err
  2748. (progn
  2749. (org-table-import file-name separator)
  2750. (delete-file file-name)
  2751. (setq result (mapcar (lambda (row)
  2752. (mapcar #'org-babel-string-read row))
  2753. (org-table-to-lisp))))
  2754. (error (message "Error reading results: %s" err) nil)))
  2755. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  2756. (if (consp (car result))
  2757. (if (null (cdr (car result)))
  2758. (caar result)
  2759. result)
  2760. (car result))
  2761. result))))
  2762. (defun org-babel-string-read (cell)
  2763. "Strip nested \"s from around strings."
  2764. (org-babel-read (or (and (stringp cell)
  2765. (string-match "\\\"\\(.+\\)\\\"" cell)
  2766. (match-string 1 cell))
  2767. cell) t))
  2768. (defun org-babel-chomp (string &optional regexp)
  2769. "Strip a trailing space or carriage return from STRING.
  2770. The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
  2771. can be specified as the REGEXP argument."
  2772. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  2773. (while (and (> (length string) 0)
  2774. (string-match regexp (substring string -1)))
  2775. (setq string (substring string 0 -1)))
  2776. string))
  2777. (defun org-babel-process-file-name (name &optional no-quote-p)
  2778. "Prepare NAME to be used in an external process.
  2779. If NAME specifies a remote location, the remote portion of the
  2780. name is removed, since in that case the process will be executing
  2781. remotely. The file name is then processed by `expand-file-name'.
  2782. Unless second argument NO-QUOTE-P is non-nil, the file name is
  2783. additionally processed by `shell-quote-argument'"
  2784. (let ((f (org-babel-local-file-name (expand-file-name name))))
  2785. (if no-quote-p f (shell-quote-argument f))))
  2786. (defvar org-babel-temporary-directory)
  2787. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  2788. (defvar org-babel-temporary-directory
  2789. (or (and (boundp 'org-babel-temporary-directory)
  2790. (file-exists-p org-babel-temporary-directory)
  2791. org-babel-temporary-directory)
  2792. (make-temp-file "babel-" t))
  2793. "Directory to hold temporary files created to execute code blocks.
  2794. Used by `org-babel-temp-file'. This directory will be removed on
  2795. Emacs shutdown."))
  2796. (defcustom org-babel-remote-temporary-directory "/tmp/"
  2797. "Directory to hold temporary files on remote hosts."
  2798. :group 'org-babel
  2799. :type 'string)
  2800. (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
  2801. "Call the code to parse raw string results according to RESULT-PARAMS."
  2802. (declare (indent 1)
  2803. (debug (form form &rest form)))
  2804. (org-with-gensyms (params)
  2805. `(let ((,params ,result-params))
  2806. (unless (member "none" ,params)
  2807. (if (or (member "scalar" ,params)
  2808. (member "verbatim" ,params)
  2809. (member "html" ,params)
  2810. (member "code" ,params)
  2811. (member "pp" ,params)
  2812. (member "file" ,params)
  2813. (and (or (member "output" ,params)
  2814. (member "raw" ,params)
  2815. (member "org" ,params)
  2816. (member "drawer" ,params))
  2817. (not (member "table" ,params))))
  2818. ,scalar-form
  2819. ,@table-forms)))))
  2820. (def-edebug-spec org-babel-result-cond (form form body))
  2821. (defun org-babel-temp-file (prefix &optional suffix)
  2822. "Create a temporary file in the `org-babel-temporary-directory'.
  2823. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  2824. value of `temporary-file-directory' temporarily set to the value
  2825. of `org-babel-temporary-directory'."
  2826. (if (file-remote-p default-directory)
  2827. (let ((prefix
  2828. (concat (file-remote-p default-directory)
  2829. (expand-file-name
  2830. prefix org-babel-remote-temporary-directory))))
  2831. (make-temp-file prefix nil suffix))
  2832. (let ((temporary-file-directory
  2833. (or (and (boundp 'org-babel-temporary-directory)
  2834. (file-exists-p org-babel-temporary-directory)
  2835. org-babel-temporary-directory)
  2836. temporary-file-directory)))
  2837. (make-temp-file prefix nil suffix))))
  2838. (defun org-babel-remove-temporary-directory ()
  2839. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  2840. (when (and (boundp 'org-babel-temporary-directory)
  2841. (file-exists-p org-babel-temporary-directory))
  2842. ;; taken from `delete-directory' in files.el
  2843. (condition-case nil
  2844. (progn
  2845. (mapc (lambda (file)
  2846. ;; This test is equivalent to
  2847. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  2848. ;; but more efficient
  2849. (if (eq t (car (file-attributes file)))
  2850. (delete-directory file)
  2851. (delete-file file)))
  2852. ;; We do not want to delete "." and "..".
  2853. (directory-files org-babel-temporary-directory 'full
  2854. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  2855. (delete-directory org-babel-temporary-directory))
  2856. (error
  2857. (message "Failed to remove temporary Org-babel directory %s"
  2858. (if (boundp 'org-babel-temporary-directory)
  2859. org-babel-temporary-directory
  2860. "[directory not defined]"))))))
  2861. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  2862. (defun org-babel-one-header-arg-safe-p (pair safe-list)
  2863. "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
  2864. For the format of SAFE-LIST, see `org-babel-safe-header-args'."
  2865. (and (consp pair)
  2866. (keywordp (car pair))
  2867. (stringp (cdr pair))
  2868. (or
  2869. (memq (car pair) safe-list)
  2870. (let ((entry (assq (car pair) safe-list)))
  2871. (and entry
  2872. (consp entry)
  2873. (cond ((functionp (cdr entry))
  2874. (funcall (cdr entry) (cdr pair)))
  2875. ((listp (cdr entry))
  2876. (member (cdr pair) (cdr entry)))
  2877. (t nil)))))))
  2878. (defun org-babel-generate-file-param (src-name params)
  2879. "Calculate the filename for source block results.
  2880. The directory is calculated from the :output-dir property of the
  2881. source block; if not specified, use the current directory.
  2882. If the source block has a #+NAME and the :file parameter does not
  2883. contain any period characters, then the :file parameter is
  2884. treated as an extension, and the output file name is the
  2885. concatenation of the directory (as calculated above), the block
  2886. name, a period, and the parameter value as a file extension.
  2887. Otherwise, the :file parameter is treated as a full file name,
  2888. and the output file name is the directory (as calculated above)
  2889. plus the parameter value."
  2890. (let* ((file-cons (assq :file params))
  2891. (file-ext-cons (assq :file-ext params))
  2892. (file-ext (cdr-safe file-ext-cons))
  2893. (dir (cdr-safe (assq :output-dir params)))
  2894. fname)
  2895. ;; create the output-dir if it does not exist
  2896. (when dir
  2897. (make-directory dir t))
  2898. (if file-cons
  2899. ;; :file given; add :output-dir if given
  2900. (when dir
  2901. (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons))))
  2902. ;; :file not given; compute from name and :file-ext if possible
  2903. (when (and src-name file-ext)
  2904. (if dir
  2905. (setq fname (concat (file-name-as-directory (or dir ""))
  2906. src-name "." file-ext))
  2907. (setq fname (concat src-name "." file-ext)))
  2908. (setq params (cons (cons :file fname) params))))
  2909. params))
  2910. (defun org-babel-graphical-output-file (params)
  2911. "File where a babel block should send graphical output, per PARAMS.
  2912. Return nil if no graphical output is expected. Raise an error if
  2913. the output file is ill-defined."
  2914. (let ((file (cdr (assq :file params))))
  2915. (cond (file (and (member "graphics" (cdr (assq :result-params params)))
  2916. file))
  2917. ((assq :file-ext params)
  2918. (user-error ":file-ext given but no :file generated; did you forget \
  2919. to name a block?"))
  2920. (t (user-error "No :file header argument given; cannot create \
  2921. graphical result")))))
  2922. (defun org-babel-make-language-alias (new old)
  2923. "Make source blocks of type NEW aliases for those of type OLD.
  2924. NEW and OLD should be strings. This function should be called
  2925. after the babel API for OLD-type source blocks is fully defined.
  2926. Callers of this function will probably want to add an entry to
  2927. `org-src-lang-modes' as well."
  2928. (dolist (fn '("execute" "expand-body" "prep-session"
  2929. "variable-assignments" "load-session"))
  2930. (let ((sym (intern-soft (concat "org-babel-" fn ":" old))))
  2931. (when (and sym (fboundp sym))
  2932. (defalias (intern (concat "org-babel-" fn ":" new)) sym))))
  2933. ;; Technically we don't need a `dolist' for just one variable, but
  2934. ;; we keep it for symmetry/ease of future expansion.
  2935. (dolist (var '("default-header-args"))
  2936. (let ((sym (intern-soft (concat "org-babel-" var ":" old))))
  2937. (when (and sym (boundp sym))
  2938. (defvaralias (intern (concat "org-babel-" var ":" new)) sym)))))
  2939. (defun org-babel-strip-quotes (string)
  2940. "Strip \\\"s from around a string, if applicable."
  2941. (org-unbracket-string "\"" "\"" string))
  2942. (provide 'ob-core)
  2943. ;; Local variables:
  2944. ;; generated-autoload-file: "org-loaddefs.el"
  2945. ;; End:
  2946. ;;; ob-core.el ends here