ob-core.el 119 KB

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