ein-cell.el 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. ;;; ein-cell.el --- Cell module
  2. ;; Copyright (C) 2012- Takafumi Arakaki
  3. ;; Author: Takafumi Arakaki <aka.tkf at gmail.com>
  4. ;; This file is NOT part of GNU Emacs.
  5. ;; ein-cell.el is free software: you can redistribute it and/or modify
  6. ;; it under the terms of the GNU General Public License as published by
  7. ;; the Free Software Foundation, either version 3 of the License, or
  8. ;; (at your option) any later version.
  9. ;; ein-cell.el is distributed in the hope that it will be useful,
  10. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. ;; GNU General Public License for more details.
  13. ;; You should have received a copy of the GNU General Public License
  14. ;; along with ein-cell.el. If not, see <http://www.gnu.org/licenses/>.
  15. ;;; Commentary:
  16. ;; Implementation note. Current implementation of cell has redundant
  17. ;; and not-guaranteed-to-be consistent information: `element' and
  18. ;; `ein:$node'. This part must be moved to ein-node.el module to
  19. ;; make it well capsuled.
  20. ;; IPython has cell.js, codecell.js and textcell.js.
  21. ;; But let's start with one file.
  22. ;;; Code:
  23. (eval-when-compile (require 'cl))
  24. (require 'eieio)
  25. (require 'ansi-color)
  26. (require 'comint)
  27. (require 'ein-core)
  28. (require 'ein-log)
  29. (require 'ein-node)
  30. (require 'ein-kernel)
  31. (require 'ein-output-area)
  32. ;;; Faces
  33. (defface ein:cell-input-prompt
  34. '((t :inherit header-line))
  35. "Face for cell input prompt"
  36. :group 'ein)
  37. (defface ein:cell-input-area
  38. '((((class color) (background light))
  39. :background "honeydew1")
  40. (((class color) (background dark))
  41. :background "#383838"))
  42. "Face for cell input area"
  43. :group 'ein)
  44. (defface ein:cell-heading-1
  45. '((t :height 1.1 :inherit ein:cell-heading-2))
  46. "Face for level 1 heading."
  47. :group 'ein)
  48. (defface ein:cell-heading-2
  49. '((t :height 1.1 :inherit ein:cell-heading-3))
  50. "Face for level 2 heading."
  51. :group 'ein)
  52. (defface ein:cell-heading-3
  53. '((t :height 1.1 :inherit ein:cell-heading-4))
  54. "Face for level 3 heading."
  55. :group 'ein)
  56. (defface ein:cell-heading-4
  57. '((t :height 1.1 :inherit ein:cell-heading-5))
  58. "Face for level 4 heading."
  59. :group 'ein)
  60. (defface ein:cell-heading-5
  61. '((t :height 1.1 :inherit ein:cell-heading-6))
  62. "Face for level 5 heading."
  63. :group 'ein)
  64. (defface ein:cell-heading-6
  65. '((t :weight bold :inherit (variable-pitch ein:cell-input-area)))
  66. "Face for level 6 heading."
  67. :group 'ein)
  68. (defface ein:cell-output-prompt
  69. '((t :inherit header-line))
  70. "Face for cell output prompt"
  71. :group 'ein)
  72. (defface ein:cell-output-stderr
  73. '((((class color) (background light))
  74. :background "PeachPuff")
  75. (((class color) (background dark))
  76. :background "#8c5353"))
  77. "Face for stderr cell output"
  78. :group 'ein)
  79. (defface ein:pos-tip-face
  80. '((t (:inherit 'popup-tip-face)))
  81. "Face for tooltip when using pos-tip backend."
  82. :group 'ein)
  83. ;;; Customization
  84. (defcustom ein:cell-traceback-level 1
  85. "Number of traceback stack to show.
  86. Hidden tracebacks are not discarded. You can always view them
  87. using the command `ein:notebook-view-traceback'."
  88. :type '(choice (integer :tag "Number of stack to show" 1)
  89. (const :tag "Show all traceback" nil))
  90. :group 'ein)
  91. (defcustom ein:cell-max-num-outputs nil
  92. "Number of maximum outputs to be shown by default.
  93. To view full output, use `ein:notebook-show-in-shared-output'."
  94. :type '(choice (integer :tag "Number of outputs to show" 5)
  95. (const :tag "Show all traceback" nil))
  96. :group 'ein)
  97. (defcustom ein:cell-autoexec-prompt "⚡"
  98. "String shown in the cell prompt when the auto-execution flag
  99. is on. See also `ein:connect-aotoexec-lighter'."
  100. :type 'string
  101. :group 'ein)
  102. (defcustom ein:slice-image nil
  103. "[EXPERIMENTAL] When non-`nil', use `insert-sliced-image' when
  104. drawing images. If it is of the form of ``(ROWS COLS)``, it is
  105. passed to the corresponding arguments of `insert-sliced-image'.
  106. .. FIXME: ROWS and COLS must be determined dynamically by measuring
  107. the size of iamge and Emacs window.
  108. See also: https://github.com/tkf/emacs-ipython-notebook/issues/94"
  109. :type 'boolean
  110. :group 'ein)
  111. ;;; EIEIO related utils
  112. (defmacro ein:oset-if-empty (obj slot value)
  113. `(unless (and (slot-boundp ,obj ,slot) (oref ,obj ,slot))
  114. (oset ,obj ,slot ,value)))
  115. (defmacro ein:oref-safe (obj slot)
  116. `(when (slot-boundp ,obj ,slot)
  117. (oref ,obj ,slot)))
  118. ;;; Utils
  119. (defun ein:insert-image (&rest args)
  120. (let ((img (apply #'create-image args)))
  121. (if ein:slice-image
  122. (destructuring-bind (&optional rows cols)
  123. (when (listp ein:slice-image) ein:slice-image)
  124. (insert-sliced-image img nil nil (or rows 20) cols))
  125. (insert-image img))))
  126. ;;; Cell classes
  127. (defclass ein:basecell ()
  128. ((cell-type :initarg :cell-type :type string)
  129. (read-only :initarg :read-only :initform nil :type boolean)
  130. (ewoc :initarg :ewoc :type ewoc)
  131. (element :initarg :element :initform nil :type list
  132. :documentation "ewoc nodes")
  133. (element-names :initarg :element-names)
  134. (input :initarg :input :type string
  135. :documentation "Place to hold data until it is rendered via `ewoc'.")
  136. (outputs :initarg :outputs :initform nil :type list)
  137. (events :initarg :events :type ein:events)
  138. (cell-id :initarg :cell-id :initform (ein:utils-uuid) :type string))
  139. "Notebook cell base class")
  140. (defclass ein:codecell (ein:basecell)
  141. ((cell-type :initarg :cell-type :initform "code")
  142. (kernel :initarg :kernel :type ein:$kernel)
  143. (element-names :initform (:prompt :input :output :footer))
  144. (input-prompt-number :initarg :input-prompt-number
  145. :documentation "\
  146. Integer or \"*\" (running state).
  147. Implementation note:
  148. Typed `:input-prompt-number' becomes a problem when reading a
  149. notebook that saved "*". So don't add `:type'!")
  150. (collapsed :initarg :collapsed :initform nil :type boolean)
  151. (running :initarg :running :initform nil :type boolean)
  152. (dynamic :initarg :dynamic :initform nil :type boolean
  153. :documentation "\
  154. Whether cell output is evaluated dynamically or not.
  155. Only Emacs lisp type output data will be affected by this
  156. slot (Javascript will not be evaluated). This value must be set
  157. to `t' when executing cell. See `ein:notebook-execute-cell'.
  158. In the implantation of IPython web client it is passed around via
  159. argument, but since it is difficult to pass argument to EWOC
  160. pretty printer, `ein:codecell' instance holds this setting in a
  161. slot.")
  162. (autoexec :initarg :autoexec :initform nil :type boolean
  163. :documentation "Auto-execution flag.
  164. This cell is executed when the connected buffer is saved,
  165. provided that (1) this flag is `t' and (2) corresponding
  166. auto-execution mode flag in the connected buffer is `t'.")))
  167. (defclass ein:textcell (ein:basecell)
  168. ((cell-type :initarg :cell-type :initform "text")
  169. (element-names :initform (:prompt :input :footer))))
  170. (defclass ein:htmlcell (ein:textcell)
  171. ((cell-type :initarg :cell-type :initform "html")))
  172. (defclass ein:markdowncell (ein:textcell)
  173. ((cell-type :initarg :cell-type :initform "markdown")))
  174. (defclass ein:rawcell (ein:textcell)
  175. ((cell-type :initarg :cell-type :initform "raw")))
  176. (defclass ein:headingcell (ein:textcell)
  177. ((cell-type :initarg :cell-type :initform "heading")
  178. (level :initarg :level :initform 1)))
  179. ;;; Cell factory
  180. (defun ein:cell-class-from-type (type)
  181. (ein:case-equal type
  182. (("code") 'ein:codecell)
  183. (("text") 'ein:textcell)
  184. (("html") 'ein:htmlcell)
  185. (("markdown") 'ein:markdowncell)
  186. (("raw") 'ein:rawcell)
  187. (("heading") 'ein:headingcell)
  188. ;; Defined in ein-shared-output.el:
  189. (("shared-output") 'ein:shared-output-cell)
  190. (t (error "No cell type called %S" type))))
  191. (defun ein:cell-from-type (type &rest args)
  192. (apply (ein:cell-class-from-type type) "Cell" args))
  193. (defun ein:cell-from-json (data &rest args)
  194. (ein:cell-init (apply #'ein:cell-from-type
  195. (plist-get data :cell_type) args) data))
  196. (defmethod ein:cell-init ((cell ein:codecell) data)
  197. (ein:oset-if-empty cell :outputs (plist-get data :outputs))
  198. (ein:oset-if-empty cell :input (plist-get data :input))
  199. (ein:aif (plist-get data :prompt_number)
  200. (ein:oset-if-empty cell :input-prompt-number it))
  201. (ein:oset-if-empty cell :collapsed
  202. (let ((v (plist-get data :collapsed)))
  203. (if (eql v json-false) nil v)))
  204. cell)
  205. (defmethod ein:cell-init ((cell ein:textcell) data)
  206. (ein:aif (plist-get data :source)
  207. (oset cell :input it))
  208. cell)
  209. (defmethod ein:cell-init ((cell ein:headingcell) data)
  210. (call-next-method)
  211. (ein:aif (plist-get data :level)
  212. (oset cell :level it))
  213. cell)
  214. (defmethod ein:cell-convert ((cell ein:basecell) type)
  215. (let ((new (ein:cell-from-type type)))
  216. ;; copy attributes
  217. (loop for k in '(:read-only :ewoc)
  218. do (set-slot-value new k (slot-value cell k)))
  219. ;; copy input
  220. (oset new :input (if (ein:cell-active-p cell)
  221. (ein:cell-get-text cell)
  222. (oref cell :input)))
  223. ;; copy output when the new cell has it
  224. (when (memq :output (oref new :element-names))
  225. (oset new :outputs (mapcar 'identity (oref cell :outputs))))
  226. new))
  227. (defmethod ein:cell-convert ((cell ein:codecell) type)
  228. (let ((new (call-next-method)))
  229. (when (and (ein:codecell-child-p new)
  230. (slot-boundp cell :kernel))
  231. (oset new :kernel (oref cell :kernel)))
  232. new))
  233. (defmethod ein:cell-convert ((cell ein:headingcell) type)
  234. (let ((new (call-next-method)))
  235. (when (ein:headingcell-p new)
  236. (oset new :level (oref cell :level)))
  237. new))
  238. (defmethod ein:cell-copy ((cell ein:basecell))
  239. (ein:cell-convert cell (oref cell :cell-type)))
  240. (defmethod ein:cell-convert-inplace ((cell ein:basecell) type)
  241. "Convert CELL to TYPE and redraw corresponding ewoc nodes."
  242. (let ((new (ein:cell-convert cell type)))
  243. ;; copy element attribute
  244. (loop for k in (oref new :element-names)
  245. with old-element = (oref cell :element)
  246. do (oset new :element
  247. (plist-put (oref new :element) k
  248. (plist-get old-element k))))
  249. ;; setting ewoc nodes
  250. (loop for en in (ein:cell-all-element cell)
  251. for node = (ewoc-data en)
  252. do (setf (ein:$node-data node) new))
  253. (let ((inhibit-read-only t)
  254. (buffer-undo-list t)) ; disable undo recording
  255. ;; delete ewoc nodes that is not copied
  256. (apply
  257. #'ewoc-delete (oref new :ewoc)
  258. (apply
  259. #'append
  260. (loop for name in (oref cell :element-names)
  261. unless (memq name (oref new :element-names))
  262. collect (let ((ens (ein:cell-element-get cell name)))
  263. (if (listp ens) ens (list ens))))))
  264. ;; draw ewoc node
  265. (loop with ewoc = (oref new :ewoc)
  266. for en in (ein:cell-all-element new)
  267. do (ewoc-invalidate ewoc en)))
  268. new))
  269. (defmethod ein:cell-change-level ((cell ein:headingcell) level)
  270. (assert (integerp level))
  271. (let ((inhibit-read-only t)
  272. (buffer-undo-list t)) ; disable undo recording
  273. (oset cell :level level)
  274. ;; draw ewoc node
  275. (loop with ewoc = (oref cell :ewoc)
  276. for en in (ein:cell-all-element cell)
  277. do (ewoc-invalidate ewoc en))))
  278. ;;; Getter/setter
  279. (defmethod ein:cell-num-outputs ((cell ein:codecell))
  280. (length (oref cell :outputs)))
  281. (defmethod ein:cell-num-outputs ((cell ein:textcell))
  282. 0)
  283. (defmethod ein:cell-element-get ((cell ein:basecell) prop &rest args)
  284. "Return ewoc node named PROP in CELL.
  285. If PROP is `:output' a list of ewoc nodes is returned.
  286. A specific node can be specified using optional ARGS."
  287. (if (memq prop (oref cell :element-names))
  288. (plist-get (oref cell :element) prop)
  289. (error "PROP %s is not supported." prop)))
  290. (defmethod ein:cell-element-get ((cell ein:codecell) prop &optional index)
  291. (let ((element (oref cell :element)))
  292. (if index
  293. (progn
  294. (assert (eql prop :output))
  295. (nth index (plist-get element prop)))
  296. (case prop
  297. (:after-input
  298. (ein:aif (nth 0 (plist-get element :output))
  299. it
  300. (plist-get element :footer)))
  301. (:after-output (plist-get element :footer))
  302. (:before-input (plist-get element :prompt))
  303. (:before-output (plist-get element :input))
  304. (:last-output
  305. (ein:aif (plist-get element :output)
  306. (car (last it))
  307. (plist-get element :input)))
  308. (t (call-next-method))))))
  309. (defmethod ein:cell-element-get ((cell ein:textcell) prop)
  310. (let ((element (oref cell :element)))
  311. (case prop
  312. (:after-input (plist-get element :footer))
  313. (:before-input (plist-get element :prompt))
  314. (t (call-next-method)))))
  315. (defmethod ein:cell-all-element ((cell ein:basecell))
  316. (list (ein:cell-element-get cell :prompt)
  317. (ein:cell-element-get cell :input)
  318. (ein:cell-element-get cell :footer)))
  319. (defmethod ein:cell-all-element ((cell ein:codecell))
  320. (append (call-next-method)
  321. (ein:cell-element-get cell :output)))
  322. (defmethod ein:cell-language ((cell ein:basecell))
  323. "Programming language used for CELL.
  324. Return language name as a string or `nil' when not defined.
  325. \(fn cell)")
  326. (defmethod ein:cell-language ((cell ein:codecell)) nil "python")
  327. (defmethod ein:cell-language ((cell ein:markdowncell)) nil "markdown")
  328. (defmethod ein:cell-language ((cell ein:htmlcell)) nil "html")
  329. (defmethod ein:cell-language ((cell ein:rawcell)) nil "rst")
  330. ;; EWOC
  331. (defun ein:cell-make-element (make-node num-outputs)
  332. (let ((buffer-undo-list t)) ; disable undo recording
  333. (list
  334. :prompt (funcall make-node 'prompt)
  335. :input (funcall make-node 'input)
  336. :output (loop for i from 0 below num-outputs
  337. collect (funcall make-node 'output i))
  338. :footer (funcall make-node 'footer))))
  339. (defmethod ein:cell-enter-last ((cell ein:basecell))
  340. (let* ((ewoc (oref cell :ewoc))
  341. ;; Use `cell' as data for ewoc. Use the whole cell data even
  342. ;; if it is not used, to access it from the notebook buffer.
  343. ;; It is equivalent to `this.element.data("cell", this)' in
  344. ;; IPython.Cell (see cell.js).
  345. (make-node
  346. (lambda (&rest path)
  347. (ewoc-enter-last ewoc (ein:node-new `(cell ,@path) cell))))
  348. (element (ein:cell-make-element make-node
  349. (ein:cell-num-outputs cell))))
  350. (oset cell :element element)
  351. cell))
  352. (defmethod ein:cell-enter-first ((cell ein:basecell))
  353. (let* ((ewoc (oref cell :ewoc))
  354. (node nil)
  355. (make-node
  356. (lambda (&rest path)
  357. (let ((ewoc-data (ein:node-new `(cell ,@path) cell)))
  358. (setq node
  359. (if node
  360. (ewoc-enter-after ewoc node ewoc-data)
  361. (ewoc-enter-first ewoc ewoc-data))))))
  362. (element (ein:cell-make-element make-node
  363. (ein:cell-num-outputs cell))))
  364. (oset cell :element element)
  365. cell))
  366. (defmethod ein:cell-insert-below ((base-cell ein:basecell) other-cell)
  367. (let* ((ewoc (oref base-cell :ewoc))
  368. (node (ein:cell-element-get base-cell :footer))
  369. (make-node
  370. (lambda (&rest path)
  371. (setq node (ewoc-enter-after
  372. ewoc node (ein:node-new `(cell ,@path) other-cell)))))
  373. (element (ein:cell-make-element make-node
  374. (ein:cell-num-outputs other-cell))))
  375. (oset other-cell :element element)
  376. other-cell))
  377. (defun ein:cell-pp (path data)
  378. (case (car path)
  379. (prompt (ein:cell-insert-prompt data))
  380. (input (ein:cell-insert-input data))
  381. (output (ein:cell-insert-output (cadr path) data))
  382. (footer (ein:cell-insert-footer data))))
  383. (defmethod ein:cell-insert-prompt ((cell ein:codecell))
  384. "Insert prompt of the CELL in the buffer.
  385. Called from ewoc pretty printer via `ein:cell-pp'."
  386. ;; Newline is inserted in `ein:cell-insert-input'.
  387. (ein:insert-read-only
  388. (concat
  389. (format "In [%s]:" (or (ein:oref-safe cell :input-prompt-number) " "))
  390. (when (oref cell :autoexec) " %s" ein:cell-autoexec-prompt))
  391. 'font-lock-face 'ein:cell-input-prompt))
  392. (defmethod ein:cell-insert-prompt ((cell ein:textcell))
  393. (ein:insert-read-only
  394. (format "%s:" (oref cell :cell-type))
  395. 'font-lock-face 'ein:cell-input-prompt))
  396. (defmethod ein:cell-insert-prompt ((cell ein:headingcell))
  397. (ein:insert-read-only
  398. (format "h%s:" (oref cell :level))
  399. 'font-lock-face 'ein:cell-input-prompt))
  400. (defmethod ein:cell-insert-input ((cell ein:basecell))
  401. "Insert input of the CELL in the buffer.
  402. Called from ewoc pretty printer via `ein:cell-pp'."
  403. (let ((start (1+ (point))))
  404. ;; Newlines must allow insertion before/after its position.
  405. (insert (propertize "\n" 'read-only t 'rear-nonsticky t)
  406. (or (ein:oref-safe cell :input) "")
  407. (propertize "\n" 'read-only t))
  408. ;; Highlight background using overlay.
  409. (let ((ol (make-overlay start (point))))
  410. (overlay-put ol 'face (ein:cell-get-input-area-face cell))
  411. ;; `evaporate' = `t': Overlay is deleted when the region become empty.
  412. (overlay-put ol 'evaporate t))))
  413. (defmethod ein:cell-get-input-area-face ((cell ein:basecell))
  414. "Return the face (symbol) for input area."
  415. 'ein:cell-input-area)
  416. (defmethod ein:cell-get-input-area-face ((cell ein:headingcell))
  417. (intern (format "ein:cell-heading-%d" (oref cell :level))))
  418. (defun ein:cell-insert-output (index cell)
  419. "Insert INDEX-th output of the CELL in the buffer.
  420. Called from ewoc pretty printer via `ein:cell-pp'."
  421. (if (or (oref cell :collapsed)
  422. (and ein:cell-max-num-outputs
  423. (>= index ein:cell-max-num-outputs)))
  424. (progn
  425. (when (and (not (oref cell :collapsed))
  426. (= index ein:cell-max-num-outputs)
  427. (> (point) (point-at-bol)))
  428. ;; The first output which exceeds `ein:cell-max-num-outputs'.
  429. (ein:insert-read-only "\n"))
  430. (ein:insert-read-only "."))
  431. (let ((out (nth index (oref cell :outputs))))
  432. ;; Handle newline for previous stream output.
  433. ;; In IPython JS, it is handled in `append_stream' because JS
  434. ;; does not need to care about newline (DOM does it for JS).
  435. ;; FIXME: Maybe I should abstract ewoc in some way and get rid
  436. ;; of this.
  437. (let ((last-out (and (> index 0)
  438. (nth (1- index) (oref cell :outputs)))))
  439. ;; If previous output is stream type, consider adding newline
  440. (when (and last-out
  441. (equal (plist-get last-out :output_type) "stream"))
  442. ;; Check if the last output is from the same stream.
  443. ;; If so, do *NOT* insert newline, otherwise insert newline.
  444. (unless (and (equal (plist-get out :output_type) "stream")
  445. (equal (plist-get out :stream)
  446. (plist-get last-out :stream)))
  447. (ein:cell-append-stream-text-fontified "\n" last-out))))
  448. ;; Finally insert real data
  449. (ein:case-equal (plist-get out :output_type)
  450. (("pyout") (ein:cell-append-pyout cell out))
  451. (("pyerr") (ein:cell-append-pyerr cell out))
  452. (("display_data") (ein:cell-append-display-data cell out))
  453. (("stream") (ein:cell-append-stream cell out))))))
  454. (defmethod ein:cell-insert-footer ((cell ein:basecell))
  455. "Insert footer (just a new line) of the CELL in the buffer.
  456. Called from ewoc pretty printer via `ein:cell-pp'."
  457. (ein:insert-read-only "\n"))
  458. (defmethod ein:cell-insert-footer ((cell ein:codecell))
  459. (if (or (oref cell :collapsed)
  460. (and ein:cell-max-num-outputs
  461. (> (ein:cell-num-outputs cell) ein:cell-max-num-outputs)))
  462. ;; Add a newline after the last ".".
  463. (ein:insert-read-only "\n")
  464. (let ((last-out (car (last (oref cell :outputs)))))
  465. (when (equal (plist-get last-out :output_type) "stream")
  466. (ein:cell-append-stream-text-fontified "\n" last-out))))
  467. (call-next-method))
  468. (defun ein:cell-node-p (node &optional element-name)
  469. (let* ((path (ein:$node-path node))
  470. (p0 (car path))
  471. (p1 (cadr path))
  472. (cell (ein:$node-path node)))
  473. (and cell (eql p0 'cell) (or (not element-name) (eql p1 element-name)))))
  474. (defun ein:cell-ewoc-node-p (ewoc-node &optional element-name)
  475. (ein:cell-node-p (ewoc-data ewoc-node) element-name))
  476. (defun ein:cell-from-ewoc-node (ewoc-node)
  477. (ein:aand ewoc-node (ewoc-data it) (ein:$node-data it)))
  478. (defmethod ein:cell-input-pos-min ((cell ein:basecell))
  479. "Return editable minimum point in the input area of the CELL.
  480. If the input area of the CELL does not exist, return `nil'"
  481. (let* ((input-node (ein:cell-element-get cell :input)))
  482. ;; 1+ for skipping newline
  483. (when input-node (1+ (ewoc-location input-node)))))
  484. (defmethod ein:cell-input-pos-max ((cell ein:basecell))
  485. "Return editable maximum point in the input area of the CELL.
  486. If the input area of the CELL does not exist, return `nil'"
  487. (let* ((ewoc (oref cell :ewoc))
  488. (input-node (ein:cell-element-get cell :input)))
  489. ;; 1- for skipping newline
  490. (when input-node (1- (ewoc-location (ewoc-next ewoc input-node))))))
  491. (defmethod ein:cell-get-text ((cell ein:basecell))
  492. "Grab text in the input area of the cell at point."
  493. (if (ein:cell-active-p cell)
  494. (let* ((beg (ein:cell-input-pos-min cell))
  495. (end (ein:cell-input-pos-max cell)))
  496. (buffer-substring beg end))
  497. (oref cell :input)))
  498. (defmethod ein:cell-set-text ((cell ein:basecell) text)
  499. (let* ((input-node (ein:cell-element-get cell :input))
  500. (ewoc (oref cell :ewoc))
  501. ;; 1+/1- is for skipping newline
  502. (beg (1+ (ewoc-location input-node)))
  503. (end (1- (ewoc-location (ewoc-next ewoc input-node)))))
  504. (save-excursion
  505. ;; probably it is better to set :input and update via ewoc?
  506. (goto-char beg)
  507. (delete-region beg end)
  508. (insert text))))
  509. (defmethod ein:cell-save-text ((cell ein:basecell))
  510. (oset cell :input (ein:cell-get-text cell)))
  511. (defmethod ein:cell-deactivate ((cell ein:basecell))
  512. (oset cell :element nil)
  513. cell)
  514. (defmethod ein:cell-active-p ((cell ein:basecell))
  515. (oref cell :element))
  516. (defmethod ein:cell-running-set ((cell ein:codecell) running)
  517. ;; FIXME: change the appearance of the cell
  518. (oset cell :running running))
  519. (defmethod ein:cell-set-collapsed ((cell ein:codecell) collapsed)
  520. "Set `:collapsed' slot of CELL and invalidate output ewoc nodes."
  521. (unless (eq (oref cell :collapsed) collapsed)
  522. (oset cell :collapsed collapsed)
  523. (apply #'ewoc-invalidate
  524. (oref cell :ewoc)
  525. (ein:cell-element-get cell :output))))
  526. (defmethod ein:cell-collapse ((cell ein:codecell))
  527. (ein:cell-set-collapsed cell t))
  528. (defmethod ein:cell-expand ((cell ein:codecell))
  529. (ein:cell-set-collapsed cell nil))
  530. (defmethod ein:cell-toggle-output ((cell ein:codecell))
  531. "Toggle `:collapsed' slot of CELL and invalidate output ewoc nodes."
  532. (ein:cell-set-collapsed cell (not (oref cell :collapsed))))
  533. (defmethod ein:cell-invalidate-prompt ((cell ein:codecell))
  534. (let ((inhibit-read-only t)
  535. (buffer-undo-list t)) ; disable undo recording
  536. (ewoc-invalidate (oref cell :ewoc)
  537. (ein:cell-element-get cell :prompt))))
  538. (defmethod ein:cell-set-input-prompt ((cell ein:codecell) &optional number)
  539. (oset cell :input-prompt-number number)
  540. (ein:cell-invalidate-prompt cell))
  541. (defmethod ein:cell-set-autoexec ((cell ein:codecell) bool)
  542. "Set auto-execution flag of CELL to BOOL and invalidate the
  543. prompt EWOC node."
  544. (oset cell :autoexec bool)
  545. (ein:cell-invalidate-prompt cell))
  546. (defmethod ein:cell-autoexec-p ((cell ein:basecell))
  547. "Auto-execution flag set to CELL.
  548. Return `nil' always for non-code cells."
  549. nil)
  550. (defmethod ein:cell-autoexec-p ((cell ein:codecell))
  551. (oref cell :autoexec))
  552. (defmethod ein:cell-toggle-autoexec ((cell ein:codecell))
  553. "Toggle auto-execution flag of CELL to BOOL and invalidate the
  554. prompt EWOC node."
  555. (ein:cell-set-autoexec cell (not (ein:cell-autoexec-p cell))))
  556. (defmethod ein:cell-goto ((cell ein:basecell) &optional relpos prop)
  557. "Go to the input area of the given CELL.
  558. RELPOS is the position relative to the input area. Default is 0.
  559. PROP is a name of cell element. Default is `:input'.
  560. \(fn cell relpos prop)"
  561. (unless relpos (setq relpos 0))
  562. (unless prop (setq prop :input))
  563. (ewoc-goto-node (oref cell :ewoc) (ein:cell-element-get cell prop))
  564. (let ((offset (case prop
  565. ((:input :before-output) 1)
  566. (:after-input -1)
  567. (t 0))))
  568. (forward-char (+ relpos offset))))
  569. (defmethod ein:cell-relative-point ((cell ein:basecell) &optional pos)
  570. "Return the point relative to the input area of CELL.
  571. If the position POS is not given, current point is considered."
  572. (unless pos (setq pos (point)))
  573. (- pos (1+ (ewoc-location (ein:cell-element-get cell :input)))))
  574. (defmethod ein:cell-location ((cell ein:basecell) &optional elm end)
  575. "Return the starting location of CELL.
  576. ELM is a name (keyword) of element that `ein:cell-element-get'
  577. understands. Note that you can't use `:output' since it returns
  578. a list. Use `:after-input' instead.
  579. If END is non-`nil', return the location of next element."
  580. (unless elm (setq elm :prompt))
  581. (let ((element (oref cell :element)))
  582. (when end
  583. (setq elm (case elm
  584. (:prompt :input)
  585. (:input :after-input)
  586. (:output :after-output)))
  587. (unless elm
  588. (setq cell (ein:cell-next cell))
  589. (setq elm :prompt)))
  590. (if cell
  591. (ewoc-location (ein:cell-element-get cell elm))
  592. (assert end)
  593. (point-max))))
  594. (defmethod ein:cell-buffer ((cell ein:basecell))
  595. "Return a buffer associated by CELL (if any)."
  596. (ein:aand (ein:oref-safe cell :ewoc) (ewoc-buffer it)))
  597. ;; Data manipulation
  598. (defmethod ein:cell-clear-output ((cell ein:codecell) stdout stderr other)
  599. ;; codecell.js in IPytohn implements it using timeout and callback.
  600. ;; As it is unclear why timeout is needed, just clear output
  601. ;; instantaneously for now.
  602. (ein:log 'debug "cell-clear-output stdout=%s stderr=%s other=%s"
  603. stdout stderr other)
  604. (let ((ewoc (oref cell :ewoc))
  605. (output-nodes (ein:cell-element-get cell :output)))
  606. (if (and stdout stderr other)
  607. (progn
  608. ;; clear all
  609. (let ((inhibit-read-only t)
  610. (buffer-undo-list t)) ; disable undo recording
  611. (apply #'ewoc-delete ewoc output-nodes))
  612. (plist-put (oref cell :element) :output nil)
  613. (oset cell :outputs nil))
  614. (let* ((ewoc-node-list
  615. (append
  616. (when stdout (ein:node-filter output-nodes :is 'output-stdout))
  617. (when stderr (ein:node-filter output-nodes :is 'output-stderr))
  618. (when stdout (ein:node-filter output-nodes
  619. :is 'output-subarea
  620. :not 'output-stderr
  621. :not 'output-stdout))))
  622. (indices
  623. (mapcar (lambda (n) (last (ein:$node-path (ewoc-data n))))
  624. ewoc-node-list)))
  625. ;; remove from buffer
  626. (let ((inhibit-read-only t)
  627. (buffer-undo-list t)) ; disable undo recording
  628. (apply #'ewoc-delete ewoc ewoc-node-list))
  629. ;; remove from `:element'
  630. (let* ((element (oref cell :element))
  631. (old-output (plist-get element :output))
  632. (new-ouptut (ein:remove-by-index old-output indices)))
  633. (plist-put element :output new-ouptut))
  634. ;; remove cleared outputs from internal data
  635. (oset cell :outputs
  636. (ein:remove-by-index (oref cell :outputs) indices))))
  637. ;; Footer may have extra (possibly colored) newline due to the
  638. ;; last output type. So invalidate it here.
  639. ;; See `ein:cell-insert-footer' (for codecell).
  640. (ewoc-invalidate ewoc (ein:cell-element-get cell :footer))))
  641. (defun ein:cell-output-json-to-class (json)
  642. (ein:case-equal (plist-get json :output_type)
  643. (("pyout")
  644. '(output-subarea))
  645. (("pyerr")
  646. '(output-subarea))
  647. (("display_data")
  648. '(output-subarea))
  649. (("stream")
  650. (list 'output-stream 'output-subarea
  651. (intern (format "output-%s" (plist-get json :stream)))))))
  652. (defmethod ein:cell-append-output ((cell ein:codecell) json dynamic)
  653. (ein:cell-expand cell)
  654. ;; (ein:flush-clear-timeout)
  655. (oset cell :outputs
  656. (append (oref cell :outputs) (list json)))
  657. ;; enter last output element
  658. (let* ((inhibit-read-only t)
  659. (buffer-undo-list t) ; disable undo recording
  660. (ewoc (oref cell :ewoc))
  661. (index (1- (ein:cell-num-outputs cell)))
  662. (path `(cell output ,index))
  663. (class (ein:cell-output-json-to-class json))
  664. (data (ein:node-new path cell class))
  665. (last-node (ein:cell-element-get cell :last-output))
  666. (ewoc-node (ewoc-enter-after ewoc last-node data))
  667. (element (oref cell :element)))
  668. (plist-put element :output
  669. (append (plist-get element :output) (list ewoc-node)))
  670. (ewoc-invalidate ewoc (ein:cell-element-get cell :footer))))
  671. (defmethod ein:cell-append-pyout ((cell ein:codecell) json)
  672. "Insert pyout type output in the buffer.
  673. Called from ewoc pretty printer via `ein:cell-insert-output'."
  674. (ein:insert-read-only (format "Out [%s]:"
  675. (or (plist-get json :prompt_number) " "))
  676. 'font-lock-face 'ein:cell-output-prompt)
  677. (ein:insert-read-only "\n")
  678. (ein:cell-append-mime-type json (oref cell :dynamic))
  679. (ein:insert-read-only "\n"))
  680. (defmethod ein:cell-append-pyerr ((cell ein:codecell) json)
  681. "Insert pyerr type output in the buffer.
  682. Called from ewoc pretty printer via `ein:cell-insert-output'."
  683. (mapc (lambda (tb)
  684. (ein:cell-append-text tb)
  685. (ein:cell-append-text "\n"))
  686. (let ((tb (plist-get json :traceback))
  687. (level ein:cell-traceback-level))
  688. (if (and level (> (- (length tb) 2) level))
  689. (cons "\nTruncated Traceback (Use C-c C-x to view full TB):"
  690. (last tb (1+ level)))
  691. tb)))
  692. (ein:insert-read-only "\n"))
  693. (ein:deflocal ein:%cell-append-stream-last-cell% nil
  694. "The last cell in which `ein:cell-append-stream' is used.")
  695. (defmethod ein:cell-append-stream ((cell ein:codecell) json)
  696. "Insert stream type output in the buffer.
  697. Called from ewoc pretty printer via `ein:cell-insert-output'."
  698. (unless (plist-get json :stream)
  699. (plist-put json :stream "stdout"))
  700. (unless (eq cell ein:%cell-append-stream-last-cell%)
  701. ;; Avoid applying unclosed ANSI escape code in the cell. Note
  702. ;; that I don't need to distinguish stdout/stderr because it looks
  703. ;; like normal terminal does not.
  704. (setq ansi-color-context nil))
  705. (let ((start (point)))
  706. (ein:cell-append-stream-text-fontified (plist-get json :text) json)
  707. (comint-carriage-motion start (point)))
  708. ;; NOTE: newlines for stream is handled in `ein:cell-insert-output'.
  709. ;; So do not insert newline here.
  710. (setq ein:%cell-append-stream-last-cell% cell))
  711. (defun ein:cell-append-stream-text-fontified (text json)
  712. "Insert TEXT with font properties defined by JSON data."
  713. (if (equal (plist-get json :stream) "stderr")
  714. (ein:cell-append-text text 'font-lock-face 'ein:cell-output-stderr)
  715. (ein:cell-append-text text)))
  716. (defmethod ein:cell-append-display-data ((cell ein:codecell) json)
  717. "Insert display-data type output in the buffer.
  718. Called from ewoc pretty printer via `ein:cell-insert-output'."
  719. (ein:cell-append-mime-type json (oref cell :dynamic))
  720. (ein:insert-read-only "\n"))
  721. (defcustom ein:output-type-preference
  722. (if (and (fboundp 'shr-insert-document)
  723. (fboundp 'libxml-parse-xml-region))
  724. #'ein:output-type-prefer-pretty-text-over-html
  725. '(emacs-lisp svg png jpeg text html latex javascript))
  726. "Output types to be used in notebook.
  727. First output-type found in this list will be used.
  728. This variable can be a list or a function returning a list given
  729. DATA plist.
  730. See also `ein:output-type-prefer-pretty-text-over-html'.
  731. **Example**:
  732. If you prefer HTML type over text type, you can set it as::
  733. (setq ein:output-type-preference
  734. '(emacs-lisp svg png jpeg html text latex javascript))
  735. Note that ``html`` comes before ``text``."
  736. :group 'ein)
  737. (defun ein:output-type-prefer-pretty-text-over-html (data)
  738. "Use text type if it is a \"prettified\" text instead of HTML.
  739. This is mostly for *not* using HTML table for pandas but using
  740. HTML for other object.
  741. If the text type output contains a newline, it is assumed be a
  742. prettified text thus be used instead of HTML type."
  743. (if (ein:aand (plist-get data :text) (string-match-p "\n" it))
  744. '(emacs-lisp svg png jpeg text html latex javascript)
  745. '(emacs-lisp svg png jpeg html text latex javascript)))
  746. (defun ein:cell-append-mime-type (json dynamic)
  747. (loop
  748. for key in (cond
  749. ((functionp ein:output-type-preference)
  750. (funcall ein:output-type-preference json))
  751. (t ein:output-type-preference))
  752. for type = (intern (format ":%s" key)) ; something like `:text'
  753. for value = (plist-get json type) ; FIXME: optimize
  754. when (plist-member json type)
  755. return
  756. (case key
  757. ;; NOTE: Normally `javascript' and `html' will not be inserted as
  758. ;; they come out after `text'. Maybe it is better to inform user
  759. ;; when one of them is inserted.
  760. (javascript
  761. (when dynamic
  762. (ein:log 'info (concat "ein:cell-append-mime-type does not support "
  763. "dynamic javascript. got: %s") value))
  764. (ein:insert-read-only (plist-get json type)))
  765. (emacs-lisp
  766. (when dynamic
  767. (ein:cell-safe-read-eval-insert (plist-get json type))))
  768. (html
  769. (funcall (ein:output-area-get-html-renderer) (plist-get json type)))
  770. ((latex text)
  771. (ein:insert-read-only (plist-get json type)))
  772. (svg
  773. (ein:insert-image value key t))
  774. ((png jpeg)
  775. (ein:insert-image (base64-decode-string value) key t)))))
  776. (defun ein:cell-append-text (data &rest properties)
  777. ;; escape ANSI in plaintext:
  778. (apply #'ein:insert-read-only (ansi-color-apply data) properties))
  779. (defun ein:cell-safe-read-eval-insert (text)
  780. (ein:insert-read-only
  781. (condition-case err
  782. (save-excursion
  783. ;; given code can be `pop-to-buffer' or something.
  784. (format "%S" (eval (read text))))
  785. (error
  786. (ein:log 'warn "Got an error while executing: '%s'"
  787. text)
  788. (format "Error: %S" err)))))
  789. (defmethod ein:cell-to-json ((cell ein:codecell) &optional discard-output)
  790. "Return json-ready alist."
  791. `((input . ,(ein:cell-get-text cell))
  792. (cell_type . "code")
  793. ,@(ein:aif (ein:oref-safe cell :input-prompt-number)
  794. `((prompt_number . ,it)))
  795. (outputs . ,(if discard-output [] (apply #'vector (oref cell :outputs))))
  796. (language . "python")
  797. (collapsed . ,(if (oref cell :collapsed) t json-false))))
  798. (defmethod ein:cell-to-json ((cell ein:textcell) &optional discard-output)
  799. `((cell_type . ,(oref cell :cell-type))
  800. (source . ,(ein:cell-get-text cell))))
  801. (defmethod ein:cell-to-json ((cell ein:headingcell) &optional discard-output)
  802. (let ((json (call-next-method)))
  803. (append json `((level . ,(oref cell :level))))))
  804. (defmethod ein:cell-next ((cell ein:basecell))
  805. "Return next cell of the given CELL or nil if CELL is the last one."
  806. (ein:aif (ewoc-next (oref cell :ewoc)
  807. (ein:cell-element-get cell :footer))
  808. (let ((cell (ein:$node-data (ewoc-data it))))
  809. (when (ein:basecell-child-p cell)
  810. cell))))
  811. (defmethod ein:cell-prev ((cell ein:basecell))
  812. "Return previous cell of the given CELL or nil if CELL is the first one."
  813. (ein:aif (ewoc-prev (oref cell :ewoc)
  814. (ein:cell-element-get cell :prompt))
  815. (let ((cell (ein:$node-data (ewoc-data it))))
  816. (when (ein:basecell-child-p cell)
  817. cell))))
  818. ;;; Kernel related calls.
  819. (defmethod ein:cell-set-kernel ((cell ein:codecell) kernel)
  820. (oset cell :kernel kernel))
  821. (defmethod ein:cell-execute ((cell ein:codecell))
  822. (ein:cell-execute-internal cell
  823. (oref cell :kernel)
  824. (ein:cell-get-text cell)
  825. :silent nil))
  826. (defmethod ein:cell-execute-internal ((cell ein:codecell)
  827. kernel code &rest args)
  828. (ein:cell-clear-output cell t t t)
  829. (ein:cell-set-input-prompt cell "*")
  830. (ein:cell-running-set cell t)
  831. (oset cell :dynamic t)
  832. (apply #'ein:kernel-execute kernel code (ein:cell-make-callbacks cell) args))
  833. (defmethod ein:cell-make-callbacks ((cell ein:codecell))
  834. (list
  835. :execute_reply (cons #'ein:cell--handle-execute-reply cell)
  836. :output (cons #'ein:cell--handle-output cell)
  837. :clear_output (cons #'ein:cell--handle-clear-output cell)
  838. :set_next_input (cons #'ein:cell--handle-set-next-input cell)))
  839. (defmethod ein:cell--handle-execute-reply ((cell ein:codecell) content
  840. -metadata-not-used-)
  841. (ein:cell-set-input-prompt cell (plist-get content :execution_count))
  842. (ein:cell-running-set cell nil)
  843. (let ((events (oref cell :events)))
  844. (ein:events-trigger events 'set_dirty.Worksheet (list :value t :cell cell))
  845. (ein:events-trigger events 'maybe_reset_undo.Worksheet cell)))
  846. (defmethod ein:cell--handle-set-next-input ((cell ein:codecell) text)
  847. (let ((events (oref cell :events)))
  848. (ein:events-trigger events 'set_next_input.Worksheet
  849. (list :cell cell :text text))
  850. (ein:events-trigger events 'maybe_reset_undo.Worksheet cell)))
  851. ;;; Output area
  852. ;; These function should go to ein-output-area.el. But as cell and
  853. ;; EWOC is connected in complicated way, I will leave them in
  854. ;; ein-cell.el.
  855. (defmethod ein:cell--handle-output ((cell ein:codecell) msg-type content
  856. -metadata-not-used-)
  857. (let* ((json (list :output_type msg-type)))
  858. (ein:case-equal msg-type
  859. (("stream")
  860. (plist-put json :text (plist-get content :data))
  861. (plist-put json :stream (plist-get content :name)))
  862. (("display_data" "pyout")
  863. (when (equal msg-type "pyout")
  864. (plist-put json :prompt_number (plist-get content :execution_count)))
  865. (setq json (ein:output-area-convert-mime-types
  866. json (plist-get content :data))))
  867. (("pyerr")
  868. (plist-put json :ename (plist-get content :ename))
  869. (plist-put json :evalue (plist-get content :evalue))
  870. (plist-put json :traceback (plist-get content :traceback))))
  871. (ein:cell-append-output cell json t)
  872. ;; (oset cell :dirty t)
  873. (ein:events-trigger (oref cell :events) 'maybe_reset_undo.Worksheet cell)))
  874. (defun ein:output-area-convert-mime-types (json data)
  875. (loop for (prop . mime) in '((:text . :text/plain)
  876. (:html . :text/html)
  877. (:svg . :image/svg+xml)
  878. (:png . :image/png)
  879. (:jpeg . :image/jpeg)
  880. (:latex . :text/latex)
  881. (:json . :application/json)
  882. (:javascript . :application/javascript)
  883. (:emacs-lisp . :application/emacs-lisp))
  884. when (plist-member data mime)
  885. do (plist-put json prop (plist-get data mime)))
  886. json)
  887. (defmethod ein:cell--handle-clear-output ((cell ein:codecell) content
  888. -metadata-not-used-)
  889. (ein:cell-clear-output cell
  890. (plist-get content :stdout)
  891. (plist-get content :stderr)
  892. (plist-get content :other))
  893. (ein:events-trigger (oref cell :events) 'maybe_reset_undo.Worksheet cell))
  894. ;;; Misc.
  895. (defmethod ein:cell-has-image-ouput-p ((cell ein:codecell))
  896. "Return `t' if given cell has image output, `nil' otherwise."
  897. (loop for out in (oref cell :outputs)
  898. when (or (plist-member out :svg)
  899. (plist-member out :png)
  900. (plist-member out :jpeg))
  901. return t))
  902. (defmethod ein:cell-has-image-ouput-p ((cell ein:textcell))
  903. nil)
  904. (defmethod ein:cell-get-tb-data ((cell ein:codecell))
  905. (loop for out in (oref cell :outputs)
  906. when (equal (plist-get out :output_type) "pyerr")
  907. return (plist-get out :traceback)))
  908. (provide 'ein-cell)
  909. ;;; ein-cell.el ends here