octave.el 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871
  1. ;;; octave.el --- editing octave source files under emacs -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 1997, 2001-2015 Free Software Foundation, Inc.
  3. ;; Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
  4. ;; John Eaton <jwe@octave.org>
  5. ;; Maintainer: emacs-devel@gnu.org
  6. ;; Keywords: languages
  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. ;;; Commentary:
  19. ;; This package provides Emacs support for Octave. It defines a major
  20. ;; mode for editing Octave code and contains code for interacting with
  21. ;; an inferior Octave process using comint.
  22. ;; See the documentation of `octave-mode' and `run-octave' for further
  23. ;; information on usage and customization.
  24. ;;; Code:
  25. (require 'comint)
  26. ;;; For emacs < 24.3.
  27. (require 'newcomment)
  28. (eval-and-compile
  29. (unless (fboundp 'user-error)
  30. (defalias 'user-error 'error))
  31. (unless (fboundp 'delete-consecutive-dups)
  32. (defalias 'delete-consecutive-dups 'delete-dups))
  33. (unless (fboundp 'completion-table-with-cache)
  34. (defun completion-table-with-cache (fun &optional ignore-case)
  35. ;; See eg bug#11906.
  36. (let* (last-arg last-result
  37. (new-fun
  38. (lambda (arg)
  39. (if (and last-arg (string-prefix-p last-arg arg ignore-case))
  40. last-result
  41. (prog1
  42. (setq last-result (funcall fun arg))
  43. (setq last-arg arg))))))
  44. (completion-table-dynamic new-fun)))))
  45. (eval-when-compile
  46. (unless (fboundp 'setq-local)
  47. (defmacro setq-local (var val)
  48. "Set variable VAR to value VAL in current buffer."
  49. (list 'set (list 'make-local-variable (list 'quote var)) val))))
  50. (defgroup octave nil
  51. "Editing Octave code."
  52. :link '(custom-manual "(octave-mode)Top")
  53. :link '(url-link "http://www.gnu.org/s/octave")
  54. :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
  55. :group 'languages)
  56. (define-obsolete-function-alias 'octave-submit-bug-report
  57. 'report-emacs-bug "24.4")
  58. (define-abbrev-table 'octave-abbrev-table nil
  59. "Abbrev table for Octave's reserved words.
  60. Used in `octave-mode' and `inferior-octave-mode' buffers.")
  61. (defvar octave-comment-char ?#
  62. "Character to start an Octave comment.")
  63. (defvar octave-comment-start (char-to-string octave-comment-char)
  64. "Octave-specific `comment-start' (which see).")
  65. (defvar octave-comment-start-skip "\\(^\\|\\S<\\)\\(?:%!\\|\\s<+\\)\\s-*"
  66. "Octave-specific `comment-start-skip' (which see).")
  67. (defvar octave-function-header-regexp
  68. (concat "^\\s-*\\_<\\(function\\)\\_>"
  69. "\\([^=;(\n]*=[ \t]*\\|[ \t]*\\)\\(\\(?:\\w\\|\\s_\\)+\\)\\_>")
  70. "Regexp to match an Octave function header.
  71. The string `function' and its name are given by the first and third
  72. parenthetical grouping.")
  73. (defvar octave-mode-map
  74. (let ((map (make-sparse-keymap)))
  75. (define-key map "\M-." 'octave-find-definition)
  76. (define-key map "\M-\C-j" 'octave-indent-new-comment-line)
  77. (define-key map "\C-c\C-p" 'octave-previous-code-line)
  78. (define-key map "\C-c\C-n" 'octave-next-code-line)
  79. (define-key map "\C-c\C-a" 'octave-beginning-of-line)
  80. (define-key map "\C-c\C-e" 'octave-end-of-line)
  81. (define-key map [remap down-list] 'smie-down-list)
  82. (define-key map "\C-c\M-\C-h" 'octave-mark-block)
  83. (define-key map "\C-c]" 'smie-close-block)
  84. (define-key map "\C-c/" 'smie-close-block)
  85. (define-key map "\C-c;" 'octave-update-function-file-comment)
  86. (define-key map "\C-hd" 'octave-help)
  87. (define-key map "\C-ha" 'octave-lookfor)
  88. (define-key map "\C-c\C-l" 'octave-source-file)
  89. (define-key map "\C-c\C-f" 'octave-insert-defun)
  90. (define-key map "\C-c\C-il" 'octave-send-line)
  91. (define-key map "\C-c\C-ib" 'octave-send-block)
  92. (define-key map "\C-c\C-if" 'octave-send-defun)
  93. (define-key map "\C-c\C-ir" 'octave-send-region)
  94. (define-key map "\C-c\C-ia" 'octave-send-buffer)
  95. (define-key map "\C-c\C-is" 'octave-show-process-buffer)
  96. (define-key map "\C-c\C-iq" 'octave-hide-process-buffer)
  97. (define-key map "\C-c\C-ik" 'octave-kill-process)
  98. (define-key map "\C-c\C-i\C-l" 'octave-send-line)
  99. (define-key map "\C-c\C-i\C-b" 'octave-send-block)
  100. (define-key map "\C-c\C-i\C-f" 'octave-send-defun)
  101. (define-key map "\C-c\C-i\C-r" 'octave-send-region)
  102. (define-key map "\C-c\C-i\C-a" 'octave-send-buffer)
  103. (define-key map "\C-c\C-i\C-s" 'octave-show-process-buffer)
  104. (define-key map "\C-c\C-i\C-q" 'octave-hide-process-buffer)
  105. (define-key map "\C-c\C-i\C-k" 'octave-kill-process)
  106. map)
  107. "Keymap used in Octave mode.")
  108. (easy-menu-define octave-mode-menu octave-mode-map
  109. "Menu for Octave mode."
  110. '("Octave"
  111. ["Split Line at Point" octave-indent-new-comment-line t]
  112. ["Previous Code Line" octave-previous-code-line t]
  113. ["Next Code Line" octave-next-code-line t]
  114. ["Begin of Line" octave-beginning-of-line t]
  115. ["End of Line" octave-end-of-line t]
  116. ["Mark Block" octave-mark-block t]
  117. ["Close Block" smie-close-block t]
  118. "---"
  119. ["Start Octave Process" run-octave t]
  120. ["Documentation Lookup" info-lookup-symbol t]
  121. ["Help on Function" octave-help t]
  122. ["Search help" octave-lookfor t]
  123. ["Find Function Definition" octave-find-definition t]
  124. ["Insert Function" octave-insert-defun t]
  125. ["Update Function File Comment" octave-update-function-file-comment t]
  126. "---"
  127. ["Function Syntax Hints" (eldoc-mode 'toggle)
  128. :style toggle :selected (bound-and-true-p eldoc-mode)
  129. :help "Display function signatures after typing `SPC' or `('"]
  130. ["Delimiter Matching" show-paren-mode
  131. :style toggle :selected show-paren-mode
  132. :help "Highlight matched pairs such as `if ... end'"
  133. :visible (fboundp 'smie--matching-block-data)]
  134. ["Auto Fill" auto-fill-mode
  135. :style toggle :selected auto-fill-function
  136. :help "Automatic line breaking"]
  137. ["Electric Layout" electric-layout-mode
  138. :style toggle :selected electric-layout-mode
  139. :help "Automatically insert newlines around some chars"]
  140. "---"
  141. ("Debug"
  142. ["Send Current Line" octave-send-line t]
  143. ["Send Current Block" octave-send-block t]
  144. ["Send Current Function" octave-send-defun t]
  145. ["Send Region" octave-send-region t]
  146. ["Send Buffer" octave-send-buffer t]
  147. ["Source Current File" octave-source-file t]
  148. ["Show Process Buffer" octave-show-process-buffer t]
  149. ["Hide Process Buffer" octave-hide-process-buffer t]
  150. ["Kill Process" octave-kill-process t])
  151. "---"
  152. ["Octave Mode Manual" (info "(octave-mode)Top") t]
  153. ["Customize Octave" (customize-group 'octave) t]
  154. ["Submit Bug Report" report-emacs-bug t]))
  155. (defvar octave-mode-syntax-table
  156. (let ((table (make-syntax-table)))
  157. (modify-syntax-entry ?\r " " table)
  158. (modify-syntax-entry ?+ "." table)
  159. (modify-syntax-entry ?- "." table)
  160. (modify-syntax-entry ?= "." table)
  161. (modify-syntax-entry ?* "." table)
  162. (modify-syntax-entry ?/ "." table)
  163. (modify-syntax-entry ?> "." table)
  164. (modify-syntax-entry ?< "." table)
  165. (modify-syntax-entry ?& "." table)
  166. (modify-syntax-entry ?| "." table)
  167. (modify-syntax-entry ?! "." table)
  168. (modify-syntax-entry ?\\ "." table)
  169. (modify-syntax-entry ?\' "." table)
  170. (modify-syntax-entry ?\` "." table)
  171. (modify-syntax-entry ?. "." table)
  172. (modify-syntax-entry ?\" "\"" table)
  173. (modify-syntax-entry ?_ "_" table)
  174. ;; The "b" flag only applies to the second letter of the comstart
  175. ;; and the first letter of the comend, i.e. the "4b" below is ineffective.
  176. ;; If we try to put `b' on the single-line comments, we get a similar
  177. ;; problem where the % and # chars appear as first chars of the 2-char
  178. ;; comend, so the multi-line ender is also turned into style-b.
  179. ;; So we need the new "c" comment style.
  180. (modify-syntax-entry ?\% "< 13" table)
  181. (modify-syntax-entry ?\# "< 13" table)
  182. (modify-syntax-entry ?\{ "(} 2c" table)
  183. (modify-syntax-entry ?\} "){ 4c" table)
  184. (modify-syntax-entry ?\n ">" table)
  185. table)
  186. "Syntax table in use in `octave-mode' buffers.")
  187. (defcustom octave-font-lock-texinfo-comment t
  188. "Control whether to highlight the texinfo comment block."
  189. :type 'boolean
  190. :version "24.4")
  191. (defcustom octave-blink-matching-block t
  192. "Control the blinking of matching Octave block keywords.
  193. Non-nil means show matching begin of block when inserting a space,
  194. newline or semicolon after an else or end keyword."
  195. :type 'boolean)
  196. (defcustom octave-block-offset 2
  197. "Extra indentation applied to statements in Octave block structures."
  198. :type 'integer)
  199. (defvar octave-block-comment-start
  200. (concat (make-string 2 octave-comment-char) " ")
  201. "String to insert to start a new Octave comment on an empty line.")
  202. (defcustom octave-continuation-offset 4
  203. "Extra indentation applied to Octave continuation lines."
  204. :type 'integer)
  205. (eval-and-compile
  206. (defconst octave-continuation-marker-regexp "\\\\\\|\\.\\.\\."))
  207. (defvar octave-continuation-regexp
  208. (concat "[^#%\n]*\\(" octave-continuation-marker-regexp
  209. "\\)\\s-*\\(\\s<.*\\)?$"))
  210. ;; Char \ is considered a bad decision for continuing a line.
  211. (defconst octave-continuation-string "..."
  212. "Character string used for Octave continuation lines.")
  213. (defvar octave-mode-imenu-generic-expression
  214. (list
  215. ;; Functions
  216. (list nil octave-function-header-regexp 3))
  217. "Imenu expression for Octave mode. See `imenu-generic-expression'.")
  218. (defcustom octave-mode-hook nil
  219. "Hook to be run when Octave mode is started."
  220. :type 'hook)
  221. (defcustom octave-send-show-buffer t
  222. "Non-nil means display `inferior-octave-buffer' after sending to it."
  223. :type 'boolean)
  224. (defcustom octave-send-line-auto-forward t
  225. "Control auto-forward after sending to the inferior Octave process.
  226. Non-nil means always go to the next Octave code line after sending."
  227. :type 'boolean)
  228. (defcustom octave-send-echo-input t
  229. "Non-nil means echo input sent to the inferior Octave process."
  230. :type 'boolean)
  231. ;;; SMIE indentation
  232. (require 'smie)
  233. (let-when-compile
  234. ((operator-table
  235. ;; Use '__operators__' in Octave REPL to get a full list?
  236. '((assoc ";" "\n") (assoc ",") ;The doc says they have equal precedence!?
  237. (right "=" "+=" "-=" "*=" "/=")
  238. (assoc "&&") (assoc "||") ; The doc claims they have equal precedence!?
  239. (assoc "&") (assoc "|") ; The doc claims they have equal precedence!?
  240. (nonassoc "<" "<=" "==" ">=" ">" "!=" "~=")
  241. (nonassoc ":") ;No idea what this is.
  242. (assoc "+" "-")
  243. (assoc "*" "/" "\\" ".\\" ".*" "./")
  244. (nonassoc "'" ".'")
  245. (nonassoc "++" "--" "!" "~") ;And unary "+" and "-".
  246. (right "^" "**" ".^" ".**")
  247. ;; It's not really an operator, but for indentation purposes it
  248. ;; could be convenient to treat it as one.
  249. (assoc "...")))
  250. (matchedrules
  251. ;; We can't distinguish the first element in a sequence with
  252. ;; precedence grammars, so we can't distinguish the condition
  253. ;; of the `if' from the subsequent body, for example.
  254. ;; This has to be done later in the indentation rules.
  255. '(("try" exp "catch" exp "end_try_catch")
  256. ("unwind_protect" exp
  257. "unwind_protect_cleanup" exp "end_unwind_protect")
  258. ("for" exp "endfor")
  259. ("parfor" exp "endparfor")
  260. ("while" exp "endwhile")
  261. ("if" exp "endif")
  262. ("if" exp "else" exp "endif")
  263. ("if" exp "elseif" exp "else" exp "endif")
  264. ("if" exp "elseif" exp "elseif" exp "else" exp "endif")
  265. ("switch" exp "case" exp "endswitch")
  266. ("switch" exp "case" exp "otherwise" exp "endswitch")
  267. ("switch" exp "case" exp "case" exp "otherwise" exp "endswitch")
  268. ("function" exp "endfunction")
  269. ("enumeration" exp "endenumeration")
  270. ("events" exp "endevents")
  271. ("methods" exp "endmethods")
  272. ("properties" exp "endproperties")
  273. ("classdef" exp "endclassdef")
  274. ))
  275. (bnf-table
  276. `((atom)
  277. ;; FIXME: We don't parse these declarations correctly since
  278. ;; SMIE *really* likes to parse "a b = 2 c" as "(a b) = (2 c)".
  279. ;; IOW to do it right, we'd need to change octave-smie-*ward-token
  280. ;; so that the spaces between vars in var-decls are lexed as
  281. ;; something like ",".
  282. ;; Doesn't seem worth the trouble/slowdown for now.
  283. ;; We could hack smie-rules so as to work around the bad parse,
  284. ;; but even that doesn't seem worth the trouble.
  285. (var-decls (atom "=" atom)) ;; (var-decls "," var-decls)
  286. (single-exp (atom "=" atom))
  287. (exp (exp "\n" exp)
  288. ;; We need to mention at least one of the operators in this part
  289. ;; of the grammar: if the BNF and the operator table have
  290. ;; no overlap, SMIE can't know how they relate.
  291. (exp ";" exp)
  292. ("do" exp "until" single-exp)
  293. ,@matchedrules
  294. ;; For every rule that ends in "endfoo", add a corresponding
  295. ;; rule which uses "end" instead.
  296. ,@(mapcar (lambda (rule) (nconc (butlast rule) '("end")))
  297. matchedrules)
  298. ("global" var-decls) ("persistent" var-decls)
  299. ;; These aren't super-important, but having them here
  300. ;; makes it easier to extract all keywords.
  301. ("break") ("continue") ("return")
  302. ;; The following rules do not correspond to valid code AFAIK,
  303. ;; but they lead to a grammar that degrades more gracefully
  304. ;; on incomplete/incorrect code. It also helps us in
  305. ;; computing octave--block-offset-keywords.
  306. ("try" exp "end") ("unwind_protect" exp "end")
  307. )
  308. ;; (fundesc (atom "=" atom))
  309. )))
  310. (defconst octave-smie-grammar
  311. (eval-when-compile
  312. (smie-prec2->grammar
  313. (smie-merge-prec2s
  314. (smie-bnf->prec2 bnf-table '((assoc "\n" ";")))
  315. (smie-precs->prec2 operator-table)))))
  316. (defconst octave-operator-regexp
  317. (eval-when-compile
  318. (regexp-opt (remove "\n" (apply #'append
  319. (mapcar #'cdr operator-table)))))))
  320. ;; Tokenizing needs to be refined so that ";;" is treated as two
  321. ;; tokens and also so as to recognize the \n separator (and
  322. ;; corresponding continuation lines).
  323. (defun octave-smie--funcall-p ()
  324. "Return non-nil if we're in an expression context. Moves point."
  325. (looking-at "[ \t]*("))
  326. (defun octave-smie--end-index-p ()
  327. (let ((ppss (syntax-ppss)))
  328. (and (nth 1 ppss)
  329. (memq (char-after (nth 1 ppss)) '(?\( ?\[ ?\{)))))
  330. (defun octave-smie--in-parens-p ()
  331. (let ((ppss (syntax-ppss)))
  332. (and (nth 1 ppss)
  333. (eq ?\( (char-after (nth 1 ppss))))))
  334. (defun octave-smie-backward-token ()
  335. (let ((pos (point)))
  336. (forward-comment (- (point)))
  337. (cond
  338. ((and (not (eq (char-before) ?\;)) ;Coalesce ";" and "\n".
  339. (> pos (line-end-position))
  340. (if (looking-back octave-continuation-marker-regexp (- (point) 3))
  341. (progn
  342. (goto-char (match-beginning 0))
  343. (forward-comment (- (point)))
  344. nil)
  345. t)
  346. (not (octave-smie--in-parens-p)))
  347. (skip-chars-forward " \t")
  348. ;; Why bother distinguishing \n and ;?
  349. ";") ;;"\n"
  350. ((and (looking-back octave-operator-regexp (- (point) 3) 'greedy)
  351. ;; Don't mistake a string quote for a transpose.
  352. (not (looking-back "\\s\"" (1- (point)))))
  353. (goto-char (match-beginning 0))
  354. (match-string-no-properties 0))
  355. (t
  356. (let ((tok (smie-default-backward-token)))
  357. (cond
  358. ((equal tok "enumeration")
  359. (if (save-excursion (smie-default-forward-token)
  360. (octave-smie--funcall-p))
  361. "enumeration (function)"
  362. tok))
  363. ((equal tok "end") (if (octave-smie--end-index-p) "end (index)" tok))
  364. (t tok)))))))
  365. (defun octave-smie-forward-token ()
  366. (skip-chars-forward " \t")
  367. (when (looking-at (eval-when-compile
  368. (concat "\\(" octave-continuation-marker-regexp
  369. "\\)[ \t]*\\($\\|[%#]\\)")))
  370. (goto-char (match-end 1))
  371. (forward-comment 1))
  372. (cond
  373. ((and (looking-at "[%#\n]")
  374. (not (or (save-excursion (skip-chars-backward " \t")
  375. ;; Only add implicit ; when needed.
  376. (or (bolp) (eq (char-before) ?\;)))
  377. (octave-smie--in-parens-p))))
  378. (if (eolp) (forward-char 1) (forward-comment 1))
  379. ;; Why bother distinguishing \n and ;?
  380. ";") ;;"\n"
  381. ((progn (forward-comment (point-max)) nil))
  382. ((looking-at ";[ \t]*\\($\\|[%#]\\)")
  383. ;; Combine the ; with the subsequent \n.
  384. (goto-char (match-beginning 1))
  385. (forward-comment 1)
  386. ";")
  387. ((and (looking-at octave-operator-regexp)
  388. ;; Don't mistake a string quote for a transpose.
  389. (not (looking-at "\\s\"")))
  390. (goto-char (match-end 0))
  391. (match-string-no-properties 0))
  392. (t
  393. (let ((tok (smie-default-forward-token)))
  394. (cond
  395. ((equal tok "enumeration")
  396. (if (octave-smie--funcall-p)
  397. "enumeration (function)"
  398. tok))
  399. ((equal tok "end") (if (octave-smie--end-index-p) "end (index)" tok))
  400. (t tok))))))
  401. (defconst octave--block-offset-keywords
  402. (let* ((end-prec (nth 1 (assoc "end" octave-smie-grammar)))
  403. (end-matchers
  404. (delq nil
  405. (mapcar (lambda (x) (if (eq end-prec (nth 2 x)) (car x)))
  406. octave-smie-grammar))))
  407. ;; Not sure if it would harm to keep "switch", but the previous code
  408. ;; excluded it, presumably because there shouldn't be any code on
  409. ;; the lines between "switch" and "case".
  410. (delete "switch" end-matchers)))
  411. (defun octave-smie-rules (kind token)
  412. (pcase (cons kind token)
  413. ;; We could set smie-indent-basic instead, but that would have two
  414. ;; disadvantages:
  415. ;; - changes to octave-block-offset wouldn't take effect immediately.
  416. ;; - edebug wouldn't show the use of this variable.
  417. (`(:elem . basic) octave-block-offset)
  418. (`(:list-intro . ,(or "global" "persistent")) t)
  419. ;; Since "case" is in the same BNF rules as switch..end, SMIE by default
  420. ;; aligns it with "switch".
  421. (`(:before . "case") (if (not (smie-rule-sibling-p)) octave-block-offset))
  422. (`(:after . ";")
  423. (if (apply #'smie-rule-parent-p octave--block-offset-keywords)
  424. (smie-rule-parent octave-block-offset)
  425. ;; For (invalid) code between switch and case.
  426. ;; (if (smie-rule-parent-p "switch") 4)
  427. nil))))
  428. (defun octave-indent-comment ()
  429. "A function for `smie-indent-functions' (which see)."
  430. (save-excursion
  431. (back-to-indentation)
  432. (cond
  433. ((octave-in-string-or-comment-p) nil)
  434. ((looking-at-p "\\(\\s<\\)\\1\\{2,\\}")
  435. 0)
  436. ;; Exclude %{, %} and %!.
  437. ((and (looking-at-p "\\s<\\(?:[^{}!]\\|$\\)")
  438. (not (looking-at-p "\\(\\s<\\)\\1")))
  439. (comment-choose-indent)))))
  440. (defvar octave-reserved-words
  441. (delq nil
  442. (mapcar (lambda (x)
  443. (setq x (car x))
  444. (and (stringp x) (string-match "\\`[[:alpha:]]" x) x))
  445. octave-smie-grammar))
  446. "Reserved words in Octave.")
  447. (defvar octave-font-lock-keywords
  448. (list
  449. ;; Fontify all builtin keywords.
  450. (cons (concat "\\_<" (regexp-opt octave-reserved-words) "\\_>")
  451. 'font-lock-keyword-face)
  452. ;; Note: 'end' also serves as the last index in an indexing expression,
  453. ;; and 'enumerate' is also a function.
  454. ;; Ref: http://www.mathworks.com/help/matlab/ref/end.html
  455. ;; Ref: http://www.mathworks.com/help/matlab/ref/enumeration.html
  456. (list (lambda (limit)
  457. (while (re-search-forward "\\_<en\\(?:d\\|umeratio\\(n\\)\\)\\_>"
  458. limit 'move)
  459. (let ((beg (match-beginning 0))
  460. (end (match-end 0)))
  461. (unless (octave-in-string-or-comment-p)
  462. (when (if (match-end 1)
  463. (octave-smie--funcall-p)
  464. (octave-smie--end-index-p))
  465. (put-text-property beg end 'face nil)))))
  466. nil))
  467. ;; Fontify all operators.
  468. (cons octave-operator-regexp 'font-lock-builtin-face)
  469. ;; Fontify all function declarations.
  470. (list octave-function-header-regexp
  471. '(1 font-lock-keyword-face)
  472. '(3 font-lock-function-name-face nil t)))
  473. "Additional Octave expressions to highlight.")
  474. (defun octave-syntax-propertize-function (start end)
  475. (goto-char start)
  476. (octave-syntax-propertize-sqs end)
  477. (funcall (syntax-propertize-rules
  478. ("\\\\" (0 (when (eq (nth 3 (save-excursion
  479. (syntax-ppss (match-beginning 0))))
  480. ?\")
  481. (string-to-syntax "\\"))))
  482. ;; Try to distinguish the string-quotes from the transpose-quotes.
  483. ("\\(?:^\\|[[({,; ]\\)\\('\\)"
  484. (1 (prog1 "\"'" (octave-syntax-propertize-sqs end)))))
  485. (point) end))
  486. (defun octave-syntax-propertize-sqs (end)
  487. "Propertize the content/end of single-quote strings."
  488. (when (eq (nth 3 (syntax-ppss)) ?\')
  489. ;; A '..' string.
  490. (when (re-search-forward
  491. "\\(?:\\=\\|[^']\\)\\(?:''\\)*\\('\\)\\($\\|[^']\\)" end 'move)
  492. (goto-char (match-beginning 2))
  493. (when (eq (char-before (match-beginning 1)) ?\\)
  494. ;; Backslash cannot escape a single quote.
  495. (put-text-property (1- (match-beginning 1)) (match-beginning 1)
  496. 'syntax-table (string-to-syntax ".")))
  497. (put-text-property (match-beginning 1) (match-end 1)
  498. 'syntax-table (string-to-syntax "\"'")))))
  499. (defvar electric-layout-rules)
  500. ;;;###autoload
  501. (define-derived-mode octave-mode prog-mode "Octave"
  502. "Major mode for editing Octave code.
  503. Octave is a high-level language, primarily intended for numerical
  504. computations. It provides a convenient command line interface
  505. for solving linear and nonlinear problems numerically. Function
  506. definitions can also be stored in files and used in batch mode.
  507. See Info node `(octave-mode) Using Octave Mode' for more details.
  508. Key bindings:
  509. \\{octave-mode-map}"
  510. :abbrev-table octave-abbrev-table
  511. :group 'octave
  512. (smie-setup octave-smie-grammar #'octave-smie-rules
  513. :forward-token #'octave-smie-forward-token
  514. :backward-token #'octave-smie-backward-token)
  515. (setq-local smie-indent-basic 'octave-block-offset)
  516. (add-hook 'smie-indent-functions #'octave-indent-comment nil t)
  517. (setq-local smie-blink-matching-triggers
  518. (cons ?\; smie-blink-matching-triggers))
  519. (unless octave-blink-matching-block
  520. (remove-hook 'post-self-insert-hook #'smie-blink-matching-open 'local))
  521. (setq-local electric-indent-chars
  522. (cons ?\; electric-indent-chars))
  523. ;; IIUC matlab-mode takes the opposite approach: it makes RET insert
  524. ;; a ";" at those places where it's correct (i.e. outside of parens).
  525. (setq-local electric-layout-rules '((?\; . after)))
  526. (setq-local comment-use-syntax t)
  527. (setq-local comment-start octave-comment-start)
  528. (setq-local comment-end "")
  529. (setq-local comment-start-skip octave-comment-start-skip)
  530. (setq-local comment-add 1)
  531. (setq-local parse-sexp-ignore-comments t)
  532. (setq-local paragraph-start (concat "\\s-*$\\|" page-delimiter))
  533. (setq-local paragraph-separate paragraph-start)
  534. (setq-local paragraph-ignore-fill-prefix t)
  535. (setq-local fill-paragraph-function 'octave-fill-paragraph)
  536. (setq-local fill-nobreak-predicate
  537. (lambda () (eq (octave-in-string-p) ?')))
  538. (with-no-warnings
  539. (if (fboundp 'add-function) ; new in 24.4
  540. (add-function :around (local 'comment-line-break-function)
  541. #'octave--indent-new-comment-line)
  542. (setq-local comment-line-break-function
  543. (apply-partially #'octave--indent-new-comment-line
  544. #'comment-indent-new-line))))
  545. (setq font-lock-defaults '(octave-font-lock-keywords))
  546. (setq-local syntax-propertize-function #'octave-syntax-propertize-function)
  547. (setq-local imenu-generic-expression octave-mode-imenu-generic-expression)
  548. (setq-local imenu-case-fold-search nil)
  549. (setq-local add-log-current-defun-function #'octave-add-log-current-defun)
  550. (add-hook 'completion-at-point-functions 'octave-completion-at-point nil t)
  551. (add-hook 'before-save-hook 'octave-sync-function-file-names nil t)
  552. (setq-local beginning-of-defun-function 'octave-beginning-of-defun)
  553. (and octave-font-lock-texinfo-comment (octave-font-lock-texinfo-comment))
  554. (add-function :before-until (local 'eldoc-documentation-function)
  555. 'octave-eldoc-function)
  556. (easy-menu-add octave-mode-menu))
  557. (defcustom inferior-octave-program "octave"
  558. "Program invoked by `inferior-octave'."
  559. :type 'string)
  560. (defcustom inferior-octave-buffer "*Inferior Octave*"
  561. "Name of buffer for running an inferior Octave process."
  562. :type 'string)
  563. (defcustom inferior-octave-prompt
  564. ;; For Octave >= 3.8, default is always 'octave', see
  565. ;; http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
  566. "\\(?:^octave\\(?:.bin\\|.exe\\)?\\(?:-[.0-9]+\\)?\\(?::[0-9]+\\)?\\|^debug\\|^\\)>+ "
  567. "Regexp to match prompts for the inferior Octave process."
  568. :type 'regexp)
  569. (defcustom inferior-octave-prompt-read-only comint-prompt-read-only
  570. "If non-nil, the Octave prompt is read only.
  571. See `comint-prompt-read-only' for details."
  572. :type 'boolean
  573. :version "24.4")
  574. (defcustom inferior-octave-startup-file
  575. (let ((n (file-name-nondirectory inferior-octave-program)))
  576. (locate-user-emacs-file (format "init_%s.m" n) (format ".emacs-%s" n)))
  577. "Name of the inferior Octave startup file.
  578. The contents of this file are sent to the inferior Octave process on
  579. startup."
  580. :type '(choice (const :tag "None" nil) file)
  581. :version "24.4")
  582. (defcustom inferior-octave-startup-args '("-i" "--no-line-editing")
  583. "List of command line arguments for the inferior Octave process.
  584. For example, for suppressing the startup message and using `traditional'
  585. mode, include \"-q\" and \"--traditional\"."
  586. :type '(repeat string)
  587. :version "24.4")
  588. (defcustom inferior-octave-mode-hook nil
  589. "Hook to be run when Inferior Octave mode is started."
  590. :type 'hook)
  591. (defcustom inferior-octave-error-regexp-alist
  592. '(("error:\\s-*\\(.*?\\) at line \\([0-9]+\\), column \\([0-9]+\\)"
  593. 1 2 3 2 1)
  594. ("warning:\\s-*\\([^:\n]+\\):.*at line \\([0-9]+\\), column \\([0-9]+\\)"
  595. 1 2 3 1 1))
  596. "Value for `compilation-error-regexp-alist' in inferior octave."
  597. :version "24.4"
  598. :type '(repeat (choice (symbol :tag "Predefined symbol")
  599. (sexp :tag "Error specification"))))
  600. (defvar inferior-octave-compilation-font-lock-keywords
  601. '(("\\_<PASS\\_>" . compilation-info-face)
  602. ("\\_<FAIL\\_>" . compilation-error-face)
  603. ("\\_<\\(warning\\):" 1 compilation-warning-face)
  604. ("\\_<\\(error\\):" 1 compilation-error-face)
  605. ("^\\s-*!!!!!.*\\|^.*failed$" . compilation-error-face))
  606. "Value for `compilation-mode-font-lock-keywords' in inferior octave.")
  607. (defvar inferior-octave-process nil)
  608. (defvar inferior-octave-mode-map
  609. (let ((map (make-sparse-keymap)))
  610. (set-keymap-parent map comint-mode-map)
  611. (define-key map "\M-." 'octave-find-definition)
  612. (define-key map "\t" 'completion-at-point)
  613. (define-key map "\C-hd" 'octave-help)
  614. (define-key map "\C-ha" 'octave-lookfor)
  615. ;; Same as in `shell-mode'.
  616. (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
  617. (define-key map "\C-c\C-l" 'inferior-octave-dynamic-list-input-ring)
  618. (define-key map [menu-bar inout list-history]
  619. '("List Input History" . inferior-octave-dynamic-list-input-ring))
  620. map)
  621. "Keymap used in Inferior Octave mode.")
  622. (defvar inferior-octave-mode-syntax-table
  623. (let ((table (make-syntax-table octave-mode-syntax-table)))
  624. table)
  625. "Syntax table in use in `inferior-octave-mode' buffers.")
  626. (defvar inferior-octave-font-lock-keywords
  627. (list
  628. (cons inferior-octave-prompt 'font-lock-type-face))
  629. ;; Could certainly do more font locking in inferior Octave ...
  630. "Additional expressions to highlight in Inferior Octave mode.")
  631. (defvar inferior-octave-output-list nil)
  632. (defvar inferior-octave-output-string nil)
  633. (defvar inferior-octave-receive-in-progress nil)
  634. (define-obsolete-variable-alias 'inferior-octave-startup-hook
  635. 'inferior-octave-mode-hook "24.4")
  636. (defvar inferior-octave-dynamic-complete-functions
  637. '(inferior-octave-completion-at-point comint-filename-completion)
  638. "List of functions called to perform completion for inferior Octave.
  639. This variable is used to initialize `comint-dynamic-complete-functions'
  640. in the Inferior Octave buffer.")
  641. (defvar info-lookup-mode)
  642. (defvar compilation-error-regexp-alist)
  643. (defvar compilation-mode-font-lock-keywords)
  644. (declare-function compilation-forget-errors "compile" ())
  645. (defun inferior-octave-process-live-p ()
  646. (process-live-p inferior-octave-process))
  647. (define-derived-mode inferior-octave-mode comint-mode "Inferior Octave"
  648. "Major mode for interacting with an inferior Octave process.
  649. See Info node `(octave-mode) Running Octave from Within Emacs' for more
  650. details.
  651. Key bindings:
  652. \\{inferior-octave-mode-map}"
  653. :abbrev-table octave-abbrev-table
  654. :group 'octave
  655. (setq comint-prompt-regexp inferior-octave-prompt)
  656. (setq-local comment-use-syntax t)
  657. (setq-local comment-start octave-comment-start)
  658. (setq-local comment-end "")
  659. (setq comment-column 32)
  660. (setq-local comment-start-skip octave-comment-start-skip)
  661. (setq font-lock-defaults '(inferior-octave-font-lock-keywords nil nil))
  662. (setq-local info-lookup-mode 'octave-mode)
  663. (setq-local eldoc-documentation-function 'octave-eldoc-function)
  664. (setq-local comint-input-ring-file-name
  665. (or (getenv "OCTAVE_HISTFILE") "~/.octave_hist"))
  666. (setq-local comint-input-ring-size
  667. (string-to-number (or (getenv "OCTAVE_HISTSIZE") "1024")))
  668. (comint-read-input-ring t)
  669. (setq-local comint-dynamic-complete-functions
  670. inferior-octave-dynamic-complete-functions)
  671. (setq-local comint-prompt-read-only inferior-octave-prompt-read-only)
  672. (add-hook 'comint-input-filter-functions
  673. 'inferior-octave-directory-tracker nil t)
  674. ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
  675. (add-hook 'window-configuration-change-hook
  676. 'inferior-octave-track-window-width-change nil t)
  677. (setq-local compilation-error-regexp-alist inferior-octave-error-regexp-alist)
  678. (setq-local compilation-mode-font-lock-keywords
  679. inferior-octave-compilation-font-lock-keywords)
  680. (compilation-shell-minor-mode 1)
  681. (compilation-forget-errors))
  682. ;;;###autoload
  683. (defun inferior-octave (&optional arg)
  684. "Run an inferior Octave process, I/O via `inferior-octave-buffer'.
  685. This buffer is put in Inferior Octave mode. See `inferior-octave-mode'.
  686. Unless ARG is non-nil, switches to this buffer.
  687. The elements of the list `inferior-octave-startup-args' are sent as
  688. command line arguments to the inferior Octave process on startup.
  689. Additional commands to be executed on startup can be provided either in
  690. the file specified by `inferior-octave-startup-file' or by the default
  691. startup file, `~/.emacs-octave'."
  692. (interactive "P")
  693. (let ((buffer (get-buffer-create inferior-octave-buffer)))
  694. (unless arg
  695. (pop-to-buffer buffer))
  696. (unless (comint-check-proc buffer)
  697. (with-current-buffer buffer
  698. (inferior-octave-startup)
  699. (inferior-octave-mode)))
  700. buffer))
  701. ;;;###autoload
  702. (defalias 'run-octave 'inferior-octave)
  703. (defun inferior-octave-startup ()
  704. "Start an inferior Octave process."
  705. (let ((proc (comint-exec-1
  706. (substring inferior-octave-buffer 1 -1)
  707. inferior-octave-buffer
  708. inferior-octave-program
  709. (append
  710. inferior-octave-startup-args
  711. ;; --no-gui is introduced in Octave > 3.7
  712. (and (not (member "--no-gui" inferior-octave-startup-args))
  713. (zerop (process-file inferior-octave-program
  714. nil nil nil "--no-gui" "--help"))
  715. '("--no-gui"))))))
  716. (set-process-filter proc 'inferior-octave-output-digest)
  717. (setq inferior-octave-process proc
  718. inferior-octave-output-list nil
  719. inferior-octave-output-string nil
  720. inferior-octave-receive-in-progress t)
  721. ;; This may look complicated ... However, we need to make sure that
  722. ;; we additional startup code only AFTER Octave is ready (otherwise,
  723. ;; output may be mixed up). Hence, we need to digest the Octave
  724. ;; output to see when it issues a prompt.
  725. (while inferior-octave-receive-in-progress
  726. (unless (inferior-octave-process-live-p)
  727. ;; Spit out the error messages.
  728. (when inferior-octave-output-list
  729. (princ (concat (mapconcat 'identity inferior-octave-output-list "\n")
  730. "\n")
  731. (process-mark inferior-octave-process)))
  732. (error "Process `%s' died" inferior-octave-process))
  733. (accept-process-output inferior-octave-process))
  734. (goto-char (point-max))
  735. (set-marker (process-mark proc) (point))
  736. (insert-before-markers
  737. (concat
  738. (if (not (bobp)) " \n")
  739. (if inferior-octave-output-list
  740. (concat (mapconcat
  741. 'identity inferior-octave-output-list "\n")
  742. "\n"))))
  743. ;; An empty secondary prompt, as e.g. obtained by '--braindead',
  744. ;; means trouble.
  745. (inferior-octave-send-list-and-digest (list "PS2\n"))
  746. (when (string-match "\\(PS2\\|ans\\) = *$"
  747. (car inferior-octave-output-list))
  748. (inferior-octave-send-list-and-digest (list "PS2 ('> ');\n")))
  749. (inferior-octave-send-list-and-digest
  750. (list "disp (getenv ('OCTAVE_SRCDIR'))\n"))
  751. (process-put proc 'octave-srcdir
  752. (unless (equal (car inferior-octave-output-list) "")
  753. (car inferior-octave-output-list)))
  754. ;; O.K., now we are ready for the Inferior Octave startup commands.
  755. (inferior-octave-send-list-and-digest
  756. (list "more off;\n"
  757. (unless (equal inferior-octave-output-string ">> ")
  758. ;; See http://hg.savannah.gnu.org/hgweb/octave/rev/708173343c50
  759. "PS1 ('octave> ');\n")
  760. (when (and inferior-octave-startup-file
  761. (file-exists-p inferior-octave-startup-file))
  762. (format "source ('%s');\n" inferior-octave-startup-file))))
  763. (when inferior-octave-output-list
  764. (insert-before-markers
  765. (mapconcat 'identity inferior-octave-output-list "\n")))
  766. ;; And finally, everything is back to normal.
  767. (set-process-filter proc 'comint-output-filter)
  768. ;; Just in case, to be sure a cd in the startup file won't have
  769. ;; detrimental effects.
  770. (with-demoted-errors (inferior-octave-resync-dirs))
  771. ;; Generate a proper prompt, which is critical to
  772. ;; `comint-history-isearch-backward-regexp'. Bug#14433.
  773. (comint-send-string proc "\n")))
  774. (defun inferior-octave-completion-table ()
  775. (completion-table-with-cache
  776. (lambda (command)
  777. (inferior-octave-send-list-and-digest
  778. (list (format "completion_matches ('%s');\n" command)))
  779. (delete-consecutive-dups
  780. (sort inferior-octave-output-list 'string-lessp)))))
  781. (defun inferior-octave-completion-at-point ()
  782. "Return the data to complete the Octave symbol at point."
  783. ;; http://debbugs.gnu.org/14300
  784. (unless (string-match-p "/" (or (comint--match-partial-filename) ""))
  785. (let ((beg (save-excursion
  786. (skip-syntax-backward "w_" (comint-line-beginning-position))
  787. (point)))
  788. (end (point)))
  789. (when (and beg (> end beg))
  790. (list beg end (completion-table-in-turn
  791. (inferior-octave-completion-table)
  792. 'comint-completion-file-name-table))))))
  793. (define-obsolete-function-alias 'inferior-octave-complete
  794. 'completion-at-point "24.1")
  795. (defun inferior-octave-dynamic-list-input-ring ()
  796. "List the buffer's input history in a help buffer."
  797. ;; We cannot use `comint-dynamic-list-input-ring', because it replaces
  798. ;; "completion" by "history reference" ...
  799. (interactive)
  800. (if (or (not (ring-p comint-input-ring))
  801. (ring-empty-p comint-input-ring))
  802. (message "No history")
  803. (let ((history nil)
  804. (history-buffer " *Input History*")
  805. (index (1- (ring-length comint-input-ring)))
  806. (conf (current-window-configuration)))
  807. ;; We have to build up a list ourselves from the ring vector.
  808. (while (>= index 0)
  809. (setq history (cons (ring-ref comint-input-ring index) history)
  810. index (1- index)))
  811. ;; Change "completion" to "history reference"
  812. ;; to make the display accurate.
  813. (with-output-to-temp-buffer history-buffer
  814. (display-completion-list history)
  815. (set-buffer history-buffer))
  816. (message "Hit space to flush")
  817. (let ((ch (read-event)))
  818. (if (eq ch ?\ )
  819. (set-window-configuration conf)
  820. (push ch unread-command-events))))))
  821. (defun inferior-octave-output-digest (_proc string)
  822. "Special output filter for the inferior Octave process.
  823. Save all output between newlines into `inferior-octave-output-list', and
  824. the rest to `inferior-octave-output-string'."
  825. (setq string (concat inferior-octave-output-string string))
  826. (while (string-match "\n" string)
  827. (setq inferior-octave-output-list
  828. (append inferior-octave-output-list
  829. (list (substring string 0 (match-beginning 0))))
  830. string (substring string (match-end 0))))
  831. (if (string-match inferior-octave-prompt string)
  832. (setq inferior-octave-receive-in-progress nil))
  833. (setq inferior-octave-output-string string))
  834. (defun inferior-octave-check-process ()
  835. (or (inferior-octave-process-live-p)
  836. (error (substitute-command-keys
  837. "No inferior octave process running. Type \\[run-octave]"))))
  838. (defun inferior-octave-send-list-and-digest (list)
  839. "Send LIST to the inferior Octave process and digest the output.
  840. The elements of LIST have to be strings and are sent one by one. All
  841. output is passed to the filter `inferior-octave-output-digest'."
  842. (inferior-octave-check-process)
  843. (let* ((proc inferior-octave-process)
  844. (filter (process-filter proc))
  845. string)
  846. (set-process-filter proc 'inferior-octave-output-digest)
  847. (setq inferior-octave-output-list nil)
  848. (unwind-protect
  849. (while (setq string (car list))
  850. (setq inferior-octave-output-string nil
  851. inferior-octave-receive-in-progress t)
  852. (comint-send-string proc string)
  853. (while inferior-octave-receive-in-progress
  854. (accept-process-output proc))
  855. (setq list (cdr list)))
  856. (set-process-filter proc filter))))
  857. (defvar inferior-octave-directory-tracker-resync nil)
  858. (make-variable-buffer-local 'inferior-octave-directory-tracker-resync)
  859. (defun inferior-octave-directory-tracker (string)
  860. "Tracks `cd' commands issued to the inferior Octave process.
  861. Use \\[inferior-octave-resync-dirs] to resync if Emacs gets confused."
  862. (when inferior-octave-directory-tracker-resync
  863. (or (inferior-octave-resync-dirs 'noerror)
  864. (setq inferior-octave-directory-tracker-resync nil)))
  865. (cond
  866. ((string-match "^[ \t]*cd[ \t;]*$" string)
  867. (cd "~"))
  868. ((string-match "^[ \t]*cd[ \t]+\\([^ \t\n;]*\\)[ \t\n;]*" string)
  869. (condition-case err
  870. (cd (match-string 1 string))
  871. (error (setq inferior-octave-directory-tracker-resync t)
  872. (message "%s: `%s'"
  873. (error-message-string err)
  874. (match-string 1 string)))))))
  875. (defun inferior-octave-resync-dirs (&optional noerror)
  876. "Resync the buffer's idea of the current directory.
  877. This command queries the inferior Octave process about its current
  878. directory and makes this the current buffer's default directory."
  879. (interactive)
  880. (inferior-octave-send-list-and-digest '("disp (pwd ())\n"))
  881. (condition-case err
  882. (progn
  883. (cd (car inferior-octave-output-list))
  884. t)
  885. (error (unless noerror (signal (car err) (cdr err))))))
  886. (defcustom inferior-octave-minimal-columns 80
  887. "The minimal column width for the inferior Octave process."
  888. :type 'integer
  889. :version "24.4")
  890. (defvar inferior-octave-last-column-width nil)
  891. (defun inferior-octave-track-window-width-change ()
  892. ;; http://thread.gmane.org/gmane.comp.gnu.octave.general/48572
  893. (let ((width (max inferior-octave-minimal-columns (window-width))))
  894. (unless (eq inferior-octave-last-column-width width)
  895. (setq-local inferior-octave-last-column-width width)
  896. (when (inferior-octave-process-live-p)
  897. (inferior-octave-send-list-and-digest
  898. (list (format "putenv ('COLUMNS', '%s');\n" width)))))))
  899. ;;; Miscellaneous useful functions
  900. (defun octave-in-comment-p ()
  901. "Return non-nil if point is inside an Octave comment."
  902. (nth 4 (syntax-ppss)))
  903. (defun octave-in-string-p ()
  904. "Return non-nil if point is inside an Octave string."
  905. (nth 3 (syntax-ppss)))
  906. (defun octave-in-string-or-comment-p ()
  907. "Return non-nil if point is inside an Octave string or comment."
  908. (nth 8 (syntax-ppss)))
  909. (defun octave-looking-at-kw (regexp)
  910. "Like `looking-at', but sets `case-fold-search' nil."
  911. (let ((case-fold-search nil))
  912. (looking-at regexp)))
  913. (defun octave-maybe-insert-continuation-string ()
  914. (if (or (octave-in-comment-p)
  915. (save-excursion
  916. (beginning-of-line)
  917. (looking-at octave-continuation-regexp)))
  918. nil
  919. (delete-horizontal-space)
  920. (insert (concat " " octave-continuation-string))))
  921. (defun octave-completing-read ()
  922. (let ((def (or (thing-at-point 'symbol)
  923. (save-excursion
  924. (skip-syntax-backward "-(")
  925. (thing-at-point 'symbol)))))
  926. (completing-read
  927. (format (if def "Function (default %s): "
  928. "Function: ") def)
  929. (inferior-octave-completion-table)
  930. nil nil nil nil def)))
  931. (defun octave-goto-function-definition (fn)
  932. "Go to the function definition of FN in current buffer."
  933. (let ((search
  934. (lambda (re sub)
  935. (let ((orig (point)) found)
  936. (goto-char (point-min))
  937. (while (and (not found) (re-search-forward re nil t))
  938. (when (and (equal (match-string sub) fn)
  939. (not (nth 8 (syntax-ppss))))
  940. (setq found t)))
  941. (unless found (goto-char orig))
  942. found))))
  943. (pcase (and buffer-file-name (file-name-extension buffer-file-name))
  944. (`"cc" (funcall search
  945. "\\_<DEFUN\\(?:_DLD\\)?\\s-*(\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)" 1))
  946. (_ (funcall search octave-function-header-regexp 3)))))
  947. (defun octave-function-file-p ()
  948. "Return non-nil if the first token is \"function\".
  949. The value is (START END NAME-START NAME-END) of the function."
  950. (save-excursion
  951. (goto-char (point-min))
  952. (when (equal (funcall smie-forward-token-function) "function")
  953. (forward-word -1)
  954. (let* ((start (point))
  955. (end (progn (forward-sexp 1) (point)))
  956. (name (when (progn
  957. (goto-char start)
  958. (re-search-forward octave-function-header-regexp
  959. end t))
  960. (list (match-beginning 3) (match-end 3)))))
  961. (cons start (cons end name))))))
  962. ;; Like forward-comment but stop at non-comment blank
  963. (defun octave-skip-comment-forward (limit)
  964. (let ((ppss (syntax-ppss)))
  965. (if (nth 4 ppss)
  966. (goto-char (nth 8 ppss))
  967. (goto-char (or (comment-search-forward limit t) (point)))))
  968. (while (and (< (point) limit) (looking-at-p "\\s<"))
  969. (forward-comment 1)))
  970. ;;; First non-copyright comment block
  971. (defun octave-function-file-comment ()
  972. "Beginning and end positions of the function file comment."
  973. (save-excursion
  974. (goto-char (point-min))
  975. ;; Copyright block: octave/libinterp/parse-tree/lex.ll around line 1634
  976. (while (save-excursion
  977. (when (comment-search-forward (point-max) t)
  978. (when (eq (char-after) ?\{) ; case of block comment
  979. (forward-char 1))
  980. (skip-syntax-forward "-")
  981. (let ((case-fold-search t))
  982. (looking-at-p "\\(?:copyright\\|author\\)\\_>"))))
  983. (octave-skip-comment-forward (point-max)))
  984. (let ((beg (comment-search-forward (point-max) t)))
  985. (when beg
  986. (goto-char beg)
  987. (octave-skip-comment-forward (point-max))
  988. (list beg (point))))))
  989. (defun octave-sync-function-file-names ()
  990. "Ensure function name agree with function file name.
  991. See Info node `(octave)Function Files'."
  992. (interactive)
  993. (when buffer-file-name
  994. (pcase-let ((`(,start ,_end ,name-start ,name-end)
  995. (octave-function-file-p)))
  996. (when (and start name-start)
  997. (let* ((func (buffer-substring name-start name-end))
  998. (file (file-name-sans-extension
  999. (file-name-nondirectory buffer-file-name)))
  1000. (help-form (format-message "\
  1001. a: Use function name `%s'
  1002. b: Use file name `%s'
  1003. q: Don't fix\n" func file))
  1004. (c (unless (equal file func)
  1005. (save-window-excursion
  1006. (help-form-show)
  1007. (read-char-choice
  1008. "Which name to use? (a/b/q) " '(?a ?b ?q))))))
  1009. (pcase c
  1010. (`?a (let ((newname (expand-file-name
  1011. (concat func (file-name-extension
  1012. buffer-file-name t)))))
  1013. (when (or (not (file-exists-p newname))
  1014. (yes-or-no-p
  1015. (format "Target file %s exists; proceed? " newname)))
  1016. (when (file-exists-p buffer-file-name)
  1017. (rename-file buffer-file-name newname t))
  1018. (set-visited-file-name newname))))
  1019. (`?b (save-excursion
  1020. (goto-char name-start)
  1021. (delete-region name-start name-end)
  1022. (insert file)))))))))
  1023. (defun octave-update-function-file-comment (beg end)
  1024. "Query replace function names in function file comment."
  1025. (interactive
  1026. (progn
  1027. (barf-if-buffer-read-only)
  1028. (if (use-region-p)
  1029. (list (region-beginning) (region-end))
  1030. (or (octave-function-file-comment)
  1031. (error "No function file comment found")))))
  1032. (save-excursion
  1033. (let* ((bounds (or (octave-function-file-p)
  1034. (error "Not in a function file buffer")))
  1035. (func (if (cddr bounds)
  1036. (apply #'buffer-substring (cddr bounds))
  1037. (error "Function name not found")))
  1038. (old-func (progn
  1039. (goto-char beg)
  1040. (when (re-search-forward
  1041. "[=}]\\s-*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"
  1042. (min (line-end-position 4) end)
  1043. t)
  1044. (match-string 1))))
  1045. (old-func (read-string (format (if old-func
  1046. "Name to replace (default %s): "
  1047. "Name to replace: ")
  1048. old-func)
  1049. nil nil old-func)))
  1050. (if (and func old-func (not (equal func old-func)))
  1051. (perform-replace old-func func 'query
  1052. nil 'delimited nil nil beg end)
  1053. (message "Function names match")))))
  1054. (defface octave-function-comment-block
  1055. '((t (:inherit font-lock-doc-face)))
  1056. "Face used to highlight function comment block.")
  1057. (eval-when-compile (require 'texinfo))
  1058. (defun octave-font-lock-texinfo-comment ()
  1059. (let ((kws
  1060. (eval-when-compile
  1061. (delq nil (mapcar
  1062. (lambda (kw)
  1063. (if (numberp (nth 1 kw))
  1064. `(,(nth 0 kw) ,(nth 1 kw) ,(nth 2 kw) prepend)
  1065. (message "Ignoring Texinfo highlight: %S" kw)))
  1066. texinfo-font-lock-keywords)))))
  1067. (font-lock-add-keywords
  1068. nil
  1069. `((,(lambda (limit)
  1070. (while (and (< (point) limit)
  1071. (search-forward "-*- texinfo -*-" limit t)
  1072. (octave-in-comment-p))
  1073. (let ((beg (nth 8 (syntax-ppss)))
  1074. (end (progn
  1075. (octave-skip-comment-forward (point-max))
  1076. (point))))
  1077. (put-text-property beg end 'font-lock-multiline t)
  1078. (font-lock-prepend-text-property
  1079. beg end 'face 'octave-function-comment-block)
  1080. (dolist (kw kws)
  1081. (goto-char beg)
  1082. (while (re-search-forward (car kw) end 'move)
  1083. (font-lock-apply-highlight (cdr kw))))))
  1084. nil)))
  1085. 'append)))
  1086. ;;; Indentation
  1087. (defun octave-indent-new-comment-line (&optional soft)
  1088. "Break Octave line at point, continuing comment if within one.
  1089. Insert `octave-continuation-string' before breaking the line
  1090. unless inside a list. Signal an error if within a single-quoted
  1091. string."
  1092. (interactive)
  1093. (funcall comment-line-break-function soft))
  1094. (defun octave--indent-new-comment-line (orig &rest args)
  1095. (cond
  1096. ((octave-in-comment-p) nil)
  1097. ((eq (octave-in-string-p) ?')
  1098. (error "Cannot split a single-quoted string"))
  1099. ((eq (octave-in-string-p) ?\")
  1100. (insert octave-continuation-string))
  1101. (t
  1102. (delete-horizontal-space)
  1103. (unless (and (cadr (syntax-ppss))
  1104. (eq (char-after (cadr (syntax-ppss))) ?\())
  1105. (insert " " octave-continuation-string))))
  1106. (apply orig args)
  1107. (indent-according-to-mode))
  1108. (define-obsolete-function-alias
  1109. 'octave-indent-defun 'prog-indent-sexp "24.4")
  1110. ;;; Motion
  1111. (defun octave-next-code-line (&optional arg)
  1112. "Move ARG lines of Octave code forward (backward if ARG is negative).
  1113. Skips past all empty and comment lines. Default for ARG is 1.
  1114. On success, return 0. Otherwise, go as far as possible and return -1."
  1115. (interactive "p")
  1116. (or arg (setq arg 1))
  1117. (beginning-of-line)
  1118. (let ((n 0)
  1119. (inc (if (> arg 0) 1 -1)))
  1120. (while (and (/= arg 0) (= n 0))
  1121. (setq n (forward-line inc))
  1122. (while (and (= n 0)
  1123. (looking-at "\\s-*\\($\\|\\s<\\)"))
  1124. (setq n (forward-line inc)))
  1125. (setq arg (- arg inc)))
  1126. n))
  1127. (defun octave-previous-code-line (&optional arg)
  1128. "Move ARG lines of Octave code backward (forward if ARG is negative).
  1129. Skips past all empty and comment lines. Default for ARG is 1.
  1130. On success, return 0. Otherwise, go as far as possible and return -1."
  1131. (interactive "p")
  1132. (or arg (setq arg 1))
  1133. (octave-next-code-line (- arg)))
  1134. (defun octave-beginning-of-line ()
  1135. "Move point to beginning of current Octave line.
  1136. If on an empty or comment line, go to the beginning of that line.
  1137. Otherwise, move backward to the beginning of the first Octave code line
  1138. which is not inside a continuation statement, i.e., which does not
  1139. follow a code line ending with `...' or is inside an open
  1140. parenthesis list."
  1141. (interactive)
  1142. (beginning-of-line)
  1143. (unless (looking-at "\\s-*\\($\\|\\s<\\)")
  1144. (while (or (when (cadr (syntax-ppss))
  1145. (goto-char (cadr (syntax-ppss)))
  1146. (beginning-of-line)
  1147. t)
  1148. (and (or (looking-at "\\s-*\\($\\|\\s<\\)")
  1149. (save-excursion
  1150. (if (zerop (octave-previous-code-line))
  1151. (looking-at octave-continuation-regexp))))
  1152. (zerop (forward-line -1)))))))
  1153. (defun octave-end-of-line ()
  1154. "Move point to end of current Octave line.
  1155. If on an empty or comment line, go to the end of that line.
  1156. Otherwise, move forward to the end of the first Octave code line which
  1157. does not end with `...' or is inside an open parenthesis list."
  1158. (interactive)
  1159. (end-of-line)
  1160. (unless (save-excursion
  1161. (beginning-of-line)
  1162. (looking-at "\\s-*\\($\\|\\s<\\)"))
  1163. (while (or (when (cadr (syntax-ppss))
  1164. (condition-case nil
  1165. (progn
  1166. (up-list 1)
  1167. (end-of-line)
  1168. t)
  1169. (error nil)))
  1170. (and (save-excursion
  1171. (beginning-of-line)
  1172. (or (looking-at "\\s-*\\($\\|\\s<\\)")
  1173. (looking-at octave-continuation-regexp)))
  1174. (zerop (forward-line 1)))))
  1175. (end-of-line)))
  1176. (defun octave-mark-block ()
  1177. "Put point at the beginning of this Octave block, mark at the end.
  1178. The block marked is the one that contains point or follows point."
  1179. (interactive)
  1180. (if (and (looking-at "\\sw\\|\\s_")
  1181. (looking-back "\\sw\\|\\s_" (1- (point))))
  1182. (skip-syntax-forward "w_"))
  1183. (unless (or (looking-at "\\s(")
  1184. (save-excursion
  1185. (let* ((token (funcall smie-forward-token-function))
  1186. (level (assoc token smie-grammar)))
  1187. (and level (not (numberp (cadr level)))))))
  1188. (backward-up-list 1))
  1189. (mark-sexp))
  1190. (defun octave-beginning-of-defun (&optional arg)
  1191. "Octave-specific `beginning-of-defun-function' (which see)."
  1192. (or arg (setq arg 1))
  1193. ;; Move out of strings or comments.
  1194. (when (octave-in-string-or-comment-p)
  1195. (goto-char (octave-in-string-or-comment-p)))
  1196. (letrec ((orig (point))
  1197. (toplevel (lambda (pos)
  1198. (condition-case nil
  1199. (progn
  1200. (backward-up-list 1)
  1201. (funcall toplevel (point)))
  1202. (scan-error pos)))))
  1203. (goto-char (funcall toplevel (point)))
  1204. (when (and (> arg 0) (/= orig (point)))
  1205. (setq arg (1- arg)))
  1206. (forward-sexp (- arg))
  1207. (and (< arg 0) (forward-sexp -1))
  1208. (/= orig (point))))
  1209. (defun octave-fill-paragraph (&optional _arg)
  1210. "Fill paragraph of Octave code, handling Octave comments."
  1211. ;; FIXME: difference with generic fill-paragraph:
  1212. ;; - code lines are only split, never joined.
  1213. ;; - \n that end comments are never removed.
  1214. ;; - insert continuation marker when splitting code lines.
  1215. (interactive "P")
  1216. (save-excursion
  1217. (let ((end (progn (forward-paragraph) (copy-marker (point) t)))
  1218. (beg (progn
  1219. (forward-paragraph -1)
  1220. (skip-chars-forward " \t\n")
  1221. (beginning-of-line)
  1222. (point)))
  1223. (cfc (current-fill-column))
  1224. comment-prefix)
  1225. (goto-char beg)
  1226. (while (< (point) end)
  1227. (condition-case nil
  1228. (indent-according-to-mode)
  1229. (error nil))
  1230. (move-to-column cfc)
  1231. ;; First check whether we need to combine non-empty comment lines
  1232. (if (and (< (current-column) cfc)
  1233. (octave-in-comment-p)
  1234. (not (save-excursion
  1235. (beginning-of-line)
  1236. (looking-at "^\\s-*\\s<+\\s-*$"))))
  1237. ;; This is a nonempty comment line which does not extend
  1238. ;; past the fill column. If it is followed by a nonempty
  1239. ;; comment line with the same comment prefix, try to
  1240. ;; combine them, and repeat this until either we reach the
  1241. ;; fill-column or there is nothing more to combine.
  1242. (progn
  1243. ;; Get the comment prefix
  1244. (save-excursion
  1245. (beginning-of-line)
  1246. (while (and (re-search-forward "\\s<+")
  1247. (not (octave-in-comment-p))))
  1248. (setq comment-prefix (match-string 0)))
  1249. ;; And keep combining ...
  1250. (while (and (< (current-column) cfc)
  1251. (save-excursion
  1252. (forward-line 1)
  1253. (and (looking-at
  1254. (concat "^\\s-*"
  1255. comment-prefix
  1256. "\\S<"))
  1257. (not (looking-at
  1258. (concat "^\\s-*"
  1259. comment-prefix
  1260. "\\s-*$"))))))
  1261. (delete-char 1)
  1262. (re-search-forward comment-prefix)
  1263. (delete-region (match-beginning 0) (match-end 0))
  1264. (fixup-whitespace)
  1265. (move-to-column cfc))))
  1266. ;; We might also try to combine continued code lines> Perhaps
  1267. ;; some other time ...
  1268. (skip-chars-forward "^ \t\n")
  1269. (delete-horizontal-space)
  1270. (if (or (< (current-column) cfc)
  1271. (and (= (current-column) cfc) (eolp)))
  1272. (forward-line 1)
  1273. (if (not (eolp)) (insert " "))
  1274. (or (funcall normal-auto-fill-function)
  1275. (forward-line 1))))
  1276. t)))
  1277. (defun octave-completion-at-point ()
  1278. "Find the text to complete and the corresponding table."
  1279. (let* ((beg (save-excursion (skip-syntax-backward "w_") (point)))
  1280. (end (point)))
  1281. (if (< beg (point))
  1282. ;; Extend region past point, if applicable.
  1283. (save-excursion (skip-syntax-forward "w_")
  1284. (setq end (point))))
  1285. (when (> end beg)
  1286. (list beg end (or (and (inferior-octave-process-live-p)
  1287. (inferior-octave-completion-table))
  1288. octave-reserved-words)))))
  1289. (define-obsolete-function-alias 'octave-complete-symbol
  1290. 'completion-at-point "24.1")
  1291. (defun octave-add-log-current-defun ()
  1292. "A function for `add-log-current-defun-function' (which see)."
  1293. (save-excursion
  1294. (end-of-line)
  1295. (and (beginning-of-defun)
  1296. (re-search-forward octave-function-header-regexp
  1297. (line-end-position) t)
  1298. (match-string 3))))
  1299. ;;; Electric characters && friends
  1300. (define-skeleton octave-insert-defun
  1301. "Insert an Octave function skeleton.
  1302. Prompt for the function's name, arguments and return values (to be
  1303. entered without parens)."
  1304. (let* ((defname (file-name-sans-extension (buffer-name)))
  1305. (name (read-string (format "Function name (default %s): " defname)
  1306. nil nil defname))
  1307. (args (read-string "Arguments: "))
  1308. (vals (read-string "Return values: ")))
  1309. (format "%s%s (%s)"
  1310. (cond
  1311. ((string-equal vals "") vals)
  1312. ((string-match "[ ,]" vals) (concat "[" vals "] = "))
  1313. (t (concat vals " = ")))
  1314. name
  1315. args))
  1316. \n octave-block-comment-start "usage: " str \n
  1317. octave-block-comment-start '(delete-horizontal-space) \n
  1318. octave-block-comment-start '(delete-horizontal-space) \n
  1319. "function " > str \n
  1320. _ \n
  1321. "endfunction" > \n)
  1322. ;;; Communication with the inferior Octave process
  1323. (defun octave-kill-process ()
  1324. "Kill inferior Octave process and its buffer."
  1325. (interactive)
  1326. (when (and (buffer-live-p (get-buffer inferior-octave-buffer))
  1327. (or (yes-or-no-p (format "Kill %S and its buffer? "
  1328. inferior-octave-process))
  1329. (user-error "Aborted")))
  1330. (when (inferior-octave-process-live-p)
  1331. (set-process-query-on-exit-flag inferior-octave-process nil)
  1332. (process-send-string inferior-octave-process "quit;\n")
  1333. (accept-process-output inferior-octave-process))
  1334. (kill-buffer inferior-octave-buffer)))
  1335. (defun octave-show-process-buffer ()
  1336. "Make sure that `inferior-octave-buffer' is displayed."
  1337. (interactive)
  1338. (if (get-buffer inferior-octave-buffer)
  1339. (display-buffer inferior-octave-buffer)
  1340. (message "No buffer named %s" inferior-octave-buffer)))
  1341. (defun octave-hide-process-buffer ()
  1342. "Delete all windows that display `inferior-octave-buffer'."
  1343. (interactive)
  1344. (if (get-buffer inferior-octave-buffer)
  1345. (delete-windows-on inferior-octave-buffer)
  1346. (message "No buffer named %s" inferior-octave-buffer)))
  1347. (defun octave-source-file (file)
  1348. "Execute FILE in the inferior Octave process.
  1349. This is done using Octave's source function. FILE defaults to
  1350. current buffer file unless called with a prefix arg \\[universal-argument]."
  1351. (interactive (list (or (and (not current-prefix-arg) buffer-file-name)
  1352. (read-file-name "File: " nil nil t))))
  1353. (or (stringp file)
  1354. (signal 'wrong-type-argument (list 'stringp file)))
  1355. (inferior-octave t)
  1356. (with-current-buffer inferior-octave-buffer
  1357. (comint-send-string inferior-octave-process
  1358. (format "source '%s'\n" file))))
  1359. (defun octave-send-region (beg end)
  1360. "Send current region to the inferior Octave process."
  1361. (interactive "r")
  1362. (inferior-octave t)
  1363. (let ((proc inferior-octave-process)
  1364. (string (buffer-substring-no-properties beg end))
  1365. line)
  1366. (with-current-buffer inferior-octave-buffer
  1367. ;; http://lists.gnu.org/archive/html/emacs-devel/2013-10/msg00095.html
  1368. (compilation-forget-errors)
  1369. (setq inferior-octave-output-list nil)
  1370. (while (not (string-equal string ""))
  1371. (if (string-match "\n" string)
  1372. (setq line (substring string 0 (match-beginning 0))
  1373. string (substring string (match-end 0)))
  1374. (setq line string string ""))
  1375. (setq inferior-octave-receive-in-progress t)
  1376. (inferior-octave-send-list-and-digest (list (concat line "\n")))
  1377. (while inferior-octave-receive-in-progress
  1378. (accept-process-output proc))
  1379. (insert-before-markers
  1380. (mapconcat 'identity
  1381. (append
  1382. (if octave-send-echo-input (list line) (list ""))
  1383. inferior-octave-output-list
  1384. (list inferior-octave-output-string))
  1385. "\n")))))
  1386. (if octave-send-show-buffer
  1387. (display-buffer inferior-octave-buffer)))
  1388. (defun octave-send-buffer ()
  1389. "Send current buffer to the inferior Octave process."
  1390. (interactive)
  1391. (octave-send-region (point-min) (point-max)))
  1392. (defun octave-send-block ()
  1393. "Send current Octave block to the inferior Octave process."
  1394. (interactive)
  1395. (save-excursion
  1396. (octave-mark-block)
  1397. (octave-send-region (point) (mark))))
  1398. (defun octave-send-defun ()
  1399. "Send current Octave function to the inferior Octave process."
  1400. (interactive)
  1401. (save-excursion
  1402. (mark-defun)
  1403. (octave-send-region (point) (mark))))
  1404. (defun octave-send-line (&optional arg)
  1405. "Send current Octave code line to the inferior Octave process.
  1406. With positive prefix ARG, send that many lines.
  1407. If `octave-send-line-auto-forward' is non-nil, go to the next unsent
  1408. code line."
  1409. (interactive "P")
  1410. (or arg (setq arg 1))
  1411. (if (> arg 0)
  1412. (let (beg end)
  1413. (beginning-of-line)
  1414. (setq beg (point))
  1415. (octave-next-code-line (- arg 1))
  1416. (end-of-line)
  1417. (setq end (point))
  1418. (if octave-send-line-auto-forward
  1419. (octave-next-code-line 1))
  1420. (octave-send-region beg end))))
  1421. (defun octave-eval-print-last-sexp ()
  1422. "Evaluate Octave sexp before point and print value into current buffer."
  1423. (interactive)
  1424. (inferior-octave t)
  1425. (let ((standard-output (current-buffer))
  1426. (print-escape-newlines nil)
  1427. (opoint (point)))
  1428. (terpri)
  1429. (prin1
  1430. (save-excursion
  1431. (forward-sexp -1)
  1432. (inferior-octave-send-list-and-digest
  1433. (list (concat (buffer-substring-no-properties (point) opoint)
  1434. "\n")))
  1435. (mapconcat 'identity inferior-octave-output-list "\n")))
  1436. (terpri)))
  1437. (defcustom octave-eldoc-message-style 'auto
  1438. "Octave eldoc message style: auto, oneline, multiline."
  1439. :type '(choice (const :tag "Automatic" auto)
  1440. (const :tag "One Line" oneline)
  1441. (const :tag "Multi Line" multiline))
  1442. :version "24.4")
  1443. ;; (FN SIGNATURE1 SIGNATURE2 ...)
  1444. (defvar octave-eldoc-cache nil)
  1445. (defun octave-eldoc-function-signatures (fn)
  1446. (unless (equal fn (car octave-eldoc-cache))
  1447. (inferior-octave-send-list-and-digest
  1448. (list (format "print_usage ('%s');\n" fn)))
  1449. (let (result)
  1450. (dolist (line inferior-octave-output-list)
  1451. (when (string-match
  1452. "\\s-*\\(?:--[^:]+\\|usage\\):\\s-*\\(.*\\)$"
  1453. line)
  1454. (push (match-string 1 line) result)))
  1455. (setq octave-eldoc-cache
  1456. (cons (substring-no-properties fn)
  1457. (nreverse result)))))
  1458. (cdr octave-eldoc-cache))
  1459. (defun octave-eldoc-function ()
  1460. "A function for `eldoc-documentation-function' (which see)."
  1461. (when (inferior-octave-process-live-p)
  1462. (let* ((ppss (syntax-ppss))
  1463. (paren-pos (cadr ppss))
  1464. (fn (save-excursion
  1465. (if (and paren-pos
  1466. ;; PAREN-POS must be after the prompt
  1467. (>= paren-pos
  1468. (if (eq (get-buffer-process (current-buffer))
  1469. inferior-octave-process)
  1470. (process-mark inferior-octave-process)
  1471. (point-min)))
  1472. (or (not (eq (get-buffer-process (current-buffer))
  1473. inferior-octave-process))
  1474. (< (process-mark inferior-octave-process)
  1475. paren-pos))
  1476. (eq (char-after paren-pos) ?\())
  1477. (goto-char paren-pos)
  1478. (setq paren-pos nil))
  1479. (when (or (< (skip-syntax-backward "-") 0) paren-pos)
  1480. (thing-at-point 'symbol))))
  1481. (sigs (and fn (octave-eldoc-function-signatures fn)))
  1482. (oneline (mapconcat 'identity sigs
  1483. (propertize " | " 'face 'warning)))
  1484. (multiline (mapconcat (lambda (s) (concat "-- " s)) sigs "\n")))
  1485. ;;
  1486. ;; Return the value according to style.
  1487. (pcase octave-eldoc-message-style
  1488. (`auto (if (< (length oneline) (window-width (minibuffer-window)))
  1489. oneline
  1490. multiline))
  1491. (`oneline oneline)
  1492. (`multiline multiline)))))
  1493. (defcustom octave-help-buffer "*Octave Help*"
  1494. "Buffer name for `octave-help'."
  1495. :type 'string
  1496. :version "24.4")
  1497. ;; Used in a mode derived from help-mode.
  1498. (declare-function help-button-action "help-mode" (button))
  1499. (define-button-type 'octave-help-file
  1500. 'follow-link t
  1501. 'action #'help-button-action
  1502. 'help-function 'octave-find-definition)
  1503. (define-button-type 'octave-help-function
  1504. 'follow-link t
  1505. 'action (lambda (b)
  1506. (octave-help
  1507. (buffer-substring (button-start b) (button-end b)))))
  1508. (defvar octave-help-mode-map
  1509. (let ((map (make-sparse-keymap)))
  1510. (define-key map "\M-." 'octave-find-definition)
  1511. (define-key map "\C-hd" 'octave-help)
  1512. (define-key map "\C-ha" 'octave-lookfor)
  1513. map))
  1514. (define-derived-mode octave-help-mode help-mode "OctHelp"
  1515. "Major mode for displaying Octave documentation."
  1516. :abbrev-table nil
  1517. :syntax-table octave-mode-syntax-table
  1518. (eval-and-compile (require 'help-mode))
  1519. ;; Don't highlight `EXAMPLE' as elisp symbols by using a regexp that
  1520. ;; can never match.
  1521. (setq-local help-xref-symbol-regexp "x\\`"))
  1522. (defun octave-help (fn)
  1523. "Display the documentation of FN."
  1524. (interactive (list (octave-completing-read)))
  1525. (inferior-octave-send-list-and-digest
  1526. (list (format "help ('%s');\n" fn)))
  1527. (let ((lines inferior-octave-output-list)
  1528. (inhibit-read-only t))
  1529. (when (string-match "error: \\(.*\\)$" (car lines))
  1530. (error "%s" (match-string 1 (car lines))))
  1531. (with-help-window octave-help-buffer
  1532. (princ (mapconcat 'identity lines "\n"))
  1533. (with-current-buffer octave-help-buffer
  1534. ;; Bound to t so that `help-buffer' returns current buffer for
  1535. ;; `help-setup-xref'.
  1536. (let ((help-xref-following t))
  1537. (help-setup-xref (list 'octave-help fn)
  1538. (called-interactively-p 'interactive)))
  1539. ;; Note: can be turned off by suppress_verbose_help_message.
  1540. ;;
  1541. ;; Remove boring trailing text: Additional help for built-in functions
  1542. ;; and operators ...
  1543. (goto-char (point-max))
  1544. (when (search-backward "\n\n\n" nil t)
  1545. (goto-char (match-beginning 0))
  1546. (delete-region (point) (point-max)))
  1547. ;; File name highlight
  1548. (goto-char (point-min))
  1549. (when (re-search-forward "from the file \\(.*\\)$"
  1550. (line-end-position)
  1551. t)
  1552. (let* ((file (match-string 1))
  1553. (dir (file-name-directory
  1554. (directory-file-name (file-name-directory file)))))
  1555. (replace-match "" nil nil nil 1)
  1556. (insert (substitute-command-keys "`"))
  1557. ;; Include the parent directory which may be regarded as
  1558. ;; the category for the FN.
  1559. (help-insert-xref-button (file-relative-name file dir)
  1560. 'octave-help-file fn)
  1561. (insert (substitute-command-keys "'"))))
  1562. ;; Make 'See also' clickable.
  1563. (with-syntax-table octave-mode-syntax-table
  1564. (when (re-search-forward "^\\s-*See also:" nil t)
  1565. (let ((end (save-excursion (re-search-forward "^\\s-*$" nil t))))
  1566. (while (re-search-forward
  1567. "\\s-*\\([^,\n]+?\\)\\s-*\\(?:[,]\\|[.]?$\\)" end t)
  1568. (make-text-button (match-beginning 1) (match-end 1)
  1569. :type 'octave-help-function)))))
  1570. (octave-help-mode)))))
  1571. (defun octave-lookfor (str &optional all)
  1572. "Search for the string STR in all function help strings.
  1573. If ALL is non-nil search the entire help string else only search the first
  1574. sentence."
  1575. (interactive "sSearch for: \nP")
  1576. (inferior-octave-send-list-and-digest
  1577. (list (format "lookfor (%s'%s');\n"
  1578. (if all "'-all', " "")
  1579. str)))
  1580. (let ((lines inferior-octave-output-list))
  1581. (when (and (stringp (car lines))
  1582. (string-match "error: \\(.*\\)$" (car lines)))
  1583. (error "%s" (match-string 1 (car lines))))
  1584. (with-help-window octave-help-buffer
  1585. (with-current-buffer octave-help-buffer
  1586. (if lines
  1587. (insert (mapconcat 'identity lines "\n"))
  1588. (insert (format "Nothing found for \"%s\".\n" str)))
  1589. ;; Bound to t so that `help-buffer' returns current buffer for
  1590. ;; `help-setup-xref'.
  1591. (let ((help-xref-following t))
  1592. (help-setup-xref (list 'octave-lookfor str all)
  1593. (called-interactively-p 'interactive)))
  1594. (goto-char (point-min))
  1595. (when lines
  1596. (while (re-search-forward "^\\([^[:blank:]]+\\) " nil 'noerror)
  1597. (make-text-button (match-beginning 1) (match-end 1)
  1598. :type 'octave-help-function)))
  1599. (unless all
  1600. (goto-char (point-max))
  1601. (insert "\nRetry with ")
  1602. (insert-text-button "'-all'"
  1603. 'follow-link t
  1604. 'action #'(lambda (_b)
  1605. (octave-lookfor str '-all)))
  1606. (insert ".\n"))
  1607. (octave-help-mode)))))
  1608. (defcustom octave-source-directories nil
  1609. "A list of directories for Octave sources.
  1610. If the environment variable OCTAVE_SRCDIR is set, it is searched first."
  1611. :type '(repeat directory)
  1612. :version "24.4")
  1613. (defun octave-source-directories ()
  1614. (let ((srcdir (or (and inferior-octave-process
  1615. (process-get inferior-octave-process 'octave-srcdir))
  1616. (getenv "OCTAVE_SRCDIR"))))
  1617. (if srcdir
  1618. (cons srcdir octave-source-directories)
  1619. octave-source-directories)))
  1620. (defvar octave-find-definition-filename-function
  1621. #'octave-find-definition-default-filename)
  1622. (defun octave-find-definition-default-filename (name)
  1623. "Default value for `octave-find-definition-filename-function'."
  1624. (pcase (file-name-extension name)
  1625. (`"oct"
  1626. (octave-find-definition-default-filename
  1627. (concat "libinterp/dldfcn/"
  1628. (file-name-sans-extension (file-name-nondirectory name))
  1629. ".cc")))
  1630. (`"cc"
  1631. (let ((file (or (locate-file name (octave-source-directories))
  1632. (locate-file (file-name-nondirectory name)
  1633. (octave-source-directories)))))
  1634. (or (and file (file-exists-p file))
  1635. (error "File `%s' not found" name))
  1636. file))
  1637. (`"mex"
  1638. (if (yes-or-no-p (format-message "File `%s' may be binary; open? "
  1639. (file-name-nondirectory name)))
  1640. name
  1641. (user-error "Aborted")))
  1642. (_ name)))
  1643. (defvar find-tag-marker-ring)
  1644. (defun octave-find-definition (fn)
  1645. "Find the definition of FN.
  1646. Functions implemented in C++ can be found if
  1647. variable `octave-source-directories' is set correctly."
  1648. (interactive (list (octave-completing-read)))
  1649. (require 'etags)
  1650. (let ((orig (point)))
  1651. (if (and (derived-mode-p 'octave-mode)
  1652. (octave-goto-function-definition fn))
  1653. (ring-insert find-tag-marker-ring (copy-marker orig))
  1654. (inferior-octave-send-list-and-digest
  1655. ;; help NAME is more verbose
  1656. (list (format "\
  1657. if iskeyword('%s') disp('`%s'' is a keyword') else which('%s') endif\n"
  1658. fn fn fn)))
  1659. (let (line file)
  1660. ;; Skip garbage lines such as
  1661. ;; warning: fmincg.m: possible Matlab-style ....
  1662. (while (and (not file) (consp inferior-octave-output-list))
  1663. (setq line (pop inferior-octave-output-list))
  1664. (when (string-match "from the file \\(.*\\)$" line)
  1665. (setq file (match-string 1 line))))
  1666. (if (not file)
  1667. (user-error "%s" (or line (format-message "`%s' not found" fn)))
  1668. (ring-insert find-tag-marker-ring (point-marker))
  1669. (setq file (funcall octave-find-definition-filename-function file))
  1670. (when file
  1671. (find-file file)
  1672. (octave-goto-function-definition fn)))))))
  1673. (provide 'octave)
  1674. ;;; octave.el ends here