octave.el 72 KB

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