octave.el 72 KB

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