rst.el 146 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196
  1. ;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
  2. ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
  3. ;; Maintainer: Stefan Merten <smerten@oekonux.de>
  4. ;; Author: Stefan Merten <smerten@oekonux.de>,
  5. ;; Martin Blais <blais@furius.ca>,
  6. ;; David Goodger <goodger@python.org>,
  7. ;; Wei-Wei Guo <wwguocn@gmail.com>
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; This package provides major mode rst-mode, which supports documents marked
  21. ;; up using the reStructuredText format. Support includes font locking as well
  22. ;; as a lot of convenience functions for editing. It does this by defining a
  23. ;; Emacs major mode: rst-mode (ReST). This mode is derived from text-mode.
  24. ;; This package also contains:
  25. ;;
  26. ;; - Functions to automatically adjust and cycle the section underline
  27. ;; adornments;
  28. ;; - A mode that displays the table of contents and allows you to jump anywhere
  29. ;; from it;
  30. ;; - Functions to insert and automatically update a TOC in your source
  31. ;; document;
  32. ;; - Function to insert list, processing item bullets and enumerations
  33. ;; automatically;
  34. ;; - Font-lock highlighting of most reStructuredText structures;
  35. ;; - Indentation and filling according to reStructuredText syntax;
  36. ;; - Cursor movement according to reStructuredText syntax;
  37. ;; - Some other convenience functions.
  38. ;;
  39. ;; See the accompanying document in the docutils documentation about
  40. ;; the contents of this package and how to use it.
  41. ;;
  42. ;; For more information about reStructuredText, see
  43. ;; http://docutils.sourceforge.net/rst.html
  44. ;;
  45. ;; For full details on how to use the contents of this file, see
  46. ;; http://docutils.sourceforge.net/docs/user/emacs.html
  47. ;;
  48. ;;
  49. ;; There are a number of convenient key bindings provided by rst-mode.
  50. ;; For more on bindings, see rst-mode-map below. There are also many variables
  51. ;; that can be customized, look for defcustom in this file.
  52. ;;
  53. ;; If you use the table-of-contents feature, you may want to add a hook to
  54. ;; update the TOC automatically every time you adjust a section title::
  55. ;;
  56. ;; (add-hook 'rst-adjust-hook 'rst-toc-update)
  57. ;;
  58. ;; Syntax highlighting: font-lock is enabled by default. If you want to turn
  59. ;; off syntax highlighting to rst-mode, you can use the following::
  60. ;;
  61. ;; (setq font-lock-global-modes '(not rst-mode ...))
  62. ;;
  63. ;;
  64. ;;
  65. ;; Customization is done by customizable variables contained in customization
  66. ;; group "rst" and subgroups. Group "rst" is contained in the "wp" group.
  67. ;;
  68. ;;; DOWNLOAD
  69. ;; The latest release of this file lies in the docutils source code repository:
  70. ;; http://docutils.svn.sourceforge.net/svnroot/docutils/trunk/docutils/tools/editors/emacs/rst.el
  71. ;;; INSTALLATION
  72. ;; Add the following lines to your `.emacs' file:
  73. ;;
  74. ;; (require 'rst)
  75. ;;
  76. ;; If you are using `.txt' as a standard extension for reST files as
  77. ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
  78. ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
  79. ;; provides to set the major mode automatically. For instance you may use::
  80. ;;
  81. ;; .. -*- mode: rst -*-
  82. ;;
  83. ;; in the very first line of your file. The following code is useful if you
  84. ;; want automatically enter rst-mode from any file with compatible extensions:
  85. ;;
  86. ;; (setq auto-mode-alist
  87. ;; (append '(("\\.txt\\'" . rst-mode)
  88. ;; ("\\.rst\\'" . rst-mode)
  89. ;; ("\\.rest\\'" . rst-mode)) auto-mode-alist))
  90. ;;
  91. ;;; Code:
  92. ;; Only use of macros is allowed - may be replaced by `cl-lib' some time.
  93. (eval-when-compile
  94. (require 'cl))
  95. ;; Redefine some functions from `cl.el' in a proper namespace until they may be
  96. ;; used from there.
  97. (defun rst-signum (x)
  98. "Return 1 if X is positive, -1 if negative, 0 if zero."
  99. (cond
  100. ((> x 0) 1)
  101. ((< x 0) -1)
  102. (t 0)))
  103. (defun rst-some (seq &optional pred)
  104. "Return non-nil if any element of SEQ yields non-nil when PRED is applied.
  105. Apply PRED to each element of list SEQ until the first non-nil
  106. result is yielded and return this result. PRED defaults to
  107. `identity'."
  108. (unless pred
  109. (setq pred 'identity))
  110. (catch 'rst-some
  111. (dolist (elem seq)
  112. (let ((r (funcall pred elem)))
  113. (when r
  114. (throw 'rst-some r))))))
  115. (defun rst-position-if (pred seq)
  116. "Return position of first element satisfying PRED in list SEQ or nil."
  117. (catch 'rst-position-if
  118. (let ((i 0))
  119. (dolist (elem seq)
  120. (when (funcall pred elem)
  121. (throw 'rst-position-if i))
  122. (incf i)))))
  123. (defun rst-position (elem seq)
  124. "Return position of ELEM in list SEQ or nil.
  125. Comparison done with `equal'."
  126. ;; Create a closure containing `elem' so the `lambda' always sees our
  127. ;; parameter instead of an `elem' which may be in dynamic scope at the time
  128. ;; of execution of the `lambda'.
  129. (lexical-let ((elem elem))
  130. (rst-position-if (function (lambda (e)
  131. (equal elem e)))
  132. seq)))
  133. ;; FIXME: Check whether complicated `defconst's can be embedded in
  134. ;; `eval-when-compile'.
  135. ;; FIXME: Check whether `lambda's can be embedded in `function'.
  136. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  137. ;; Versions
  138. (defun rst-extract-version (delim-re head-re re tail-re var &optional default)
  139. "Extract the version from a variable according to the given regexes.
  140. Return the version after regex DELIM-RE and HEAD-RE matching RE
  141. and before TAIL-RE and DELIM-RE in VAR or DEFAULT for no match."
  142. (if (string-match
  143. (concat delim-re head-re "\\(" re "\\)" tail-re delim-re)
  144. var)
  145. (match-string 1 var)
  146. default))
  147. ;; Use CVSHeader to really get information from CVS and not other version
  148. ;; control systems.
  149. (defconst rst-cvs-header
  150. "$CVSHeader: sm/rst_el/rst.el,v 1.282 2012-06-06 19:16:55 stefan Exp $")
  151. (defconst rst-cvs-rev
  152. (rst-extract-version "\\$" "CVSHeader: \\S + " "[0-9]+\\(?:\\.[0-9]+\\)+"
  153. " .*" rst-cvs-header "0.0")
  154. "The CVS revision of this file. CVS revision is the development revision.")
  155. (defconst rst-cvs-timestamp
  156. (rst-extract-version "\\$" "CVSHeader: \\S + \\S + "
  157. "[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+" " .*"
  158. rst-cvs-header "1970-01-01 00:00:00")
  159. "The CVS time stamp of this file.")
  160. ;; Use LastChanged... to really get information from SVN.
  161. (defconst rst-svn-rev
  162. (rst-extract-version "\\$" "LastChangedRevision: " "[0-9]+" " "
  163. "$LastChangedRevision: 7399 $")
  164. "The SVN revision of this file.
  165. SVN revision is the upstream (docutils) revision.")
  166. (defconst rst-svn-timestamp
  167. (rst-extract-version "\\$" "LastChangedDate: " ".+?+" " "
  168. "$LastChangedDate: 2012-04-29 17:01:05 +0200 (Sun, 29 Apr 2012) $")
  169. "The SVN time stamp of this file.")
  170. ;; Maintained by the release process.
  171. (defconst rst-official-version
  172. (rst-extract-version "%" "OfficialVersion: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
  173. "%OfficialVersion: 1.2.1 %")
  174. "Official version of the package.")
  175. (defconst rst-official-cvs-rev
  176. (rst-extract-version "[%$]" "Revision: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
  177. "%Revision: 1.256 %")
  178. "CVS revision of this file in the official version.")
  179. ;; FIXME: Version differences due to SVN checkin must not change this.
  180. (defconst rst-version
  181. (if (equal rst-official-cvs-rev rst-cvs-rev)
  182. rst-official-version
  183. (format "%s (development %s [%s])" rst-official-version
  184. rst-cvs-rev rst-cvs-timestamp))
  185. "The version string.
  186. Starts with the current official version. For developer versions
  187. in parentheses follows the development revision and the time stamp.")
  188. (defconst rst-package-emacs-version-alist
  189. '(("1.0.0" . "24.2")
  190. ("1.1.0" . "24.2")
  191. ("1.2.0" . "24.2")
  192. ("1.2.1" . "24.2")
  193. ("1.3.0" . "24.2")))
  194. (unless (assoc rst-official-version rst-package-emacs-version-alist)
  195. (error "Version %s not listed in `rst-package-emacs-version-alist'"
  196. rst-version))
  197. (add-to-list 'customize-package-emacs-version-alist
  198. (cons 'ReST rst-package-emacs-version-alist))
  199. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  200. ;; Initialize customization
  201. (defgroup rst nil "Support for reStructuredText documents."
  202. :group 'wp
  203. :version "23.1"
  204. :link '(url-link "http://docutils.sourceforge.net/rst.html"))
  205. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  206. ;; Facilities for regular expressions used everywhere
  207. ;; The trailing numbers in the names give the number of referenceable regex
  208. ;; groups contained in the regex.
  209. ;; Used to be customizable but really is not customizable but fixed by the reST
  210. ;; syntax.
  211. (defconst rst-bullets
  212. ;; Sorted so they can form a character class when concatenated.
  213. '(?- ?* ?+ ?\u2022 ?\u2023 ?\u2043)
  214. "List of all possible bullet characters for bulleted lists.")
  215. (defconst rst-uri-schemes
  216. '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap"
  217. "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp"
  218. "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
  219. "Supported URI schemes.")
  220. (defconst rst-adornment-chars
  221. ;; Sorted so they can form a character class when concatenated.
  222. '(?\]
  223. ?! ?\" ?# ?$ ?% ?& ?' ?\( ?\) ?* ?+ ?, ?. ?/ ?: ?\; ?< ?= ?> ?? ?@ ?\[ ?\\
  224. ?^ ?_ ?` ?{ ?| ?} ?~
  225. ?-)
  226. "Characters which may be used in adornments for sections and transitions.")
  227. (defconst rst-max-inline-length
  228. 1000
  229. "Maximum length of inline markup to recognize.")
  230. (defconst rst-re-alist-def
  231. ;; `*-beg' matches * at the beginning of a line.
  232. ;; `*-end' matches * at the end of a line.
  233. ;; `*-prt' matches a part of *.
  234. ;; `*-tag' matches *.
  235. ;; `*-sta' matches the start of * which may be followed by respective content.
  236. ;; `*-pfx' matches the delimiter left of *.
  237. ;; `*-sfx' matches the delimiter right of *.
  238. ;; `*-hlp' helper for *.
  239. ;;
  240. ;; A trailing number says how many referenceable groups are contained.
  241. `(
  242. ;; Horizontal white space (`hws')
  243. (hws-prt "[\t ]")
  244. (hws-tag hws-prt "*") ; Optional sequence of horizontal white space.
  245. (hws-sta hws-prt "+") ; Mandatory sequence of horizontal white space.
  246. ;; Lines (`lin')
  247. (lin-beg "^" hws-tag) ; Beginning of a possibly indented line.
  248. (lin-end hws-tag "$") ; End of a line with optional trailing white space.
  249. (linemp-tag "^" hws-tag "$") ; Empty line with optional white space.
  250. ;; Various tags and parts
  251. (ell-tag "\\.\\.\\.") ; Ellipsis
  252. (bul-tag ,(concat "[" rst-bullets "]")) ; A bullet.
  253. (ltr-tag "[a-zA-Z]") ; A letter enumerator tag.
  254. (num-prt "[0-9]") ; A number enumerator part.
  255. (num-tag num-prt "+") ; A number enumerator tag.
  256. (rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part.
  257. (rom-tag rom-prt "+") ; A roman enumerator tag.
  258. (aut-tag "#") ; An automatic enumerator tag.
  259. (dcl-tag "::") ; Double colon.
  260. ;; Block lead in (`bli')
  261. (bli-sfx (:alt hws-sta "$")) ; Suffix of a block lead-in with *optional*
  262. ; immediate content.
  263. ;; Various starts
  264. (bul-sta bul-tag bli-sfx) ; Start of a bulleted item.
  265. ;; Explicit markup tag (`exm')
  266. (exm-tag "\\.\\.")
  267. (exm-sta exm-tag hws-sta)
  268. (exm-beg lin-beg exm-sta)
  269. ;; Counters in enumerations (`cnt')
  270. (cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag)) ; An arbitrary counter.
  271. (cntexp-tag (:alt ltr-tag num-tag rom-tag)) ; An arbitrary explicit counter.
  272. ;; Enumerator (`enm')
  273. (enmany-tag (:alt
  274. (:seq cntany-tag "\\.")
  275. (:seq "(?" cntany-tag ")"))) ; An arbitrary enumerator.
  276. (enmexp-tag (:alt
  277. (:seq cntexp-tag "\\.")
  278. (:seq "(?" cntexp-tag ")"))) ; An arbitrary explicit
  279. ; enumerator.
  280. (enmaut-tag (:alt
  281. (:seq aut-tag "\\.")
  282. (:seq "(?" aut-tag ")"))) ; An automatic enumerator.
  283. (enmany-sta enmany-tag bli-sfx) ; An arbitrary enumerator start.
  284. (enmexp-sta enmexp-tag bli-sfx) ; An arbitrary explicit enumerator start.
  285. (enmexp-beg lin-beg enmexp-sta) ; An arbitrary explicit enumerator start
  286. ; at the beginning of a line.
  287. ;; Items may be enumerated or bulleted (`itm')
  288. (itmany-tag (:alt enmany-tag bul-tag)) ; An arbitrary item tag.
  289. (itmany-sta-1 (:grp itmany-tag) bli-sfx) ; An arbitrary item start, group
  290. ; is the item tag.
  291. (itmany-beg-1 lin-beg itmany-sta-1) ; An arbitrary item start at the
  292. ; beginning of a line, group is the
  293. ; item tag.
  294. ;; Inline markup (`ilm')
  295. (ilm-pfx (:alt "^" hws-prt "[-'\"([{<\u2018\u201c\u00ab\u2019/:]"))
  296. (ilm-sfx (:alt "$" hws-prt "[]-'\")}>\u2019\u201d\u00bb/:.,;!?\\]"))
  297. ;; Inline markup content (`ilc')
  298. (ilcsgl-tag "\\S ") ; A single non-white character.
  299. (ilcast-prt (:alt "[^*\\]" "\\\\.")) ; Part of non-asterisk content.
  300. (ilcbkq-prt (:alt "[^`\\]" "\\\\.")) ; Part of non-backquote content.
  301. (ilcbkqdef-prt (:alt "[^`\\\n]" "\\\\.")) ; Part of non-backquote
  302. ; definition.
  303. (ilcbar-prt (:alt "[^|\\]" "\\\\.")) ; Part of non-vertical-bar content.
  304. (ilcbardef-prt (:alt "[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar
  305. ; definition.
  306. (ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content.
  307. (ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content.
  308. (ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content.
  309. (ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length)) ; Repeat count.
  310. (ilcast-tag (:alt ilcsgl-tag
  311. (:seq ilcsgl-tag
  312. ilcast-prt ilcrep-hlp
  313. ilcast-sfx))) ; Non-asterisk content.
  314. (ilcbkq-tag (:alt ilcsgl-tag
  315. (:seq ilcsgl-tag
  316. ilcbkq-prt ilcrep-hlp
  317. ilcbkq-sfx))) ; Non-backquote content.
  318. (ilcbkqdef-tag (:alt ilcsgl-tag
  319. (:seq ilcsgl-tag
  320. ilcbkqdef-prt ilcrep-hlp
  321. ilcbkq-sfx))) ; Non-backquote definition.
  322. (ilcbar-tag (:alt ilcsgl-tag
  323. (:seq ilcsgl-tag
  324. ilcbar-prt ilcrep-hlp
  325. ilcbar-sfx))) ; Non-vertical-bar content.
  326. (ilcbardef-tag (:alt ilcsgl-tag
  327. (:seq ilcsgl-tag
  328. ilcbardef-prt ilcrep-hlp
  329. ilcbar-sfx))) ; Non-vertical-bar definition.
  330. ;; Fields (`fld')
  331. (fldnam-prt (:alt "[^:\n]" "\\\\:")) ; Part of a field name.
  332. (fldnam-tag fldnam-prt "+") ; A field name.
  333. (fld-tag ":" fldnam-tag ":") ; A field marker.
  334. ;; Options (`opt')
  335. (optsta-tag (:alt "[-+/]" "--")) ; Start of an option.
  336. (optnam-tag "\\sw" (:alt "-" "\\sw") "*") ; Name of an option.
  337. (optarg-tag (:shy "[ =]\\S +")) ; Option argument.
  338. (optsep-tag (:shy "," hws-prt)) ; Separator between options.
  339. (opt-tag (:shy optsta-tag optnam-tag optarg-tag "?")) ; A complete option.
  340. ;; Footnotes and citations (`fnc')
  341. (fncnam-prt "[^\]\n]") ; Part of a footnote or citation name.
  342. (fncnam-tag fncnam-prt "+") ; A footnote or citation name.
  343. (fnc-tag "\\[" fncnam-tag "]") ; A complete footnote or citation tag.
  344. (fncdef-tag-2 (:grp exm-sta)
  345. (:grp fnc-tag)) ; A complete footnote or citation definition
  346. ; tag. First group is the explicit markup
  347. ; start, second group is the footnote /
  348. ; citation tag.
  349. (fnc-sta-2 fncdef-tag-2 bli-sfx) ; Start of a footnote or citation
  350. ; definition. First group is the explicit
  351. ; markup start, second group is the
  352. ; footnote / citation tag.
  353. ;; Substitutions (`sub')
  354. (sub-tag "|" ilcbar-tag "|") ; A complete substitution tag.
  355. (subdef-tag "|" ilcbardef-tag "|") ; A complete substitution definition
  356. ; tag.
  357. ;; Symbol (`sym')
  358. (sym-tag (:shy "\\sw+" (:shy "\\s_\\sw+") "*"))
  359. ;; URIs (`uri')
  360. (uri-tag (:alt ,@rst-uri-schemes))
  361. ;; Adornment (`ado')
  362. (ado-prt "[" ,(concat rst-adornment-chars) "]")
  363. (adorep3-hlp "\\{3,\\}") ; There must be at least 3 characters because
  364. ; otherwise explicit markup start would be
  365. ; recognized.
  366. (adorep2-hlp "\\{2,\\}") ; As `adorep3-hlp' but when the first of three
  367. ; characters is matched differently.
  368. (ado-tag-1-1 (:grp ado-prt)
  369. "\\1" adorep2-hlp) ; A complete adornment, group is the first
  370. ; adornment character and MUST be the FIRST
  371. ; group in the whole expression.
  372. (ado-tag-1-2 (:grp ado-prt)
  373. "\\2" adorep2-hlp) ; A complete adornment, group is the first
  374. ; adornment character and MUST be the
  375. ; SECOND group in the whole expression.
  376. (ado-beg-2-1 "^" (:grp ado-tag-1-2)
  377. lin-end) ; A complete adornment line; first group is the whole
  378. ; adornment and MUST be the FIRST group in the whole
  379. ; expression; second group is the first adornment
  380. ; character.
  381. ;; Titles (`ttl')
  382. (ttl-tag "\\S *\\w\\S *") ; A title text.
  383. (ttl-beg lin-beg ttl-tag) ; A title text at the beginning of a line.
  384. ;; Directives and substitution definitions (`dir')
  385. (dir-tag-3 (:grp exm-sta)
  386. (:grp (:shy subdef-tag hws-sta) "?")
  387. (:grp sym-tag dcl-tag)) ; A directive or substitution definition
  388. ; tag. First group is explicit markup
  389. ; start, second group is a possibly
  390. ; empty substitution tag, third group is
  391. ; the directive tag including the double
  392. ; colon.
  393. (dir-sta-3 dir-tag-3 bli-sfx) ; Start of a directive or substitution
  394. ; definition. Groups are as in dir-tag-3.
  395. ;; Literal block (`lit')
  396. (lit-sta-2 (:grp (:alt "[^.\n]" "\\.[^.\n]") ".*") "?"
  397. (:grp dcl-tag) "$") ; Start of a literal block. First group is
  398. ; any text before the double colon tag which
  399. ; may not exist, second group is the double
  400. ; colon tag.
  401. ;; Comments (`cmt')
  402. (cmt-sta-1 (:grp exm-sta) "[^\[|_\n]"
  403. (:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$")))
  404. "*$") ; Start of a comment block; first group is explicit markup
  405. ; start.
  406. ;; Paragraphs (`par')
  407. (par-tag- (:alt itmany-tag fld-tag opt-tag fncdef-tag-2 dir-tag-3 exm-tag)
  408. ) ; Tag at the beginning of a paragraph; there may be groups in
  409. ; certain cases.
  410. )
  411. "Definition alist of relevant regexes.
  412. Each entry consists of the symbol naming the regex and an
  413. argument list for `rst-re'.")
  414. (defvar rst-re-alist) ; Forward declare to use it in `rst-re'.
  415. ;; FIXME: Use `sregex` or `rx` instead of re-inventing the wheel.
  416. (defun rst-re (&rest args)
  417. "Interpret ARGS as regular expressions and return a regex string.
  418. Each element of ARGS may be one of the following:
  419. A string which is inserted unchanged.
  420. A character which is resolved to a quoted regex.
  421. A symbol which is resolved to a string using `rst-re-alist-def'.
  422. A list with a keyword in the car. Each element of the cdr of such
  423. a list is recursively interpreted as ARGS. The results of this
  424. interpretation are concatenated according to the keyword.
  425. For the keyword `:seq' the results are simply concatenated.
  426. For the keyword `:shy' the results are concatenated and
  427. surrounded by a shy-group (\"\\(?:...\\)\").
  428. For the keyword `:alt' the results form an alternative (\"\\|\")
  429. which is shy-grouped (\"\\(?:...\\)\").
  430. For the keyword `:grp' the results are concatenated and form a
  431. referenceable group (\"\\(...\\)\").
  432. After interpretation of ARGS the results are concatenated as for
  433. `:seq'."
  434. (apply 'concat
  435. (mapcar
  436. (lambda (re)
  437. (cond
  438. ((stringp re)
  439. re)
  440. ((symbolp re)
  441. (cadr (assoc re rst-re-alist)))
  442. ((characterp re)
  443. (regexp-quote (char-to-string re)))
  444. ((listp re)
  445. (let ((nested
  446. (mapcar (lambda (elt)
  447. (rst-re elt))
  448. (cdr re))))
  449. (cond
  450. ((eq (car re) :seq)
  451. (mapconcat 'identity nested ""))
  452. ((eq (car re) :shy)
  453. (concat "\\(?:" (mapconcat 'identity nested "") "\\)"))
  454. ((eq (car re) :grp)
  455. (concat "\\(" (mapconcat 'identity nested "") "\\)"))
  456. ((eq (car re) :alt)
  457. (concat "\\(?:" (mapconcat 'identity nested "\\|") "\\)"))
  458. (t
  459. (error "Unknown list car: %s" (car re))))))
  460. (t
  461. (error "Unknown object type for building regex: %s" re))))
  462. args)))
  463. ;; FIXME: Remove circular dependency between `rst-re' and `rst-re-alist'.
  464. (with-no-warnings ; Silence byte-compiler about this construction.
  465. (defconst rst-re-alist
  466. ;; Shadow global value we are just defining so we can construct it step by
  467. ;; step.
  468. (let (rst-re-alist)
  469. (dolist (re rst-re-alist-def rst-re-alist)
  470. (setq rst-re-alist
  471. (nconc rst-re-alist
  472. (list (list (car re) (apply 'rst-re (cdr re))))))))
  473. "Alist mapping symbols from `rst-re-alist-def' to regex strings."))
  474. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  475. ;; Mode definition
  476. (defun rst-define-key (keymap key def &rest deprecated)
  477. "Bind like `define-key' but add deprecated key definitions.
  478. KEYMAP, KEY, and DEF are as in `define-key'. DEPRECATED key
  479. definitions should be in vector notation. These are defined as
  480. well but give an additional message."
  481. (define-key keymap key def)
  482. (dolist (dep-key deprecated)
  483. (define-key keymap dep-key
  484. `(lambda ()
  485. ,(format "Deprecated binding for %s, use \\[%s] instead." def def)
  486. (interactive)
  487. (call-interactively ',def)
  488. (message "[Deprecated use of key %s; use key %s instead]"
  489. (key-description (this-command-keys))
  490. (key-description ,key))))))
  491. ;; Key bindings.
  492. (defvar rst-mode-map
  493. (let ((map (make-sparse-keymap)))
  494. ;; \C-c is the general keymap.
  495. (rst-define-key map [?\C-c ?\C-h] 'describe-prefix-bindings)
  496. ;;
  497. ;; Section Adornments
  498. ;;
  499. ;; The adjustment function that adorns or rotates a section title.
  500. (rst-define-key map [?\C-c ?\C-=] 'rst-adjust [?\C-c ?\C-a t])
  501. (rst-define-key map [?\C-=] 'rst-adjust) ; (Does not work on the Mac OSX.)
  502. ;; \C-c \C-a is the keymap for adornments.
  503. (rst-define-key map [?\C-c ?\C-a ?\C-h] 'describe-prefix-bindings)
  504. ;; Display the hierarchy of adornments implied by the current document
  505. ;; contents.
  506. (rst-define-key map [?\C-c ?\C-a ?\C-d] 'rst-display-adornments-hierarchy)
  507. ;; Homogenize the adornments in the document.
  508. (rst-define-key map [?\C-c ?\C-a ?\C-s] 'rst-straighten-adornments
  509. [?\C-c ?\C-s])
  510. ;;
  511. ;; Section Movement and Selection
  512. ;;
  513. ;; Mark the subsection where the cursor is.
  514. (rst-define-key map [?\C-\M-h] 'rst-mark-section
  515. ;; Same as mark-defun sgml-mark-current-element.
  516. [?\C-c ?\C-m])
  517. ;; Move backward/forward between section titles.
  518. (rst-define-key map [?\C-\M-a] 'rst-backward-section
  519. ;; Same as beginning-of-defun.
  520. [?\C-c ?\C-n])
  521. (rst-define-key map [?\C-\M-e] 'rst-forward-section
  522. ;; Same as end-of-defun.
  523. [?\C-c ?\C-p])
  524. ;;
  525. ;; Operating on regions
  526. ;;
  527. ;; \C-c \C-r is the keymap for regions.
  528. (rst-define-key map [?\C-c ?\C-r ?\C-h] 'describe-prefix-bindings)
  529. ;; Makes region a line-block.
  530. (rst-define-key map [?\C-c ?\C-r ?\C-l] 'rst-line-block-region
  531. [?\C-c ?\C-d])
  532. ;; Shift region left or right according to tabs.
  533. (rst-define-key map [?\C-c ?\C-r tab] 'rst-shift-region
  534. [?\C-c ?\C-r t] [?\C-c ?\C-l t])
  535. ;;
  536. ;; Operating on lists
  537. ;;
  538. ;; \C-c \C-l is the keymap for lists.
  539. (rst-define-key map [?\C-c ?\C-l ?\C-h] 'describe-prefix-bindings)
  540. ;; Makes paragraphs in region as a bullet list.
  541. (rst-define-key map [?\C-c ?\C-l ?\C-b] 'rst-bullet-list-region
  542. [?\C-c ?\C-b])
  543. ;; Makes paragraphs in region as a enumeration.
  544. (rst-define-key map [?\C-c ?\C-l ?\C-e] 'rst-enumerate-region
  545. [?\C-c ?\C-e])
  546. ;; Converts bullets to an enumeration.
  547. (rst-define-key map [?\C-c ?\C-l ?\C-c] 'rst-convert-bullets-to-enumeration
  548. [?\C-c ?\C-v])
  549. ;; Make sure that all the bullets in the region are consistent.
  550. (rst-define-key map [?\C-c ?\C-l ?\C-s] 'rst-straighten-bullets-region
  551. [?\C-c ?\C-w])
  552. ;; Insert a list item.
  553. (rst-define-key map [?\C-c ?\C-l ?\C-i] 'rst-insert-list)
  554. ;;
  555. ;; Table-of-Contents Features
  556. ;;
  557. ;; \C-c \C-t is the keymap for table of contents.
  558. (rst-define-key map [?\C-c ?\C-t ?\C-h] 'describe-prefix-bindings)
  559. ;; Enter a TOC buffer to view and move to a specific section.
  560. (rst-define-key map [?\C-c ?\C-t ?\C-t] 'rst-toc)
  561. ;; Insert a TOC here.
  562. (rst-define-key map [?\C-c ?\C-t ?\C-i] 'rst-toc-insert
  563. [?\C-c ?\C-i])
  564. ;; Update the document's TOC (without changing the cursor position).
  565. (rst-define-key map [?\C-c ?\C-t ?\C-u] 'rst-toc-update
  566. [?\C-c ?\C-u])
  567. ;; Go to the section under the cursor (cursor must be in TOC).
  568. (rst-define-key map [?\C-c ?\C-t ?\C-j] 'rst-goto-section
  569. [?\C-c ?\C-f])
  570. ;;
  571. ;; Converting Documents from Emacs
  572. ;;
  573. ;; \C-c \C-c is the keymap for compilation.
  574. (rst-define-key map [?\C-c ?\C-c ?\C-h] 'describe-prefix-bindings)
  575. ;; Run one of two pre-configured toolset commands on the document.
  576. (rst-define-key map [?\C-c ?\C-c ?\C-c] 'rst-compile
  577. [?\C-c ?1])
  578. (rst-define-key map [?\C-c ?\C-c ?\C-a] 'rst-compile-alt-toolset
  579. [?\C-c ?2])
  580. ;; Convert the active region to pseudo-xml using the docutils tools.
  581. (rst-define-key map [?\C-c ?\C-c ?\C-x] 'rst-compile-pseudo-region
  582. [?\C-c ?3])
  583. ;; Convert the current document to PDF and launch a viewer on the results.
  584. (rst-define-key map [?\C-c ?\C-c ?\C-p] 'rst-compile-pdf-preview
  585. [?\C-c ?4])
  586. ;; Convert the current document to S5 slides and view in a web browser.
  587. (rst-define-key map [?\C-c ?\C-c ?\C-s] 'rst-compile-slides-preview
  588. [?\C-c ?5])
  589. map)
  590. "Keymap for reStructuredText mode commands.
  591. This inherits from Text mode.")
  592. ;; Abbrevs.
  593. (define-abbrev-table 'rst-mode-abbrev-table
  594. (mapcar (lambda (x) (append x '(nil 0 system)))
  595. '(("contents" ".. contents::\n..\n ")
  596. ("con" ".. contents::\n..\n ")
  597. ("cont" "[...]")
  598. ("skip" "\n\n[...]\n\n ")
  599. ("seq" "\n\n[...]\n\n ")
  600. ;; FIXME: Add footnotes, links, and more.
  601. ))
  602. "Abbrev table used while in `rst-mode'.")
  603. ;; Syntax table.
  604. (defvar rst-mode-syntax-table
  605. (let ((st (copy-syntax-table text-mode-syntax-table)))
  606. ;; FIXME: This must be rethought; at the very least ?. should not be a
  607. ;; symbol for `dabbrev' to work properly.
  608. (modify-syntax-entry ?$ "." st)
  609. (modify-syntax-entry ?% "." st)
  610. (modify-syntax-entry ?& "." st)
  611. (modify-syntax-entry ?' "." st)
  612. (modify-syntax-entry ?* "." st)
  613. (modify-syntax-entry ?+ "_" st)
  614. (modify-syntax-entry ?. "_" st)
  615. (modify-syntax-entry ?/ "." st)
  616. (modify-syntax-entry ?: "_" st)
  617. (modify-syntax-entry ?< "." st)
  618. (modify-syntax-entry ?= "." st)
  619. (modify-syntax-entry ?> "." st)
  620. (modify-syntax-entry ?\\ "\\" st)
  621. (modify-syntax-entry ?| "." st)
  622. (modify-syntax-entry ?_ "_" st)
  623. (modify-syntax-entry ?\u00ab "." st)
  624. (modify-syntax-entry ?\u00bb "." st)
  625. (modify-syntax-entry ?\u2018 "." st)
  626. (modify-syntax-entry ?\u2019 "." st)
  627. (modify-syntax-entry ?\u201c "." st)
  628. (modify-syntax-entry ?\u201d "." st)
  629. st)
  630. "Syntax table used while in `rst-mode'.")
  631. (defcustom rst-mode-hook nil
  632. "Hook run when `rst-mode' is turned on.
  633. The hook for `text-mode' is run before this one."
  634. :group 'rst
  635. :type '(hook))
  636. ;; Pull in variable definitions silencing byte-compiler.
  637. (require 'newcomment)
  638. ;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files
  639. ;; use *.txt, but this is too generic to be set as a default.
  640. ;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode)))
  641. ;;;###autoload
  642. (define-derived-mode rst-mode text-mode "ReST"
  643. "Major mode for editing reStructuredText documents.
  644. \\<rst-mode-map>
  645. Turning on `rst-mode' calls the normal hooks `text-mode-hook'
  646. and `rst-mode-hook'. This mode also supports font-lock
  647. highlighting.
  648. \\{rst-mode-map}"
  649. :abbrev-table rst-mode-abbrev-table
  650. :syntax-table rst-mode-syntax-table
  651. :group 'rst
  652. ;; Paragraph recognition.
  653. (set (make-local-variable 'paragraph-separate)
  654. (rst-re '(:alt
  655. "\f"
  656. lin-end)))
  657. (set (make-local-variable 'paragraph-start)
  658. (rst-re '(:alt
  659. "\f"
  660. lin-end
  661. (:seq hws-tag par-tag- bli-sfx))))
  662. ;; Indenting and filling.
  663. (set (make-local-variable 'indent-line-function) 'rst-indent-line)
  664. (set (make-local-variable 'adaptive-fill-mode) t)
  665. (set (make-local-variable 'adaptive-fill-regexp)
  666. (rst-re 'hws-tag 'par-tag- "?" 'hws-tag))
  667. (set (make-local-variable 'adaptive-fill-function) 'rst-adaptive-fill)
  668. (set (make-local-variable 'fill-paragraph-handle-comment) nil)
  669. ;; Comments.
  670. (set (make-local-variable 'comment-start) ".. ")
  671. (set (make-local-variable 'comment-start-skip)
  672. (rst-re 'lin-beg 'exm-tag 'bli-sfx))
  673. (set (make-local-variable 'comment-continue) " ")
  674. (set (make-local-variable 'comment-multi-line) t)
  675. (set (make-local-variable 'comment-use-syntax) nil)
  676. ;; reStructuredText has not really a comment ender but nil is not really a
  677. ;; permissible value.
  678. (set (make-local-variable 'comment-end) "")
  679. (set (make-local-variable 'comment-end-skip) nil)
  680. ;; Commenting in reStructuredText is very special so use our own set of
  681. ;; functions.
  682. (set (make-local-variable 'comment-line-break-function)
  683. 'rst-comment-line-break)
  684. (set (make-local-variable 'comment-indent-function)
  685. 'rst-comment-indent)
  686. (set (make-local-variable 'comment-insert-comment-function)
  687. 'rst-comment-insert-comment)
  688. (set (make-local-variable 'comment-region-function)
  689. 'rst-comment-region)
  690. (set (make-local-variable 'uncomment-region-function)
  691. 'rst-uncomment-region)
  692. ;; Font lock.
  693. (set (make-local-variable 'font-lock-defaults)
  694. '(rst-font-lock-keywords
  695. t nil nil nil
  696. (font-lock-multiline . t)
  697. (font-lock-mark-block-function . mark-paragraph)))
  698. (add-hook 'font-lock-extend-region-functions 'rst-font-lock-extend-region t)
  699. ;; Text after a changed line may need new fontification.
  700. (set (make-local-variable 'jit-lock-contextually) t))
  701. ;;;###autoload
  702. (define-minor-mode rst-minor-mode
  703. "Toggle ReST minor mode.
  704. With a prefix argument ARG, enable ReST minor mode if ARG is
  705. positive, and disable it otherwise. If called from Lisp, enable
  706. the mode if ARG is omitted or nil.
  707. When ReST minor mode is enabled, the ReST mode keybindings
  708. are installed on top of the major mode bindings. Use this
  709. for modes derived from Text mode, like Mail mode."
  710. ;; The initial value.
  711. nil
  712. ;; The indicator for the mode line.
  713. " ReST"
  714. ;; The minor mode bindings.
  715. rst-mode-map
  716. :group 'rst)
  717. ;; FIXME: can I somehow install these too?
  718. ;; :abbrev-table rst-mode-abbrev-table
  719. ;; :syntax-table rst-mode-syntax-table
  720. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  721. ;; Section Adornment Adjustment
  722. ;; ============================
  723. ;;
  724. ;; The following functions implement a smart automatic title sectioning feature.
  725. ;; The idea is that with the cursor sitting on a section title, we try to get as
  726. ;; much information from context and try to do the best thing automatically.
  727. ;; This function can be invoked many times and/or with prefix argument to rotate
  728. ;; between the various sectioning adornments.
  729. ;;
  730. ;; Definitions: the two forms of sectioning define semantically separate section
  731. ;; levels. A sectioning ADORNMENT consists in:
  732. ;;
  733. ;; - a CHARACTER
  734. ;;
  735. ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
  736. ;;
  737. ;; - an INDENT (meaningful for the over-and-under style only) which determines
  738. ;; how many characters and over-and-under style is hanging outside of the
  739. ;; title at the beginning and ending.
  740. ;;
  741. ;; Here are two examples of adornments (| represents the window border, column
  742. ;; 0):
  743. ;;
  744. ;; |
  745. ;; 1. char: '-' e |Some Title
  746. ;; style: simple |----------
  747. ;; |
  748. ;; 2. char: '=' |==============
  749. ;; style: over-and-under | Some Title
  750. ;; indent: 2 |==============
  751. ;; |
  752. ;;
  753. ;; Some notes:
  754. ;;
  755. ;; - The underlining character that is used depends on context. The file is
  756. ;; scanned to find other sections and an appropriate character is selected.
  757. ;; If the function is invoked on a section that is complete, the character is
  758. ;; rotated among the existing section adornments.
  759. ;;
  760. ;; Note that when rotating the characters, if we come to the end of the
  761. ;; hierarchy of adornments, the variable rst-preferred-adornments is
  762. ;; consulted to propose a new underline adornment, and if continued, we cycle
  763. ;; the adornments all over again. Set this variable to nil if you want to
  764. ;; limit the underlining character propositions to the existing adornments in
  765. ;; the file.
  766. ;;
  767. ;; - An underline/overline that is not extended to the column at which it should
  768. ;; be hanging is dubbed INCOMPLETE. For example::
  769. ;;
  770. ;; |Some Title
  771. ;; |-------
  772. ;;
  773. ;; Examples of default invocation:
  774. ;;
  775. ;; |Some Title ---> |Some Title
  776. ;; | |----------
  777. ;;
  778. ;; |Some Title ---> |Some Title
  779. ;; |----- |----------
  780. ;;
  781. ;; | |------------
  782. ;; | Some Title ---> | Some Title
  783. ;; | |------------
  784. ;;
  785. ;; In over-and-under style, when alternating the style, a variable is
  786. ;; available to select how much default indent to use (it can be zero). Note
  787. ;; that if the current section adornment already has an indent, we don't
  788. ;; adjust it to the default, we rather use the current indent that is already
  789. ;; there for adjustment (unless we cycle, in which case we use the indent
  790. ;; that has been found previously).
  791. (defgroup rst-adjust nil
  792. "Settings for adjustment and cycling of section title adornments."
  793. :group 'rst
  794. :version "21.1")
  795. (define-obsolete-variable-alias
  796. 'rst-preferred-decorations 'rst-preferred-adornments "1.0.0")
  797. (defcustom rst-preferred-adornments '((?= over-and-under 1)
  798. (?= simple 0)
  799. (?- simple 0)
  800. (?~ simple 0)
  801. (?+ simple 0)
  802. (?` simple 0)
  803. (?# simple 0)
  804. (?@ simple 0))
  805. "Preferred hierarchy of section title adornments.
  806. A list consisting of lists of the form (CHARACTER STYLE INDENT).
  807. CHARACTER is the character used. STYLE is one of the symbols
  808. OVER-AND-UNDER or SIMPLE. INDENT is an integer giving the wanted
  809. indentation for STYLE OVER-AND-UNDER. CHARACTER and STYLE are
  810. always used when a section adornment is described. In other
  811. places t instead of a list stands for a transition.
  812. This sequence is consulted to offer a new adornment suggestion
  813. when we rotate the underlines at the end of the existing
  814. hierarchy of characters, or when there is no existing section
  815. title in the file.
  816. Set this to an empty list to use only the adornment found in the
  817. file."
  818. :group 'rst-adjust
  819. :type `(repeat
  820. (group :tag "Adornment specification"
  821. (choice :tag "Adornment character"
  822. ,@(mapcar (lambda (char)
  823. (list 'const
  824. :tag (char-to-string char) char))
  825. rst-adornment-chars))
  826. (radio :tag "Adornment type"
  827. (const :tag "Overline and underline" over-and-under)
  828. (const :tag "Underline only" simple))
  829. (integer :tag "Indentation for overline and underline type"
  830. :value 0))))
  831. (defcustom rst-default-indent 1
  832. "Number of characters to indent the section title.
  833. This is used for when toggling adornment styles, when switching
  834. from a simple adornment style to a over-and-under adornment
  835. style."
  836. :group 'rst-adjust
  837. :type '(integer))
  838. (defun rst-compare-adornments (ado1 ado2)
  839. "Compare adornments.
  840. Return true if both ADO1 and ADO2 adornments are equal,
  841. according to restructured text semantics (only the character and
  842. the style are compared, the indentation does not matter)."
  843. (and (eq (car ado1) (car ado2))
  844. (eq (cadr ado1) (cadr ado2))))
  845. (defun rst-get-adornment-match (hier ado)
  846. "Return the index (level) in hierarchy HIER of adornment ADO.
  847. This basically just searches for the item using the appropriate
  848. comparison and returns the index. Return nil if the item is
  849. not found."
  850. (let ((cur hier))
  851. (while (and cur (not (rst-compare-adornments (car cur) ado)))
  852. (setq cur (cdr cur)))
  853. cur))
  854. (defun rst-suggest-new-adornment (allados &optional prev)
  855. "Suggest a new, different adornment from all that have been seen.
  856. ALLADOS is the set of all adornments, including the line numbers.
  857. PREV is the optional previous adornment, in order to suggest a
  858. better match."
  859. ;; For all the preferred adornments...
  860. (let* (
  861. ;; If 'prev' is given, reorder the list to start searching after the
  862. ;; match.
  863. (fplist
  864. (cdr (rst-get-adornment-match rst-preferred-adornments prev)))
  865. ;; List of candidates to search.
  866. (curpotential (append fplist rst-preferred-adornments)))
  867. (while
  868. ;; For all the adornments...
  869. (let ((cur allados)
  870. found)
  871. (while (and cur (not found))
  872. (if (rst-compare-adornments (car cur) (car curpotential))
  873. ;; Found it!
  874. (setq found (car curpotential))
  875. (setq cur (cdr cur))))
  876. found)
  877. (setq curpotential (cdr curpotential)))
  878. (copy-sequence (car curpotential))))
  879. (defun rst-delete-entire-line ()
  880. "Delete the entire current line without using the `kill-ring'."
  881. (delete-region (line-beginning-position)
  882. (line-beginning-position 2)))
  883. (defun rst-update-section (char style &optional indent)
  884. "Unconditionally update the style of a section adornment.
  885. Do this using the given character CHAR, with STYLE 'simple
  886. or 'over-and-under, and with indent INDENT. If the STYLE
  887. is 'simple, whitespace before the title is removed (indent
  888. is always assumed to be 0).
  889. If there are existing overline and/or underline from the
  890. existing adornment, they are removed before adding the
  891. requested adornment."
  892. (end-of-line)
  893. (let ((marker (point-marker))
  894. len)
  895. ;; Fixup whitespace at the beginning and end of the line.
  896. (if (or (null indent) (eq style 'simple))
  897. (setq indent 0))
  898. (beginning-of-line)
  899. (delete-horizontal-space)
  900. (insert (make-string indent ? ))
  901. (end-of-line)
  902. (delete-horizontal-space)
  903. ;; Set the current column, we're at the end of the title line.
  904. (setq len (+ (current-column) indent))
  905. ;; Remove previous line if it is an adornment.
  906. (save-excursion
  907. (forward-line -1)
  908. (if (and (looking-at (rst-re 'ado-beg-2-1))
  909. ;; Avoid removing the underline of a title right above us.
  910. (save-excursion (forward-line -1)
  911. (not (looking-at (rst-re 'ttl-beg)))))
  912. (rst-delete-entire-line)))
  913. ;; Remove following line if it is an adornment.
  914. (save-excursion
  915. (forward-line +1)
  916. (if (looking-at (rst-re 'ado-beg-2-1))
  917. (rst-delete-entire-line))
  918. ;; Add a newline if we're at the end of the buffer, for the subsequence
  919. ;; inserting of the underline.
  920. (if (= (point) (buffer-end 1))
  921. (newline 1)))
  922. ;; Insert overline.
  923. (if (eq style 'over-and-under)
  924. (save-excursion
  925. (beginning-of-line)
  926. (open-line 1)
  927. (insert (make-string len char))))
  928. ;; Insert underline.
  929. (forward-line +1)
  930. (open-line 1)
  931. (insert (make-string len char))
  932. (forward-line +1)
  933. (goto-char marker)
  934. ))
  935. (defun rst-classify-adornment (adornment end)
  936. "Classify adornment for section titles and transitions.
  937. ADORNMENT is the complete adornment string as found in the buffer
  938. with optional trailing whitespace. END is the point after the
  939. last character of ADORNMENT.
  940. Return a list. The first entry is t for a transition or a
  941. cons (CHARACTER . STYLE). Check `rst-preferred-adornments' for
  942. the meaning of CHARACTER and STYLE.
  943. The remaining list forms four match groups as returned by
  944. `match-data'. Match group 0 matches the whole construct. Match
  945. group 1 matches the overline adornment if present. Match group 2
  946. matches the section title text or the transition. Match group 3
  947. matches the underline adornment.
  948. Return nil if no syntactically valid adornment is found."
  949. (save-excursion
  950. (save-match-data
  951. (when (string-match (rst-re 'ado-beg-2-1) adornment)
  952. (goto-char end)
  953. (let* ((ado-ch (string-to-char (match-string 2 adornment)))
  954. (ado-re (rst-re ado-ch 'adorep3-hlp))
  955. (end-pnt (point))
  956. (beg-pnt (progn
  957. (forward-line 0)
  958. (point)))
  959. (nxt-emp ; Next line nonexistent or empty
  960. (save-excursion
  961. (or (not (zerop (forward-line 1)))
  962. (looking-at (rst-re 'lin-end)))))
  963. (prv-emp ; Previous line nonexistent or empty
  964. (save-excursion
  965. (or (not (zerop (forward-line -1)))
  966. (looking-at (rst-re 'lin-end)))))
  967. (ttl-blw ; Title found below starting here.
  968. (save-excursion
  969. (and
  970. (zerop (forward-line 1))
  971. (looking-at (rst-re 'ttl-beg))
  972. (point))))
  973. (ttl-abv ; Title found above starting here.
  974. (save-excursion
  975. (and
  976. (zerop (forward-line -1))
  977. (looking-at (rst-re 'ttl-beg))
  978. (point))))
  979. (und-fnd ; Matching underline found starting here.
  980. (save-excursion
  981. (and ttl-blw
  982. (zerop (forward-line 2))
  983. (looking-at (rst-re ado-re 'lin-end))
  984. (point))))
  985. (ovr-fnd ; Matching overline found starting here.
  986. (save-excursion
  987. (and ttl-abv
  988. (zerop (forward-line -2))
  989. (looking-at (rst-re ado-re 'lin-end))
  990. (point))))
  991. key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
  992. (cond
  993. ((and nxt-emp prv-emp)
  994. ;; A transition.
  995. (setq key t
  996. beg-txt beg-pnt
  997. end-txt end-pnt))
  998. ((or und-fnd ovr-fnd)
  999. ;; An overline with an underline.
  1000. (setq key (cons ado-ch 'over-and-under))
  1001. (let (;; Prefer overline match over underline match.
  1002. (und-pnt (if ovr-fnd beg-pnt und-fnd))
  1003. (ovr-pnt (if ovr-fnd ovr-fnd beg-pnt))
  1004. (txt-pnt (if ovr-fnd ttl-abv ttl-blw)))
  1005. (goto-char ovr-pnt)
  1006. (setq beg-ovr (point)
  1007. end-ovr (line-end-position))
  1008. (goto-char txt-pnt)
  1009. (setq beg-txt (point)
  1010. end-txt (line-end-position))
  1011. (goto-char und-pnt)
  1012. (setq beg-und (point)
  1013. end-und (line-end-position))))
  1014. (ttl-abv
  1015. ;; An underline.
  1016. (setq key (cons ado-ch 'simple)
  1017. beg-und beg-pnt
  1018. end-und end-pnt)
  1019. (goto-char ttl-abv)
  1020. (setq beg-txt (point)
  1021. end-txt (line-end-position)))
  1022. (t
  1023. ;; Invalid adornment.
  1024. (setq key nil)))
  1025. (if key
  1026. (list key
  1027. (or beg-ovr beg-txt beg-und)
  1028. (or end-und end-txt end-ovr)
  1029. beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))))
  1030. (defun rst-find-title-line ()
  1031. "Find a section title line around point and return its characteristics.
  1032. If the point is on an adornment line find the respective title
  1033. line. If the point is on an empty line check previous or next
  1034. line whether it is a suitable title line and use it if so. If
  1035. point is on a suitable title line use it.
  1036. If no title line is found return nil.
  1037. Otherwise return as `rst-classify-adornment' does. However, if
  1038. the title line has no syntactically valid adornment STYLE is nil
  1039. in the first element. If there is no adornment around the title
  1040. CHARACTER is also nil and match groups for overline and underline
  1041. are nil."
  1042. (save-excursion
  1043. (forward-line 0)
  1044. (let ((orig-pnt (point))
  1045. (orig-end (line-end-position)))
  1046. (cond
  1047. ((looking-at (rst-re 'ado-beg-2-1))
  1048. (let ((char (string-to-char (match-string-no-properties 2)))
  1049. (r (rst-classify-adornment (match-string-no-properties 0)
  1050. (match-end 0))))
  1051. (cond
  1052. ((not r)
  1053. ;; Invalid adornment - check whether this is an incomplete overline.
  1054. (if (and
  1055. (zerop (forward-line 1))
  1056. (looking-at (rst-re 'ttl-beg)))
  1057. (list (cons char nil) orig-pnt (line-end-position)
  1058. orig-pnt orig-end (point) (line-end-position) nil nil)))
  1059. ((consp (car r))
  1060. ;; A section title - not a transition.
  1061. r))))
  1062. ((looking-at (rst-re 'lin-end))
  1063. (or
  1064. (save-excursion
  1065. (if (and (zerop (forward-line -1))
  1066. (looking-at (rst-re 'ttl-beg)))
  1067. (list (cons nil nil) (point) (line-end-position)
  1068. nil nil (point) (line-end-position) nil nil)))
  1069. (save-excursion
  1070. (if (and (zerop (forward-line 1))
  1071. (looking-at (rst-re 'ttl-beg)))
  1072. (list (cons nil nil) (point) (line-end-position)
  1073. nil nil (point) (line-end-position) nil nil)))))
  1074. ((looking-at (rst-re 'ttl-beg))
  1075. ;; Try to use the underline.
  1076. (let ((r (rst-classify-adornment
  1077. (buffer-substring-no-properties
  1078. (line-beginning-position 2) (line-end-position 2))
  1079. (line-end-position 2))))
  1080. (if r
  1081. r
  1082. ;; No valid adornment found.
  1083. (list (cons nil nil) (point) (line-end-position)
  1084. nil nil (point) (line-end-position) nil nil))))))))
  1085. ;; The following function and variables are used to maintain information about
  1086. ;; current section adornment in a buffer local cache. Thus they can be used for
  1087. ;; font-locking and manipulation commands.
  1088. (defvar rst-all-sections nil
  1089. "All section adornments in the buffer as found by `rst-find-all-adornments'.
  1090. t when no section adornments were found.")
  1091. (make-variable-buffer-local 'rst-all-sections)
  1092. ;; FIXME: If this variable is set to a different value font-locking of section
  1093. ;; headers is wrong.
  1094. (defvar rst-section-hierarchy nil
  1095. "Section hierarchy in the buffer as determined by `rst-get-hierarchy'.
  1096. t when no section adornments were found. Value depends on
  1097. `rst-all-sections'.")
  1098. (make-variable-buffer-local 'rst-section-hierarchy)
  1099. (defun rst-reset-section-caches ()
  1100. "Reset all section cache variables.
  1101. Should be called by interactive functions which deal with sections."
  1102. (setq rst-all-sections nil
  1103. rst-section-hierarchy nil))
  1104. (defun rst-find-all-adornments ()
  1105. "Return all the section adornments in the current buffer.
  1106. Return a list of (LINE . ADORNMENT) with ascending LINE where
  1107. LINE is the line containing the section title. ADORNMENT consists
  1108. of a (CHARACTER STYLE INDENT) triple as described for
  1109. `rst-preferred-adornments'.
  1110. Uses and sets `rst-all-sections'."
  1111. (unless rst-all-sections
  1112. (let (positions)
  1113. ;; Iterate over all the section titles/adornments in the file.
  1114. (save-excursion
  1115. (goto-char (point-min))
  1116. (while (re-search-forward (rst-re 'ado-beg-2-1) nil t)
  1117. (let ((ado-data (rst-classify-adornment
  1118. (match-string-no-properties 0) (point))))
  1119. (when (and ado-data
  1120. (consp (car ado-data))) ; Ignore transitions.
  1121. (set-match-data (cdr ado-data))
  1122. (goto-char (match-beginning 2)) ; Goto the title start.
  1123. (push (cons (1+ (count-lines (point-min) (point)))
  1124. (list (caar ado-data)
  1125. (cdar ado-data)
  1126. (current-indentation)))
  1127. positions)
  1128. (goto-char (match-end 0))))) ; Go beyond the whole thing.
  1129. (setq positions (nreverse positions))
  1130. (setq rst-all-sections (or positions t)))))
  1131. (if (eq rst-all-sections t)
  1132. nil
  1133. rst-all-sections))
  1134. (defun rst-infer-hierarchy (adornments)
  1135. "Build a hierarchy of adornments using the list of given ADORNMENTS.
  1136. ADORNMENTS is a list of (CHARACTER STYLE INDENT) adornment
  1137. specifications, in order that they appear in a file, and will
  1138. infer a hierarchy of section levels by removing adornments that
  1139. have already been seen in a forward traversal of the adornments,
  1140. comparing just CHARACTER and STYLE.
  1141. Similarly returns a list of (CHARACTER STYLE INDENT), where each
  1142. list element should be unique."
  1143. (let (hierarchy-alist)
  1144. (dolist (x adornments)
  1145. (let ((char (car x))
  1146. (style (cadr x)))
  1147. (unless (assoc (cons char style) hierarchy-alist)
  1148. (push (cons (cons char style) x) hierarchy-alist))))
  1149. (mapcar 'cdr (nreverse hierarchy-alist))))
  1150. (defun rst-get-hierarchy (&optional ignore)
  1151. "Return the hierarchy of section titles in the file.
  1152. Return a list of adornments that represents the hierarchy of
  1153. section titles in the file. Each element consists of (CHARACTER
  1154. STYLE INDENT) as described for `rst-find-all-adornments'. If the
  1155. line number in IGNORE is specified, a possibly adornment found on
  1156. that line is not taken into account when building the hierarchy.
  1157. Uses and sets `rst-section-hierarchy' unless IGNORE is given."
  1158. (if (and (not ignore) rst-section-hierarchy)
  1159. (if (eq rst-section-hierarchy t)
  1160. nil
  1161. rst-section-hierarchy)
  1162. (let ((r (rst-infer-hierarchy
  1163. (mapcar 'cdr
  1164. (assq-delete-all
  1165. ignore
  1166. (rst-find-all-adornments))))))
  1167. (setq rst-section-hierarchy
  1168. (if ignore
  1169. ;; Clear cache reflecting that a possible update is not
  1170. ;; reflected.
  1171. nil
  1172. (or r t)))
  1173. r)))
  1174. (defun rst-get-adornments-around ()
  1175. "Return the adornments around point.
  1176. Return a list of the previous and next adornments."
  1177. (let* ((all (rst-find-all-adornments))
  1178. (curline (line-number-at-pos))
  1179. prev next
  1180. (cur all))
  1181. ;; Search for the adornments around the current line.
  1182. (while (and cur (< (caar cur) curline))
  1183. (setq prev cur
  1184. cur (cdr cur)))
  1185. ;; 'cur' is the following adornment.
  1186. (if (and cur (caar cur))
  1187. (setq next (if (= curline (caar cur)) (cdr cur) cur)))
  1188. (mapcar 'cdar (list prev next))
  1189. ))
  1190. (defun rst-adornment-complete-p (ado)
  1191. "Return true if the adornment ADO around point is complete."
  1192. ;; Note: we assume that the detection of the overline as being the underline
  1193. ;; of a preceding title has already been detected, and has been eliminated
  1194. ;; from the adornment that is given to us.
  1195. ;; There is some sectioning already present, so check if the current
  1196. ;; sectioning is complete and correct.
  1197. (let* ((char (car ado))
  1198. (style (cadr ado))
  1199. (indent (caddr ado))
  1200. (endcol (save-excursion (end-of-line) (current-column)))
  1201. )
  1202. (if char
  1203. (let ((exps (rst-re "^" char (format "\\{%d\\}" (+ endcol indent)) "$")))
  1204. (and
  1205. (save-excursion (forward-line +1)
  1206. (beginning-of-line)
  1207. (looking-at exps))
  1208. (or (not (eq style 'over-and-under))
  1209. (save-excursion (forward-line -1)
  1210. (beginning-of-line)
  1211. (looking-at exps))))
  1212. ))
  1213. ))
  1214. (defun rst-get-next-adornment
  1215. (curado hier &optional suggestion reverse-direction)
  1216. "Get the next adornment for CURADO, in given hierarchy HIER.
  1217. If suggesting, suggest for new adornment SUGGESTION.
  1218. REVERSE-DIRECTION is used to reverse the cycling order."
  1219. (let* (
  1220. (char (car curado))
  1221. (style (cadr curado))
  1222. ;; Build a new list of adornments for the rotation.
  1223. (rotados
  1224. (append hier
  1225. ;; Suggest a new adornment.
  1226. (list suggestion
  1227. ;; If nothing to suggest, use first adornment.
  1228. (car hier)))) )
  1229. (or
  1230. ;; Search for next adornment.
  1231. (cadr
  1232. (let ((cur (if reverse-direction rotados
  1233. (reverse rotados))))
  1234. (while (and cur
  1235. (not (and (eq char (caar cur))
  1236. (eq style (cadar cur)))))
  1237. (setq cur (cdr cur)))
  1238. cur))
  1239. ;; If not found, take the first of all adornments.
  1240. suggestion
  1241. )))
  1242. ;; FIXME: A line "``/`` full" is not accepted as a section title.
  1243. (defun rst-adjust (pfxarg)
  1244. "Auto-adjust the adornment around point.
  1245. Adjust/rotate the section adornment for the section title around
  1246. point or promote/demote the adornments inside the region,
  1247. depending on if the region is active. This function is meant to
  1248. be invoked possibly multiple times, and can vary its behavior
  1249. with a positive PFXARG (toggle style), or with a negative
  1250. PFXARG (alternate behavior).
  1251. This function is a bit of a swiss knife. It is meant to adjust
  1252. the adornments of a section title in reStructuredText. It tries
  1253. to deal with all the possible cases gracefully and to do `the
  1254. right thing' in all cases.
  1255. See the documentations of `rst-adjust-adornment-work' and
  1256. `rst-promote-region' for full details.
  1257. Prefix Arguments
  1258. ================
  1259. The method can take either (but not both) of
  1260. a. a (non-negative) prefix argument, which means to toggle the
  1261. adornment style. Invoke with a prefix argument for example;
  1262. b. a negative numerical argument, which generally inverts the
  1263. direction of search in the file or hierarchy. Invoke with C--
  1264. prefix for example."
  1265. (interactive "P")
  1266. (let* (;; Save our original position on the current line.
  1267. (origpt (point-marker))
  1268. (reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
  1269. (toggle-style (and pfxarg (not reverse-direction))))
  1270. (if (rst-portable-mark-active-p)
  1271. ;; Adjust adornments within region.
  1272. (rst-promote-region (and pfxarg t))
  1273. ;; Adjust adornment around point.
  1274. (rst-adjust-adornment-work toggle-style reverse-direction))
  1275. ;; Run the hooks to run after adjusting.
  1276. (run-hooks 'rst-adjust-hook)
  1277. ;; Make sure to reset the cursor position properly after we're done.
  1278. (goto-char origpt)
  1279. ))
  1280. (defcustom rst-adjust-hook nil
  1281. "Hooks to be run after running `rst-adjust'."
  1282. :group 'rst-adjust
  1283. :type '(hook)
  1284. :package-version '(rst . "1.1.0"))
  1285. (defcustom rst-new-adornment-down nil
  1286. "Controls level of new adornment for section headers."
  1287. :group 'rst-adjust
  1288. :type '(choice
  1289. (const :tag "Same level as previous one" nil)
  1290. (const :tag "One level down relative to the previous one" t))
  1291. :package-version '(rst . "1.1.0"))
  1292. (defun rst-adjust-adornment (pfxarg)
  1293. "Call `rst-adjust-adornment-work' interactively.
  1294. Keep this for compatibility for older bindings (are there any?).
  1295. Argument PFXARG has the same meaning as for `rst-adjust'."
  1296. (interactive "P")
  1297. (let* ((reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
  1298. (toggle-style (and pfxarg (not reverse-direction))))
  1299. (rst-adjust-adornment-work toggle-style reverse-direction)))
  1300. (defun rst-adjust-adornment-work (toggle-style reverse-direction)
  1301. "Adjust/rotate the section adornment for the section title around point.
  1302. This function is meant to be invoked possibly multiple times, and
  1303. can vary its behavior with a true TOGGLE-STYLE argument, or with
  1304. a REVERSE-DIRECTION argument.
  1305. General Behavior
  1306. ================
  1307. The next action it takes depends on context around the point, and
  1308. it is meant to be invoked possibly more than once to rotate among
  1309. the various possibilities. Basically, this function deals with:
  1310. - adding a adornment if the title does not have one;
  1311. - adjusting the length of the underline characters to fit a
  1312. modified title;
  1313. - rotating the adornment in the set of already existing
  1314. sectioning adornments used in the file;
  1315. - switching between simple and over-and-under styles.
  1316. You should normally not have to read all the following, just
  1317. invoke the method and it will do the most obvious thing that you
  1318. would expect.
  1319. Adornment Definitions
  1320. =====================
  1321. The adornments consist in
  1322. 1. a CHARACTER
  1323. 2. a STYLE which can be either of 'simple' or 'over-and-under'.
  1324. 3. an INDENT (meaningful for the over-and-under style only)
  1325. which determines how many characters and over-and-under
  1326. style is hanging outside of the title at the beginning and
  1327. ending.
  1328. See source code for mode details.
  1329. Detailed Behavior Description
  1330. =============================
  1331. Here are the gory details of the algorithm (it seems quite
  1332. complicated, but really, it does the most obvious thing in all
  1333. the particular cases):
  1334. Before applying the adornment change, the cursor is placed on
  1335. the closest line that could contain a section title.
  1336. Case 1: No Adornment
  1337. --------------------
  1338. If the current line has no adornment around it,
  1339. - search backwards for the last previous adornment, and apply
  1340. the adornment one level lower to the current line. If there
  1341. is no defined level below this previous adornment, we suggest
  1342. the most appropriate of the `rst-preferred-adornments'.
  1343. If REVERSE-DIRECTION is true, we simply use the previous
  1344. adornment found directly.
  1345. - if there is no adornment found in the given direction, we use
  1346. the first of `rst-preferred-adornments'.
  1347. TOGGLE-STYLE forces a toggle of the prescribed adornment style.
  1348. Case 2: Incomplete Adornment
  1349. ----------------------------
  1350. If the current line does have an existing adornment, but the
  1351. adornment is incomplete, that is, the underline/overline does
  1352. not extend to exactly the end of the title line (it is either too
  1353. short or too long), we simply extend the length of the
  1354. underlines/overlines to fit exactly the section title.
  1355. If TOGGLE-STYLE we toggle the style of the adornment as well.
  1356. REVERSE-DIRECTION has no effect in this case.
  1357. Case 3: Complete Existing Adornment
  1358. -----------------------------------
  1359. If the adornment is complete (i.e. the underline (overline)
  1360. length is already adjusted to the end of the title line), we
  1361. search/parse the file to establish the hierarchy of all the
  1362. adornments (making sure not to include the adornment around
  1363. point), and we rotate the current title's adornment from within
  1364. that list (by default, going *down* the hierarchy that is present
  1365. in the file, i.e. to a lower section level). This is meant to be
  1366. used potentially multiple times, until the desired adornment is
  1367. found around the title.
  1368. If we hit the boundary of the hierarchy, exactly one choice from
  1369. the list of preferred adornments is suggested/chosen, the first
  1370. of those adornment that has not been seen in the file yet (and
  1371. not including the adornment around point), and the next
  1372. invocation rolls over to the other end of the hierarchy (i.e. it
  1373. cycles). This allows you to avoid having to set which character
  1374. to use.
  1375. If REVERSE-DIRECTION is true, the effect is to change the
  1376. direction of rotation in the hierarchy of adornments, thus
  1377. instead going *up* the hierarchy.
  1378. However, if TOGGLE-STYLE, we do not rotate the adornment, but
  1379. instead simply toggle the style of the current adornment (this
  1380. should be the most common way to toggle the style of an existing
  1381. complete adornment).
  1382. Point Location
  1383. ==============
  1384. The invocation of this function can be carried out anywhere
  1385. within the section title line, on an existing underline or
  1386. overline, as well as on an empty line following a section title.
  1387. This is meant to be as convenient as possible.
  1388. Indented Sections
  1389. =================
  1390. Indented section titles such as ::
  1391. My Title
  1392. --------
  1393. are invalid in reStructuredText and thus not recognized by the
  1394. parser. This code will thus not work in a way that would support
  1395. indented sections (it would be ambiguous anyway).
  1396. Joint Sections
  1397. ==============
  1398. Section titles that are right next to each other may not be
  1399. treated well. More work might be needed to support those, and
  1400. special conditions on the completeness of existing adornments
  1401. might be required to make it non-ambiguous.
  1402. For now we assume that the adornments are disjoint, that is,
  1403. there is at least a single line between the titles/adornment
  1404. lines."
  1405. (rst-reset-section-caches)
  1406. (let ((ttl-fnd (rst-find-title-line))
  1407. (orig-pnt (point)))
  1408. (when ttl-fnd
  1409. (set-match-data (cdr ttl-fnd))
  1410. (goto-char (match-beginning 2))
  1411. (let* ((moved (- (line-number-at-pos) (line-number-at-pos orig-pnt)))
  1412. (char (caar ttl-fnd))
  1413. (style (cdar ttl-fnd))
  1414. (indent (current-indentation))
  1415. (curado (list char style indent))
  1416. char-new style-new indent-new)
  1417. (cond
  1418. ;;-------------------------------------------------------------------
  1419. ;; Case 1: No valid adornment
  1420. ((not style)
  1421. (let ((prev (car (rst-get-adornments-around)))
  1422. cur
  1423. (hier (rst-get-hierarchy)))
  1424. ;; Advance one level down.
  1425. (setq cur
  1426. (if prev
  1427. (if (or (and rst-new-adornment-down reverse-direction)
  1428. (and (not rst-new-adornment-down)
  1429. (not reverse-direction)))
  1430. prev
  1431. (or (cadr (rst-get-adornment-match hier prev))
  1432. (rst-suggest-new-adornment hier prev)))
  1433. (copy-sequence (car rst-preferred-adornments))))
  1434. ;; Invert the style if requested.
  1435. (if toggle-style
  1436. (setcar (cdr cur) (if (eq (cadr cur) 'simple)
  1437. 'over-and-under 'simple)) )
  1438. (setq char-new (car cur)
  1439. style-new (cadr cur)
  1440. indent-new (caddr cur))))
  1441. ;;-------------------------------------------------------------------
  1442. ;; Case 2: Incomplete Adornment
  1443. ((not (rst-adornment-complete-p curado))
  1444. ;; Invert the style if requested.
  1445. (if toggle-style
  1446. (setq style (if (eq style 'simple) 'over-and-under 'simple)))
  1447. (setq char-new char
  1448. style-new style
  1449. indent-new indent))
  1450. ;;-------------------------------------------------------------------
  1451. ;; Case 3: Complete Existing Adornment
  1452. (t
  1453. (if toggle-style
  1454. ;; Simply switch the style of the current adornment.
  1455. (setq char-new char
  1456. style-new (if (eq style 'simple) 'over-and-under 'simple)
  1457. indent-new rst-default-indent)
  1458. ;; Else, we rotate, ignoring the adornment around the current
  1459. ;; line...
  1460. (let* ((hier (rst-get-hierarchy (line-number-at-pos)))
  1461. ;; Suggestion, in case we need to come up with something new.
  1462. (suggestion (rst-suggest-new-adornment
  1463. hier
  1464. (car (rst-get-adornments-around))))
  1465. (nextado (rst-get-next-adornment
  1466. curado hier suggestion reverse-direction)))
  1467. ;; Indent, if present, always overrides the prescribed indent.
  1468. (setq char-new (car nextado)
  1469. style-new (cadr nextado)
  1470. indent-new (caddr nextado))))))
  1471. ;; Override indent with present indent!
  1472. (setq indent-new (if (> indent 0) indent indent-new))
  1473. (if (and char-new style-new)
  1474. (rst-update-section char-new style-new indent-new))
  1475. ;; Correct the position of the cursor to more accurately reflect where
  1476. ;; it was located when the function was invoked.
  1477. (unless (zerop moved)
  1478. (forward-line (- moved))
  1479. (end-of-line))))))
  1480. ;; Maintain an alias for compatibility.
  1481. (defalias 'rst-adjust-section-title 'rst-adjust)
  1482. (defun rst-promote-region (demote)
  1483. "Promote the section titles within the region.
  1484. With argument DEMOTE or a prefix argument, demote the section
  1485. titles instead. The algorithm used at the boundaries of the
  1486. hierarchy is similar to that used by `rst-adjust-adornment-work'."
  1487. (interactive "P")
  1488. (rst-reset-section-caches)
  1489. (let* ((cur (rst-find-all-adornments))
  1490. (hier (rst-get-hierarchy))
  1491. (suggestion (rst-suggest-new-adornment hier))
  1492. (region-begin-line (line-number-at-pos (region-beginning)))
  1493. (region-end-line (line-number-at-pos (region-end)))
  1494. marker-list
  1495. )
  1496. ;; Skip the markers that come before the region beginning.
  1497. (while (and cur (< (caar cur) region-begin-line))
  1498. (setq cur (cdr cur)))
  1499. ;; Create a list of markers for all the adornments which are found within
  1500. ;; the region.
  1501. (save-excursion
  1502. (let (line)
  1503. (while (and cur (< (setq line (caar cur)) region-end-line))
  1504. (goto-char (point-min))
  1505. (forward-line (1- line))
  1506. (push (list (point-marker) (cdar cur)) marker-list)
  1507. (setq cur (cdr cur)) ))
  1508. ;; Apply modifications.
  1509. (dolist (p marker-list)
  1510. ;; Go to the adornment to promote.
  1511. (goto-char (car p))
  1512. ;; Update the adornment.
  1513. (apply 'rst-update-section
  1514. ;; Rotate the next adornment.
  1515. (rst-get-next-adornment
  1516. (cadr p) hier suggestion demote))
  1517. ;; Clear marker to avoid slowing down the editing after we're done.
  1518. (set-marker (car p) nil))
  1519. (setq deactivate-mark nil)
  1520. )))
  1521. (defun rst-display-adornments-hierarchy (&optional adornments)
  1522. "Display the current file's section title adornments hierarchy.
  1523. This function expects a list of (CHARACTER STYLE INDENT) triples
  1524. in ADORNMENTS."
  1525. (interactive)
  1526. (rst-reset-section-caches)
  1527. (if (not adornments)
  1528. (setq adornments (rst-get-hierarchy)))
  1529. (with-output-to-temp-buffer "*rest section hierarchy*"
  1530. (let ((level 1))
  1531. (with-current-buffer standard-output
  1532. (dolist (x adornments)
  1533. (insert (format "\nSection Level %d" level))
  1534. (apply 'rst-update-section x)
  1535. (goto-char (point-max))
  1536. (insert "\n")
  1537. (incf level)
  1538. ))
  1539. )))
  1540. (defun rst-straighten-adornments ()
  1541. "Redo all the adornments in the current buffer.
  1542. This is done using our preferred set of adornments. This can be
  1543. used, for example, when using somebody else's copy of a document,
  1544. in order to adapt it to our preferred style."
  1545. (interactive)
  1546. (rst-reset-section-caches)
  1547. (save-excursion
  1548. (let (;; Get a list of pairs of (level . marker).
  1549. (levels-and-markers (mapcar
  1550. (lambda (ado)
  1551. (cons (rst-position (cdr ado)
  1552. (rst-get-hierarchy))
  1553. (progn
  1554. (goto-char (point-min))
  1555. (forward-line (1- (car ado)))
  1556. (point-marker))))
  1557. (rst-find-all-adornments))))
  1558. (dolist (lm levels-and-markers)
  1559. ;; Go to the appropriate position.
  1560. (goto-char (cdr lm))
  1561. ;; Apply the new style.
  1562. (apply 'rst-update-section (nth (car lm) rst-preferred-adornments))
  1563. ;; Reset the market to avoid slowing down editing until it gets GC'ed.
  1564. (set-marker (cdr lm) nil)
  1565. )
  1566. )))
  1567. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1568. ;; Insert list items
  1569. ;; =================
  1570. ;=================================================
  1571. ; Borrowed from a2r.el (version 1.3), by Lawrence Mitchell <wence@gmx.li>.
  1572. ; I needed to make some tiny changes to the functions, so I put it here.
  1573. ; -- Wei-Wei Guo
  1574. (defconst rst-arabic-to-roman
  1575. '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
  1576. (100 . "C") (90 . "XC") (50 . "L") (40 . "XL")
  1577. (10 . "X") (9 . "IX") (5 . "V") (4 . "IV")
  1578. (1 . "I"))
  1579. "List of maps between Arabic numbers and their Roman numeral equivalents.")
  1580. (defun rst-arabic-to-roman (num &optional arg)
  1581. "Convert Arabic number NUM to its Roman numeral representation.
  1582. Obviously, NUM must be greater than zero. Don't blame me, blame the
  1583. Romans, I mean \"what have the Romans ever _done_ for /us/?\" (with
  1584. apologies to Monty Python).
  1585. If optional prefix ARG is non-nil, insert in current buffer."
  1586. (let ((map rst-arabic-to-roman)
  1587. res)
  1588. (while (and map (> num 0))
  1589. (if (or (= num (caar map))
  1590. (> num (caar map)))
  1591. (setq res (concat res (cdar map))
  1592. num (- num (caar map)))
  1593. (setq map (cdr map))))
  1594. res))
  1595. (defun rst-roman-to-arabic (string &optional arg)
  1596. "Convert STRING of Roman numerals to an Arabic number.
  1597. If STRING contains a letter which isn't a valid Roman numeral, the rest
  1598. of the string from that point onwards is ignored.
  1599. Hence:
  1600. MMD == 2500
  1601. and
  1602. MMDFLXXVI == 2500.
  1603. If optional ARG is non-nil, insert in current buffer."
  1604. (let ((res 0)
  1605. (map rst-arabic-to-roman))
  1606. (while map
  1607. (if (string-match (concat "^" (cdar map)) string)
  1608. (setq res (+ res (caar map))
  1609. string (replace-match "" nil t string))
  1610. (setq map (cdr map))))
  1611. res))
  1612. ;=================================================
  1613. (defun rst-find-pfx-in-region (beg end pfx-re)
  1614. "Find all the positions of prefixes in region between BEG and END.
  1615. This is used to find bullets and enumerated list items. PFX-RE is
  1616. a regular expression for matching the lines after indentation
  1617. with items. Returns a list of cons cells consisting of the point
  1618. and the column of the point."
  1619. (let ((pfx ()))
  1620. (save-excursion
  1621. (goto-char beg)
  1622. (while (< (point) end)
  1623. (back-to-indentation)
  1624. (when (and
  1625. (looking-at pfx-re) ; pfx found and...
  1626. (let ((pfx-col (current-column)))
  1627. (save-excursion
  1628. (forward-line -1) ; ...previous line is...
  1629. (back-to-indentation)
  1630. (or (looking-at (rst-re 'lin-end)) ; ...empty,
  1631. (> (current-column) pfx-col) ; ...deeper level, or
  1632. (and (= (current-column) pfx-col)
  1633. (looking-at pfx-re)))))) ; ...pfx at same level.
  1634. (push (cons (point) (current-column))
  1635. pfx))
  1636. (forward-line 1)) )
  1637. (nreverse pfx)))
  1638. (defun rst-insert-list-pos (newitem)
  1639. "Arrange relative position of a newly inserted list item of style NEWITEM.
  1640. Adding a new list might consider three situations:
  1641. (a) Current line is a blank line.
  1642. (b) Previous line is a blank line.
  1643. (c) Following line is a blank line.
  1644. When (a) and (b), just add the new list at current line.
  1645. when (a) and not (b), a blank line is added before adding the new list.
  1646. When not (a), first forward point to the end of the line, and add two
  1647. blank lines, then add the new list.
  1648. Other situations are just ignored and left to users themselves."
  1649. (if (save-excursion
  1650. (beginning-of-line)
  1651. (looking-at (rst-re 'lin-end)))
  1652. (if (save-excursion
  1653. (forward-line -1)
  1654. (looking-at (rst-re 'lin-end)))
  1655. (insert newitem " ")
  1656. (insert "\n" newitem " "))
  1657. (end-of-line)
  1658. (insert "\n\n" newitem " ")))
  1659. ;; FIXME: Isn't this a `defconst'?
  1660. (defvar rst-initial-enums
  1661. (let (vals)
  1662. (dolist (fmt '("%s." "(%s)" "%s)"))
  1663. (dolist (c '("1" "a" "A" "I" "i"))
  1664. (push (format fmt c) vals)))
  1665. (cons "#." (nreverse vals)))
  1666. "List of initial enumerations.")
  1667. ;; FIXME: Isn't this a `defconst'?
  1668. (defvar rst-initial-items
  1669. (append (mapcar 'char-to-string rst-bullets) rst-initial-enums)
  1670. "List of initial items. It's collection of bullets and enumerations.")
  1671. (defun rst-insert-list-new-item ()
  1672. "Insert a new list item.
  1673. User is asked to select the item style first, for example (a), i), +. Use TAB
  1674. for completion and choices.
  1675. If user selects bullets or #, it's just added with position arranged by
  1676. `rst-insert-list-pos'.
  1677. If user selects enumerations, a further prompt is given. User need to input a
  1678. starting item, for example 'e' for 'A)' style. The position is also arranged by
  1679. `rst-insert-list-pos'."
  1680. (interactive)
  1681. ;; FIXME: Make this comply to `interactive' standards.
  1682. (let* ((itemstyle (completing-read
  1683. "Select preferred item style [#.]: "
  1684. rst-initial-items nil t nil nil "#."))
  1685. (cnt (if (string-match (rst-re 'cntexp-tag) itemstyle)
  1686. (match-string 0 itemstyle)))
  1687. (no
  1688. (save-match-data
  1689. ;; FIXME: Make this comply to `interactive' standards.
  1690. (cond
  1691. ((equal cnt "a")
  1692. (let ((itemno (read-string "Give starting value [a]: "
  1693. nil nil "a")))
  1694. (downcase (substring itemno 0 1))))
  1695. ((equal cnt "A")
  1696. (let ((itemno (read-string "Give starting value [A]: "
  1697. nil nil "A")))
  1698. (upcase (substring itemno 0 1))))
  1699. ((equal cnt "I")
  1700. (let ((itemno (read-number "Give starting value [1]: " 1)))
  1701. (rst-arabic-to-roman itemno)))
  1702. ((equal cnt "i")
  1703. (let ((itemno (read-number "Give starting value [1]: " 1)))
  1704. (downcase (rst-arabic-to-roman itemno))))
  1705. ((equal cnt "1")
  1706. (let ((itemno (read-number "Give starting value [1]: " 1)))
  1707. (number-to-string itemno)))))))
  1708. (if no
  1709. (setq itemstyle (replace-match no t t itemstyle)))
  1710. (rst-insert-list-pos itemstyle)))
  1711. (defcustom rst-preferred-bullets
  1712. '(?* ?- ?+)
  1713. "List of favorite bullets."
  1714. :group 'rst
  1715. :type `(repeat
  1716. (choice ,@(mapcar (lambda (char)
  1717. (list 'const
  1718. :tag (char-to-string char) char))
  1719. rst-bullets)))
  1720. :package-version '(rst . "1.1.0"))
  1721. (defun rst-insert-list-continue (curitem prefer-roman)
  1722. "Insert a list item with list start CURITEM including its indentation level.
  1723. If PREFER-ROMAN roman numbering is preferred over using letters."
  1724. (end-of-line)
  1725. (insert
  1726. "\n" ; FIXME: Separating lines must be possible.
  1727. (cond
  1728. ((string-match (rst-re '(:alt enmaut-tag
  1729. bul-tag)) curitem)
  1730. curitem)
  1731. ((string-match (rst-re 'num-tag) curitem)
  1732. (replace-match (number-to-string
  1733. (1+ (string-to-number (match-string 0 curitem))))
  1734. nil nil curitem))
  1735. ((and (string-match (rst-re 'rom-tag) curitem)
  1736. (save-match-data
  1737. (if (string-match (rst-re 'ltr-tag) curitem) ; Also a letter tag.
  1738. (save-excursion
  1739. ;; FIXME: Assumes one line list items without separating
  1740. ;; empty lines.
  1741. (if (and (zerop (forward-line -1))
  1742. (looking-at (rst-re 'enmexp-beg)))
  1743. (string-match
  1744. (rst-re 'rom-tag)
  1745. (match-string 0)) ; Previous was a roman tag.
  1746. prefer-roman)) ; Don't know - use flag.
  1747. t))) ; Not a letter tag.
  1748. (replace-match
  1749. (let* ((old (match-string 0 curitem))
  1750. (new (save-match-data
  1751. (rst-arabic-to-roman
  1752. (1+ (rst-roman-to-arabic
  1753. (upcase old)))))))
  1754. (if (equal old (upcase old))
  1755. (upcase new)
  1756. (downcase new)))
  1757. t nil curitem))
  1758. ((string-match (rst-re 'ltr-tag) curitem)
  1759. (replace-match (char-to-string
  1760. (1+ (string-to-char (match-string 0 curitem))))
  1761. nil nil curitem)))))
  1762. (defun rst-insert-list (&optional prefer-roman)
  1763. "Insert a list item at the current point.
  1764. The command can insert a new list or a continuing list. When it is called at a
  1765. non-list line, it will promote to insert new list. When it is called at a list
  1766. line, it will insert a list with the same list style.
  1767. 1. When inserting a new list:
  1768. User is asked to select the item style first, for example (a), i), +. Use TAB
  1769. for completion and choices.
  1770. (a) If user selects bullets or #, it's just added.
  1771. (b) If user selects enumerations, a further prompt is given. User needs to
  1772. input a starting item, for example 'e' for 'A)' style.
  1773. The position of the new list is arranged according to whether or not the
  1774. current line and the previous line are blank lines.
  1775. 2. When continuing a list, one thing need to be noticed:
  1776. List style alphabetical list, such as 'a.', and roman numerical list, such as
  1777. 'i.', have some overlapping items, for example 'v.' The function can deal with
  1778. the problem elegantly in most situations. But when those overlapped list are
  1779. preceded by a blank line, it is hard to determine which type to use
  1780. automatically. The function uses alphabetical list by default. If you want
  1781. roman numerical list, just use a prefix to set PREFER-ROMAN."
  1782. (interactive "P")
  1783. (beginning-of-line)
  1784. (if (looking-at (rst-re 'itmany-beg-1))
  1785. (rst-insert-list-continue (match-string 0) prefer-roman)
  1786. (rst-insert-list-new-item)))
  1787. (defun rst-straighten-bullets-region (beg end)
  1788. "Make all the bulleted list items in the region consistent.
  1789. The region is specified between BEG and END. You can use this
  1790. after you have merged multiple bulleted lists to make them use
  1791. the same/correct/consistent bullet characters.
  1792. See variable `rst-preferred-bullets' for the list of bullets to
  1793. adjust. If bullets are found on levels beyond the
  1794. `rst-preferred-bullets' list, they are not modified."
  1795. (interactive "r")
  1796. (let ((bullets (rst-find-pfx-in-region beg end (rst-re 'bul-sta)))
  1797. (levtable (make-hash-table :size 4)))
  1798. ;; Create a map of levels to list of positions.
  1799. (dolist (x bullets)
  1800. (let ((key (cdr x)))
  1801. (puthash key
  1802. (append (gethash key levtable (list))
  1803. (list (car x)))
  1804. levtable)))
  1805. ;; Sort this map and create a new map of prefix char and list of positions.
  1806. (let ((poslist ())) ; List of (indent . positions).
  1807. (maphash (lambda (x y) (push (cons x y) poslist)) levtable)
  1808. (let ((bullets rst-preferred-bullets))
  1809. (dolist (x (sort poslist 'car-less-than-car))
  1810. (when bullets
  1811. ;; Apply the characters.
  1812. (dolist (pos (cdr x))
  1813. (goto-char pos)
  1814. (delete-char 1)
  1815. (insert (string (car bullets))))
  1816. (setq bullets (cdr bullets))))))))
  1817. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1818. ;; Table of contents
  1819. ;; =================
  1820. (defun rst-get-stripped-line ()
  1821. "Return the line at cursor, stripped from whitespace."
  1822. (re-search-forward (rst-re "\\S .*\\S ") (line-end-position))
  1823. (buffer-substring-no-properties (match-beginning 0)
  1824. (match-end 0)) )
  1825. (defun rst-section-tree ()
  1826. "Get the hierarchical tree of section titles.
  1827. Returns a hierarchical tree of the sections titles in the
  1828. document. This can be used to generate a table of contents for
  1829. the document. The top node will always be a nil node, with the
  1830. top level titles as children (there may potentially be more than
  1831. one).
  1832. Each section title consists in a cons of the stripped title
  1833. string and a marker to the section in the original text document.
  1834. If there are missing section levels, the section titles are
  1835. inserted automatically, and the title string is set to nil, and
  1836. the marker set to the first non-nil child of itself.
  1837. Conceptually, the nil nodes--i.e.\ those which have no title--are
  1838. to be considered as being the same line as their first non-nil
  1839. child. This has advantages later in processing the graph."
  1840. (let ((hier (rst-get-hierarchy))
  1841. (levels (make-hash-table :test 'equal :size 10))
  1842. lines)
  1843. (let ((lev 0))
  1844. (dolist (ado hier)
  1845. ;; Compare just the character and indent in the hash table.
  1846. (puthash (cons (car ado) (cadr ado)) lev levels)
  1847. (incf lev)))
  1848. ;; Create a list of lines that contains (text, level, marker) for each
  1849. ;; adornment.
  1850. (save-excursion
  1851. (setq lines
  1852. (mapcar (lambda (ado)
  1853. (goto-char (point-min))
  1854. (forward-line (1- (car ado)))
  1855. (list (gethash (cons (cadr ado) (caddr ado)) levels)
  1856. (rst-get-stripped-line)
  1857. (progn
  1858. (beginning-of-line 1)
  1859. (point-marker))))
  1860. (rst-find-all-adornments))))
  1861. (let ((lcontnr (cons nil lines)))
  1862. (rst-section-tree-rec lcontnr -1))))
  1863. (defun rst-section-tree-rec (ados lev)
  1864. "Recursive guts of the section tree construction.
  1865. ADOS is a cons cell whose cdr is the remaining list of
  1866. adornments, and we change it as we consume them. LEV is
  1867. the current level of that node. This function returns a
  1868. pair of the subtree that was built. This treats the ADOS
  1869. list destructively."
  1870. (let ((nado (cadr ados))
  1871. node
  1872. children)
  1873. ;; If the next adornment matches our level.
  1874. (when (and nado (= (car nado) lev))
  1875. ;; Pop the next adornment and create the current node with it.
  1876. (setcdr ados (cddr ados))
  1877. (setq node (cdr nado)) )
  1878. ;; Else we let the node title/marker be unset.
  1879. ;; Build the child nodes.
  1880. (while (and (cdr ados) (> (caadr ados) lev))
  1881. (setq children
  1882. (cons (rst-section-tree-rec ados (1+ lev))
  1883. children)))
  1884. (setq children (reverse children))
  1885. ;; If node is still unset, we use the marker of the first child.
  1886. (when (eq node nil)
  1887. (setq node (cons nil (cdaar children))))
  1888. ;; Return this node with its children.
  1889. (cons node children)
  1890. ))
  1891. (defun rst-section-tree-point (node &optional point)
  1892. "Find tree node at point.
  1893. Given a computed and valid section tree in NODE and a point
  1894. POINT (default being the current point in the current buffer),
  1895. find and return the node within the section tree where the cursor
  1896. lives.
  1897. Return values: a pair of (parent path, container subtree).
  1898. The parent path is simply a list of the nodes above the
  1899. container subtree node that we're returning."
  1900. (let (path outtree)
  1901. (let* ((curpoint (or point (point))))
  1902. ;; Check if we are before the current node.
  1903. (if (and (cadar node) (>= curpoint (cadar node)))
  1904. ;; Iterate all the children, looking for one that might contain the
  1905. ;; current section.
  1906. (let ((curnode (cdr node))
  1907. last)
  1908. (while (and curnode (>= curpoint (cadaar curnode)))
  1909. (setq last curnode
  1910. curnode (cdr curnode)))
  1911. (if last
  1912. (let ((sub (rst-section-tree-point (car last) curpoint)))
  1913. (setq path (car sub)
  1914. outtree (cdr sub)))
  1915. (setq outtree node))
  1916. )))
  1917. (cons (cons (car node) path) outtree)
  1918. ))
  1919. (defgroup rst-toc nil
  1920. "Settings for reStructuredText table of contents."
  1921. :group 'rst
  1922. :version "21.1")
  1923. (defcustom rst-toc-indent 2
  1924. "Indentation for table-of-contents display.
  1925. Also used for formatting insertion, when numbering is disabled."
  1926. :group 'rst-toc)
  1927. (defcustom rst-toc-insert-style 'fixed
  1928. "Insertion style for table-of-contents.
  1929. Set this to one of the following values to determine numbering and
  1930. indentation style:
  1931. - plain: no numbering (fixed indentation)
  1932. - fixed: numbering, but fixed indentation
  1933. - aligned: numbering, titles aligned under each other
  1934. - listed: numbering, with dashes like list items (EXPERIMENTAL)"
  1935. :group 'rst-toc)
  1936. (defcustom rst-toc-insert-number-separator " "
  1937. "Separator that goes between the TOC number and the title."
  1938. :group 'rst-toc)
  1939. ;; This is used to avoid having to change the user's mode.
  1940. (defvar rst-toc-insert-click-keymap
  1941. (let ((map (make-sparse-keymap)))
  1942. (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
  1943. map)
  1944. "(Internal) What happens when you click on propertized text in the TOC.")
  1945. (defcustom rst-toc-insert-max-level nil
  1946. "If non-nil, maximum depth of the inserted TOC."
  1947. :group 'rst-toc)
  1948. (defun rst-toc-insert (&optional pfxarg)
  1949. "Insert a simple text rendering of the table of contents.
  1950. By default the top level is ignored if there is only one, because
  1951. we assume that the document will have a single title.
  1952. If a numeric prefix argument PFXARG is given, insert the TOC up
  1953. to the specified level.
  1954. The TOC is inserted indented at the current column."
  1955. (interactive "P")
  1956. (rst-reset-section-caches)
  1957. (let* (;; Check maximum level override.
  1958. (rst-toc-insert-max-level
  1959. (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
  1960. (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
  1961. ;; Get the section tree for the current cursor point.
  1962. (sectree-pair
  1963. (rst-section-tree-point
  1964. (rst-section-tree)))
  1965. ;; Figure out initial indent.
  1966. (initial-indent (make-string (current-column) ? ))
  1967. (init-point (point)))
  1968. (when (cddr sectree-pair)
  1969. (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
  1970. ;; Fixup for the first line.
  1971. (delete-region init-point (+ init-point (length initial-indent)))
  1972. ;; Delete the last newline added.
  1973. (delete-char -1)
  1974. )))
  1975. (defun rst-toc-insert-node (node level indent pfx)
  1976. "Insert tree node NODE in table-of-contents.
  1977. Recursive function that does printing of the inserted toc.
  1978. LEVEL is the depth level of the sections in the tree.
  1979. INDENT is the indentation string. PFX is the prefix numbering,
  1980. that includes the alignment necessary for all the children of
  1981. level to align."
  1982. ;; Note: we do child numbering from the parent, so we start number the
  1983. ;; children one level before we print them.
  1984. (let ((do-print (> level 0))
  1985. (count 1))
  1986. (when do-print
  1987. (insert indent)
  1988. (let ((b (point)))
  1989. (unless (equal rst-toc-insert-style 'plain)
  1990. (insert pfx rst-toc-insert-number-separator))
  1991. (insert (or (caar node) "[missing node]"))
  1992. ;; Add properties to the text, even though in normal text mode it
  1993. ;; won't be doing anything for now. Not sure that I want to change
  1994. ;; mode stuff. At least the highlighting gives the idea that this
  1995. ;; is generated automatically.
  1996. (put-text-property b (point) 'mouse-face 'highlight)
  1997. (put-text-property b (point) 'rst-toc-target (cadar node))
  1998. (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
  1999. )
  2000. (insert "\n")
  2001. ;; Prepare indent for children.
  2002. (setq indent
  2003. (cond
  2004. ((eq rst-toc-insert-style 'plain)
  2005. (concat indent (make-string rst-toc-indent ? )))
  2006. ((eq rst-toc-insert-style 'fixed)
  2007. (concat indent (make-string rst-toc-indent ? )))
  2008. ((eq rst-toc-insert-style 'aligned)
  2009. (concat indent (make-string (+ (length pfx) 2) ? )))
  2010. ((eq rst-toc-insert-style 'listed)
  2011. (concat (substring indent 0 -3)
  2012. (concat (make-string (+ (length pfx) 2) ? ) " - ")))
  2013. ))
  2014. )
  2015. (if (or (eq rst-toc-insert-max-level nil)
  2016. (< level rst-toc-insert-max-level))
  2017. (let ((do-child-numbering (>= level 0))
  2018. fmt)
  2019. (if do-child-numbering
  2020. (progn
  2021. ;; Add a separating dot if there is already a prefix.
  2022. (when (> (length pfx) 0)
  2023. (string-match (rst-re "[ \t\n]*\\'") pfx)
  2024. (setq pfx (concat (replace-match "" t t pfx) ".")))
  2025. ;; Calculate the amount of space that the prefix will require
  2026. ;; for the numbers.
  2027. (if (cdr node)
  2028. (setq fmt (format "%%-%dd"
  2029. (1+ (floor (log10 (length
  2030. (cdr node))))))))
  2031. ))
  2032. (dolist (child (cdr node))
  2033. (rst-toc-insert-node child
  2034. (1+ level)
  2035. indent
  2036. (if do-child-numbering
  2037. (concat pfx (format fmt count)) pfx))
  2038. (incf count)))
  2039. )))
  2040. (defun rst-toc-update ()
  2041. "Automatically find the contents section of a document and update.
  2042. Updates the inserted TOC if present. You can use this in your
  2043. file-write hook to always make it up-to-date automatically."
  2044. (interactive)
  2045. (save-excursion
  2046. ;; Find and delete an existing comment after the first contents directive.
  2047. ;; Delete that region.
  2048. (goto-char (point-min))
  2049. ;; We look for the following and the following only (in other words, if your
  2050. ;; syntax differs, this won't work.).
  2051. ;;
  2052. ;; .. contents:: [...anything here...]
  2053. ;; [:field: value]...
  2054. ;; ..
  2055. ;; XXXXXXXX
  2056. ;; XXXXXXXX
  2057. ;; [more lines]
  2058. (let ((beg (re-search-forward
  2059. (rst-re "^" 'exm-sta "contents" 'dcl-tag ".*\n"
  2060. "\\(?:" 'hws-sta 'fld-tag ".*\n\\)*" 'exm-tag) nil t))
  2061. last-real)
  2062. (when beg
  2063. ;; Look for the first line that starts at the first column.
  2064. (forward-line 1)
  2065. (while (and
  2066. (< (point) (point-max))
  2067. (or (if (looking-at
  2068. (rst-re 'hws-sta "\\S ")) ; indented content.
  2069. (setq last-real (point)))
  2070. (looking-at (rst-re 'lin-end)))) ; empty line.
  2071. (forward-line 1))
  2072. (if last-real
  2073. (progn
  2074. (goto-char last-real)
  2075. (end-of-line)
  2076. (delete-region beg (point)))
  2077. (goto-char beg))
  2078. (insert "\n ")
  2079. (rst-toc-insert))))
  2080. ;; Note: always return nil, because this may be used as a hook.
  2081. nil)
  2082. ;; Note: we cannot bind the TOC update on file write because it messes with
  2083. ;; undo. If we disable undo, since it adds and removes characters, the
  2084. ;; positions in the undo list are not making sense anymore. Dunno what to do
  2085. ;; with this, it would be nice to update when saving.
  2086. ;;
  2087. ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
  2088. ;; (defun rst-toc-update-fun ()
  2089. ;; ;; Disable undo for the write file hook.
  2090. ;; (let ((buffer-undo-list t)) (rst-toc-update) ))
  2091. (defalias 'rst-toc-insert-update 'rst-toc-update) ; backwards compat.
  2092. ;;------------------------------------------------------------------------------
  2093. (defun rst-toc-node (node level)
  2094. "Recursive function that does insert NODE at LEVEL in the table-of-contents."
  2095. (if (> level 0)
  2096. (let ((b (point)))
  2097. ;; Insert line text.
  2098. (insert (make-string (* rst-toc-indent (1- level)) ? ))
  2099. (insert (or (caar node) "[missing node]"))
  2100. ;; Highlight lines.
  2101. (put-text-property b (point) 'mouse-face 'highlight)
  2102. ;; Add link on lines.
  2103. (put-text-property b (point) 'rst-toc-target (cadar node))
  2104. (insert "\n")
  2105. ))
  2106. (dolist (child (cdr node))
  2107. (rst-toc-node child (1+ level))))
  2108. (defun rst-toc-count-lines (node target-node)
  2109. "Count the number of lines from NODE to the TARGET-NODE node.
  2110. This recursive function returns a cons of the number of
  2111. additional lines that have been counted for its node and
  2112. children, and t if the node has been found."
  2113. (let ((count 1)
  2114. found)
  2115. (if (eq node target-node)
  2116. (setq found t)
  2117. (let ((child (cdr node)))
  2118. (while (and child (not found))
  2119. (let ((cl (rst-toc-count-lines (car child) target-node)))
  2120. (setq count (+ count (car cl))
  2121. found (cdr cl)
  2122. child (cdr child))))))
  2123. (cons count found)))
  2124. (defvar rst-toc-buffer-name "*Table of Contents*"
  2125. "Name of the Table of Contents buffer.")
  2126. (defvar rst-toc-return-wincfg nil
  2127. "Window configuration to which to return when leaving the TOC.")
  2128. (defun rst-toc ()
  2129. "Display a table-of-contents.
  2130. Finds all the section titles and their adornments in the
  2131. file, and displays a hierarchically-organized list of the
  2132. titles, which is essentially a table-of-contents of the
  2133. document.
  2134. The Emacs buffer can be navigated, and selecting a section
  2135. brings the cursor in that section."
  2136. (interactive)
  2137. (rst-reset-section-caches)
  2138. (let* ((curbuf (list (current-window-configuration) (point-marker)))
  2139. (sectree (rst-section-tree))
  2140. (our-node (cdr (rst-section-tree-point sectree)))
  2141. line
  2142. ;; Create a temporary buffer.
  2143. (buf (get-buffer-create rst-toc-buffer-name))
  2144. )
  2145. (with-current-buffer buf
  2146. (let ((inhibit-read-only t))
  2147. (rst-toc-mode)
  2148. (delete-region (point-min) (point-max))
  2149. (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
  2150. (put-text-property (point-min) (point)
  2151. 'face (list '(background-color . "gray")))
  2152. (rst-toc-node sectree 0)
  2153. ;; Count the lines to our found node.
  2154. (let ((linefound (rst-toc-count-lines sectree our-node)))
  2155. (setq line (if (cdr linefound) (car linefound) 0)))
  2156. ))
  2157. (display-buffer buf)
  2158. (pop-to-buffer buf)
  2159. ;; Save the buffer to return to.
  2160. (set (make-local-variable 'rst-toc-return-wincfg) curbuf)
  2161. ;; Move the cursor near the right section in the TOC.
  2162. (goto-char (point-min))
  2163. (forward-line (1- line))
  2164. ))
  2165. (defun rst-toc-mode-find-section ()
  2166. "Get the section from text property at point."
  2167. (let ((pos (get-text-property (point) 'rst-toc-target)))
  2168. (unless pos
  2169. (error "No section on this line"))
  2170. (unless (buffer-live-p (marker-buffer pos))
  2171. (error "Buffer for this section was killed"))
  2172. pos))
  2173. ;; FIXME: Cursor before or behind the list must be handled properly; before the
  2174. ;; list should jump to the top and behind the list to the last normal
  2175. ;; paragraph.
  2176. (defun rst-goto-section (&optional kill)
  2177. "Go to the section the current line describes.
  2178. If KILL a toc buffer is destroyed."
  2179. (interactive)
  2180. (let ((pos (rst-toc-mode-find-section)))
  2181. (when kill
  2182. ;; FIXME: This should rather go to `rst-toc-mode-goto-section'.
  2183. (set-window-configuration (car rst-toc-return-wincfg))
  2184. (kill-buffer (get-buffer rst-toc-buffer-name)))
  2185. (pop-to-buffer (marker-buffer pos))
  2186. (goto-char pos)
  2187. ;; FIXME: make the recentering conditional on scroll.
  2188. (recenter 5)))
  2189. (defun rst-toc-mode-goto-section ()
  2190. "Go to the section the current line describes and kill the TOC buffer."
  2191. (interactive)
  2192. (rst-goto-section t))
  2193. (defun rst-toc-mode-mouse-goto (event)
  2194. "In `rst-toc' mode, go to the occurrence whose line you click on.
  2195. EVENT is the input event."
  2196. (interactive "e")
  2197. (let ((pos
  2198. (with-current-buffer (window-buffer (posn-window (event-end event)))
  2199. (save-excursion
  2200. (goto-char (posn-point (event-end event)))
  2201. (rst-toc-mode-find-section)))))
  2202. (pop-to-buffer (marker-buffer pos))
  2203. (goto-char pos)
  2204. (recenter 5)))
  2205. (defun rst-toc-mode-mouse-goto-kill (event)
  2206. "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well.
  2207. EVENT is the input event."
  2208. (interactive "e")
  2209. (call-interactively 'rst-toc-mode-mouse-goto event)
  2210. (kill-buffer (get-buffer rst-toc-buffer-name)))
  2211. (defun rst-toc-quit-window ()
  2212. "Leave the current TOC buffer."
  2213. (interactive)
  2214. (let ((retbuf rst-toc-return-wincfg))
  2215. (set-window-configuration (car retbuf))
  2216. (goto-char (cadr retbuf))))
  2217. (defvar rst-toc-mode-map
  2218. (let ((map (make-sparse-keymap)))
  2219. (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
  2220. (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
  2221. (define-key map "\C-m" 'rst-toc-mode-goto-section)
  2222. (define-key map "f" 'rst-toc-mode-goto-section)
  2223. (define-key map "q" 'rst-toc-quit-window)
  2224. (define-key map "z" 'kill-this-buffer)
  2225. map)
  2226. "Keymap for `rst-toc-mode'.")
  2227. (put 'rst-toc-mode 'mode-class 'special)
  2228. ;; Could inherit from the new `special-mode'.
  2229. (define-derived-mode rst-toc-mode nil "ReST-TOC"
  2230. "Major mode for output from \\[rst-toc], the table-of-contents for the document."
  2231. (setq buffer-read-only t))
  2232. ;; Note: use occur-mode (replace.el) as a good example to complete missing
  2233. ;; features.
  2234. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2235. ;; Section movement commands
  2236. ;; =========================
  2237. (defun rst-forward-section (&optional offset)
  2238. "Skip to the next reStructuredText section title.
  2239. OFFSET specifies how many titles to skip. Use a negative OFFSET to move
  2240. backwards in the file (default is to use 1)."
  2241. (interactive)
  2242. (rst-reset-section-caches)
  2243. (let* (;; Default value for offset.
  2244. (offset (or offset 1))
  2245. ;; Get all the adornments in the file, with their line numbers.
  2246. (allados (rst-find-all-adornments))
  2247. ;; Get the current line.
  2248. (curline (line-number-at-pos))
  2249. (cur allados)
  2250. (idx 0)
  2251. )
  2252. ;; Find the index of the "next" adornment w.r.t. to the current line.
  2253. (while (and cur (< (caar cur) curline))
  2254. (setq cur (cdr cur))
  2255. (incf idx))
  2256. ;; 'cur' is the adornment on or following the current line.
  2257. (if (and (> offset 0) cur (= (caar cur) curline))
  2258. (incf idx))
  2259. ;; Find the final index.
  2260. (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
  2261. (setq cur (nth idx allados))
  2262. ;; If the index is positive, goto the line, otherwise go to the buffer
  2263. ;; boundaries.
  2264. (if (and cur (>= idx 0))
  2265. (progn
  2266. (goto-char (point-min))
  2267. (forward-line (1- (car cur))))
  2268. (if (> offset 0) (goto-char (point-max)) (goto-char (point-min))))
  2269. ))
  2270. (defun rst-backward-section ()
  2271. "Like `rst-forward-section', except move back one title."
  2272. (interactive)
  2273. (rst-forward-section -1))
  2274. ;; FIXME: What is `allow-extend' for?
  2275. (defun rst-mark-section (&optional count allow-extend)
  2276. "Select COUNT sections around point.
  2277. Mark following sections for positive COUNT or preceding sections
  2278. for negative COUNT."
  2279. ;; Cloned from mark-paragraph.
  2280. (interactive "p\np")
  2281. (unless count (setq count 1))
  2282. (when (zerop count)
  2283. (error "Cannot mark zero sections"))
  2284. (cond ((and allow-extend
  2285. (or (and (eq last-command this-command) (mark t))
  2286. (rst-portable-mark-active-p)))
  2287. (set-mark
  2288. (save-excursion
  2289. (goto-char (mark))
  2290. (rst-forward-section count)
  2291. (point))))
  2292. (t
  2293. (rst-forward-section count)
  2294. (push-mark nil t t)
  2295. (rst-forward-section (- count)))))
  2296. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2297. ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
  2298. ;; always 2 or 3 characters apart horizontally with rest.
  2299. (defun rst-find-leftmost-column (beg end)
  2300. "Return the leftmost column in region BEG to END."
  2301. (let (mincol)
  2302. (save-excursion
  2303. (goto-char beg)
  2304. (while (< (point) end)
  2305. (back-to-indentation)
  2306. (unless (looking-at (rst-re 'lin-end))
  2307. (setq mincol (if mincol
  2308. (min mincol (current-column))
  2309. (current-column))))
  2310. (forward-line 1)))
  2311. mincol))
  2312. ;; FIXME: This definition is old and deprecated. We need to move to the newer
  2313. ;; version below.
  2314. (defmacro rst-iterate-leftmost-paragraphs
  2315. (beg end first-only body-consequent body-alternative)
  2316. ;; FIXME: The following comment is pretty useless.
  2317. "Call FUN at the beginning of each line, with an argument that
  2318. specifies whether we are at the first line of a paragraph that
  2319. starts at the leftmost column of the given region BEG and END.
  2320. Set FIRST-ONLY to true if you want to callback on the first line
  2321. of each paragraph only."
  2322. `(save-excursion
  2323. (let ((leftcol (rst-find-leftmost-column ,beg ,end))
  2324. (endm (copy-marker ,end)))
  2325. (do* (;; Iterate lines.
  2326. (l (progn (goto-char ,beg) (back-to-indentation))
  2327. (progn (forward-line 1) (back-to-indentation)))
  2328. (previous nil valid)
  2329. (curcol (current-column)
  2330. (current-column))
  2331. (valid (and (= curcol leftcol)
  2332. (not (looking-at (rst-re 'lin-end))))
  2333. (and (= curcol leftcol)
  2334. (not (looking-at (rst-re 'lin-end)))))
  2335. )
  2336. ((>= (point) endm))
  2337. (if (if ,first-only
  2338. (and valid (not previous))
  2339. valid)
  2340. ,body-consequent
  2341. ,body-alternative)
  2342. ))))
  2343. ;; FIXME: This needs to be refactored. Probably this is simply a function
  2344. ;; applying BODY rather than a macro.
  2345. (defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body)
  2346. "Evaluate BODY for each line in region defined by BEG END.
  2347. LEFTMOST is set to true if the line is one of the leftmost of the
  2348. entire paragraph. PARABEGIN is set to true if the line is the
  2349. first of a paragraph."
  2350. (declare (indent 1) (debug (sexp body)))
  2351. (destructuring-bind
  2352. (beg end parabegin leftmost isleftmost isempty) spec
  2353. `(save-excursion
  2354. (let ((,leftmost (rst-find-leftmost-column ,beg ,end))
  2355. (endm (copy-marker ,end)))
  2356. (do* (;; Iterate lines.
  2357. (l (progn (goto-char ,beg) (back-to-indentation))
  2358. (progn (forward-line 1) (back-to-indentation)))
  2359. (empty-line-previous nil ,isempty)
  2360. (,isempty (looking-at (rst-re 'lin-end))
  2361. (looking-at (rst-re 'lin-end)))
  2362. (,parabegin (not ,isempty)
  2363. (and empty-line-previous
  2364. (not ,isempty)))
  2365. (,isleftmost (and (not ,isempty)
  2366. (= (current-column) ,leftmost))
  2367. (and (not ,isempty)
  2368. (= (current-column) ,leftmost)))
  2369. )
  2370. ((>= (point) endm))
  2371. (progn ,@body)
  2372. )))))
  2373. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2374. ;; Indentation
  2375. ;; FIXME: At the moment only block comments with leading empty comment line are
  2376. ;; supported. Comment lines with leading comment markup should be also
  2377. ;; supported. May be a customizable option could control which style to
  2378. ;; prefer.
  2379. (defgroup rst-indent nil "Settings for indentation in reStructuredText.
  2380. In reStructuredText indentation points are usually determined by
  2381. preceding lines. Sometimes the syntax allows arbitrary
  2382. indentation points such as where to start the first line
  2383. following a directive. These indentation widths can be customized
  2384. here."
  2385. :group 'rst
  2386. :package-version '(rst . "1.1.0"))
  2387. (define-obsolete-variable-alias
  2388. 'rst-shift-basic-offset 'rst-indent-width "1.0.0")
  2389. (defcustom rst-indent-width 2
  2390. "Indentation when there is no more indentation point given."
  2391. :group 'rst-indent
  2392. :type '(integer))
  2393. (defcustom rst-indent-field 3
  2394. "Indentation for first line after a field or 0 to always indent for content."
  2395. :group 'rst-indent
  2396. :type '(integer))
  2397. (defcustom rst-indent-literal-normal 3
  2398. "Default indentation for literal block after a markup on an own line."
  2399. :group 'rst-indent
  2400. :type '(integer))
  2401. (defcustom rst-indent-literal-minimized 2
  2402. "Default indentation for literal block after a minimized markup."
  2403. :group 'rst-indent
  2404. :type '(integer))
  2405. (defcustom rst-indent-comment 3
  2406. "Default indentation for first line of a comment."
  2407. :group 'rst-indent
  2408. :type '(integer))
  2409. ;; FIXME: Must consider other tabs:
  2410. ;; * Line blocks
  2411. ;; * Definition lists
  2412. ;; * Option lists
  2413. (defun rst-line-tabs ()
  2414. "Return tabs of the current line or nil for no tab.
  2415. The list is sorted so the tab where writing continues most likely
  2416. is the first one. Each tab is of the form (COLUMN . INNER).
  2417. COLUMN is the column of the tab. INNER is non-nil if this is an
  2418. inner tab. I.e. a tab which does come from the basic indentation
  2419. and not from inner alignment points."
  2420. (save-excursion
  2421. (forward-line 0)
  2422. (save-match-data
  2423. (unless (looking-at (rst-re 'lin-end))
  2424. (back-to-indentation)
  2425. ;; Current indendation is always the least likely tab.
  2426. (let ((tabs (list (list (point) 0 nil)))) ; (POINT OFFSET INNER)
  2427. ;; Push inner tabs more likely to continue writing.
  2428. (cond
  2429. ;; Item.
  2430. ((looking-at (rst-re '(:grp itmany-tag hws-sta) '(:grp "\\S ") "?"))
  2431. (when (match-string 2)
  2432. (push (list (match-beginning 2) 0 t) tabs)))
  2433. ;; Field.
  2434. ((looking-at (rst-re '(:grp fld-tag) '(:grp hws-tag)
  2435. '(:grp "\\S ") "?"))
  2436. (unless (zerop rst-indent-field)
  2437. (push (list (match-beginning 1) rst-indent-field t) tabs))
  2438. (if (match-string 3)
  2439. (push (list (match-beginning 3) 0 t) tabs)
  2440. (if (zerop rst-indent-field)
  2441. (push (list (match-end 2)
  2442. (if (string= (match-string 2) "") 1 0)
  2443. t) tabs))))
  2444. ;; Directive.
  2445. ((looking-at (rst-re 'dir-sta-3 '(:grp "\\S ") "?"))
  2446. (push (list (match-end 1) 0 t) tabs)
  2447. (unless (string= (match-string 2) "")
  2448. (push (list (match-end 2) 0 t) tabs))
  2449. (when (match-string 4)
  2450. (push (list (match-beginning 4) 0 t) tabs)))
  2451. ;; Footnote or citation definition.
  2452. ((looking-at (rst-re 'fnc-sta-2 '(:grp "\\S ") "?"))
  2453. (push (list (match-end 1) 0 t) tabs)
  2454. (when (match-string 3)
  2455. (push (list (match-beginning 3) 0 t) tabs)))
  2456. ;; Comment.
  2457. ((looking-at (rst-re 'cmt-sta-1))
  2458. (push (list (point) rst-indent-comment t) tabs)))
  2459. ;; Start of literal block.
  2460. (when (looking-at (rst-re 'lit-sta-2))
  2461. (let ((tab0 (first tabs)))
  2462. (push (list (first tab0)
  2463. (+ (second tab0)
  2464. (if (match-string 1)
  2465. rst-indent-literal-minimized
  2466. rst-indent-literal-normal))
  2467. t) tabs)))
  2468. (mapcar (lambda (tab)
  2469. (goto-char (first tab))
  2470. (cons (+ (current-column) (second tab)) (third tab)))
  2471. tabs))))))
  2472. (defun rst-compute-tabs (pt)
  2473. "Build the list of possible tabs for all lines above.
  2474. Search backwards from point PT to build the list of possible
  2475. tabs. Return a list of tabs sorted by likeliness to continue
  2476. writing like `rst-line-tabs'. Nearer lines have generally a
  2477. higher likeliness than farther lines. Return nil if no tab is found
  2478. in the text above."
  2479. (save-excursion
  2480. (goto-char pt)
  2481. (let (leftmost ; Leftmost column found so far.
  2482. innermost ; Leftmost column for inner tab.
  2483. tablist)
  2484. (while (and (zerop (forward-line -1))
  2485. (or (not leftmost)
  2486. (> leftmost 0)))
  2487. (let* ((tabs (rst-line-tabs))
  2488. (leftcol (if tabs (apply 'min (mapcar 'car tabs)))))
  2489. (when tabs
  2490. ;; Consider only lines indented less or same if not INNERMOST.
  2491. (when (or (not leftmost)
  2492. (< leftcol leftmost)
  2493. (and (not innermost) (= leftcol leftmost)))
  2494. (dolist (tab tabs)
  2495. (let ((inner (cdr tab))
  2496. (newcol (car tab)))
  2497. (when (and
  2498. (or
  2499. (and (not inner)
  2500. (or (not leftmost)
  2501. (< newcol leftmost)))
  2502. (and inner
  2503. (or (not innermost)
  2504. (< newcol innermost))))
  2505. (not (memq newcol tablist)))
  2506. (push newcol tablist))))
  2507. (setq innermost (if (rst-some (mapcar 'cdr tabs)) ; Has inner.
  2508. leftcol
  2509. innermost))
  2510. (setq leftmost leftcol)))))
  2511. (nreverse tablist))))
  2512. (defun rst-indent-line (&optional dflt)
  2513. "Indent current line to next best reStructuredText tab.
  2514. The next best tab is taken from the tab list returned by
  2515. `rst-compute-tabs' which is used in a cyclic manner. If the
  2516. current indentation does not end on a tab use the first one. If
  2517. the current indentation is on a tab use the next tab. This allows
  2518. a repeated use of \\[indent-for-tab-command] to cycle through all
  2519. possible tabs. If no indentation is possible return `noindent' or
  2520. use DFLT. Return the indentation indented to. When point is in
  2521. indentation it ends up at its end. Otherwise the point is kept
  2522. relative to the content."
  2523. (let* ((pt (point-marker))
  2524. (cur (current-indentation))
  2525. (clm (current-column))
  2526. (tabs (rst-compute-tabs (point)))
  2527. (fnd (rst-position cur tabs))
  2528. ind)
  2529. (if (and (not tabs) (not dflt))
  2530. 'noindent
  2531. (if (not tabs)
  2532. (setq ind dflt)
  2533. (if (not fnd)
  2534. (setq fnd 0)
  2535. (setq fnd (1+ fnd))
  2536. (if (>= fnd (length tabs))
  2537. (setq fnd 0)))
  2538. (setq ind (nth fnd tabs)))
  2539. (indent-line-to ind)
  2540. (if (> clm cur)
  2541. (goto-char pt))
  2542. (set-marker pt nil)
  2543. ind)))
  2544. (defun rst-shift-region (beg end cnt)
  2545. "Shift region BEG to END by CNT tabs.
  2546. Shift by one tab to the right (CNT > 0) or left (CNT < 0) or
  2547. remove all indentation (CNT = 0). A tab is taken from the text
  2548. above. If no suitable tab is found `rst-indent-width' is used."
  2549. (interactive "r\np")
  2550. (let ((tabs (sort (rst-compute-tabs beg) (lambda (x y) (<= x y))))
  2551. (leftmostcol (rst-find-leftmost-column beg end)))
  2552. (when (or (> leftmostcol 0) (> cnt 0))
  2553. ;; Apply the indent.
  2554. (indent-rigidly
  2555. beg end
  2556. (if (zerop cnt)
  2557. (- leftmostcol)
  2558. ;; Find the next tab after the leftmost column.
  2559. (let* ((cmp (if (> cnt 0) '> '<))
  2560. (tabs (if (> cnt 0) tabs (reverse tabs)))
  2561. (len (length tabs))
  2562. (dir (rst-signum cnt)) ; Direction to take.
  2563. (abs (abs cnt)) ; Absolute number of steps to take.
  2564. ;; Get the position of the first tab beyond leftmostcol.
  2565. (fnd (lexical-let ((cmp cmp)
  2566. (leftmostcol leftmostcol)) ; Create closure.
  2567. (rst-position-if (lambda (elt)
  2568. (funcall cmp elt leftmostcol))
  2569. tabs)))
  2570. ;; Virtual position of tab.
  2571. (pos (+ (or fnd len) (1- abs)))
  2572. (tab (if (< pos len)
  2573. ;; Tab exists - use it.
  2574. (nth pos tabs)
  2575. ;; Column needs to be computed.
  2576. (let ((col (+ (or (car (last tabs)) leftmostcol)
  2577. ;; Base on last known column.
  2578. (* (- pos (1- len)) ; Distance left.
  2579. dir ; Direction to take.
  2580. rst-indent-width))))
  2581. (if (< col 0) 0 col)))))
  2582. (- tab leftmostcol)))))))
  2583. ;; FIXME: A paragraph with an (incorrectly) indented second line is not filled
  2584. ;; correctly::
  2585. ;;
  2586. ;; Some start
  2587. ;; continued wrong
  2588. (defun rst-adaptive-fill ()
  2589. "Return fill prefix found at point.
  2590. Value for `adaptive-fill-function'."
  2591. (let ((fnd (if (looking-at adaptive-fill-regexp)
  2592. (match-string-no-properties 0))))
  2593. (if (save-match-data
  2594. (not (string-match comment-start-skip fnd)))
  2595. ;; An non-comment prefix is fine.
  2596. fnd
  2597. ;; Matches a comment - return whitespace instead.
  2598. (make-string (-
  2599. (save-excursion
  2600. (goto-char (match-end 0))
  2601. (current-column))
  2602. (save-excursion
  2603. (goto-char (match-beginning 0))
  2604. (current-column))) ? ))))
  2605. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2606. ;; Comments
  2607. (defun rst-comment-line-break (&optional soft)
  2608. "Break line and indent, continuing reStructuredText comment if within one.
  2609. Value for `comment-line-break-function'. If SOFT use soft
  2610. newlines as mandated by `comment-line-break-function'."
  2611. (if soft
  2612. (insert-and-inherit ?\n)
  2613. (newline 1))
  2614. (save-excursion
  2615. (forward-char -1)
  2616. (delete-horizontal-space))
  2617. (delete-horizontal-space)
  2618. (let ((tabs (rst-compute-tabs (point))))
  2619. (when tabs
  2620. (indent-line-to (car tabs)))))
  2621. (defun rst-comment-indent ()
  2622. "Return indentation for current comment line."
  2623. (car (rst-compute-tabs (point))))
  2624. (defun rst-comment-insert-comment ()
  2625. "Insert a comment in the current line."
  2626. (rst-indent-line 0)
  2627. (insert comment-start))
  2628. (defun rst-comment-region (beg end &optional arg)
  2629. "Comment or uncomment the current region.
  2630. Region is from from BEG to END. Uncomment if ARG."
  2631. (save-excursion
  2632. (if (consp arg)
  2633. (rst-uncomment-region beg end arg)
  2634. (goto-char beg)
  2635. (let ((ind (current-indentation))
  2636. bol)
  2637. (forward-line 0)
  2638. (setq bol (point))
  2639. (indent-rigidly bol end rst-indent-comment)
  2640. (goto-char bol)
  2641. (open-line 1)
  2642. (indent-line-to ind)
  2643. (insert (comment-string-strip comment-start t t))))))
  2644. (defun rst-uncomment-region (beg end &optional arg)
  2645. "Uncomment the current region.
  2646. Region is from BEG to END. ARG is ignored"
  2647. (save-excursion
  2648. (let (bol eol)
  2649. (goto-char beg)
  2650. (forward-line 0)
  2651. (setq bol (point))
  2652. (forward-line 1)
  2653. (setq eol (point))
  2654. (indent-rigidly eol end (- rst-indent-comment))
  2655. (delete-region bol eol))))
  2656. ;;------------------------------------------------------------------------------
  2657. ;; FIXME: These next functions should become part of a larger effort to redo
  2658. ;; the bullets in bulleted lists. The enumerate would just be one of
  2659. ;; the possible outputs.
  2660. ;;
  2661. ;; FIXME: We need to do the enumeration removal as well.
  2662. (defun rst-enumerate-region (beg end all)
  2663. "Add enumeration to all the leftmost paragraphs in the given region.
  2664. The region is specified between BEG and END. With ALL,
  2665. do all lines instead of just paragraphs."
  2666. (interactive "r\nP")
  2667. (let ((count 0)
  2668. (last-insert-len nil))
  2669. (rst-iterate-leftmost-paragraphs
  2670. beg end (not all)
  2671. (let ((ins-string (format "%d. " (incf count))))
  2672. (setq last-insert-len (length ins-string))
  2673. (insert ins-string))
  2674. (insert (make-string last-insert-len ?\ ))
  2675. )))
  2676. (defun rst-bullet-list-region (beg end all)
  2677. "Add bullets to all the leftmost paragraphs in the given region.
  2678. The region is specified between BEG and END. With ALL,
  2679. do all lines instead of just paragraphs."
  2680. (interactive "r\nP")
  2681. (rst-iterate-leftmost-paragraphs
  2682. beg end (not all)
  2683. (insert (car rst-preferred-bullets) " ")
  2684. (insert " ")
  2685. ))
  2686. ;; FIXME: Does not deal with a varying number of digits appropriately.
  2687. ;; FIXME: Does not deal with multiple levels independently.
  2688. ;; FIXME: Does not indent a multiline item correctly.
  2689. (defun rst-convert-bullets-to-enumeration (beg end)
  2690. "Convert the bulleted and enumerated items in the region to enumerated lists.
  2691. Renumber as necessary. Region is from BEG to END."
  2692. (interactive "r")
  2693. (let* (;; Find items and convert the positions to markers.
  2694. (items (mapcar
  2695. (lambda (x)
  2696. (cons (copy-marker (car x))
  2697. (cdr x)))
  2698. (rst-find-pfx-in-region beg end (rst-re 'itmany-sta-1))))
  2699. (count 1)
  2700. )
  2701. (save-excursion
  2702. (dolist (x items)
  2703. (goto-char (car x))
  2704. (looking-at (rst-re 'itmany-beg-1))
  2705. (replace-match (format "%d." count) nil nil nil 1)
  2706. (incf count)
  2707. ))
  2708. ))
  2709. ;;------------------------------------------------------------------------------
  2710. (defun rst-line-block-region (rbeg rend &optional pfxarg)
  2711. "Toggle line block prefixes for a region.
  2712. Region is from RBEG to REND. With PFXARG set the empty lines too."
  2713. (interactive "r\nP")
  2714. (let ((comment-start "| ")
  2715. (comment-end "")
  2716. (comment-start-skip "| ")
  2717. (comment-style 'indent)
  2718. (force (not (not pfxarg))))
  2719. (rst-iterate-leftmost-paragraphs-2
  2720. (rbeg rend parbegin leftmost isleft isempty)
  2721. (when (or force (not isempty))
  2722. (move-to-column leftmost force)
  2723. (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
  2724. (insert "| ")))))
  2725. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2726. ;; Font lock
  2727. ;; =========
  2728. (require 'font-lock)
  2729. ;; FIXME: The obsolete variables need to disappear.
  2730. ;; The following versions have been done inside Emacs and should not be
  2731. ;; replaced by `:package-version' attributes until a change.
  2732. (defgroup rst-faces nil "Faces used in Rst Mode."
  2733. :group 'rst
  2734. :group 'faces
  2735. :version "21.1")
  2736. (defface rst-block '((t :inherit font-lock-keyword-face))
  2737. "Face used for all syntax marking up a special block."
  2738. :version "24.1"
  2739. :group 'rst-faces)
  2740. (defcustom rst-block-face 'rst-block
  2741. "All syntax marking up a special block."
  2742. :version "24.1"
  2743. :group 'rst-faces
  2744. :type '(face))
  2745. (make-obsolete-variable 'rst-block-face
  2746. "customize the face `rst-block' instead."
  2747. "24.1")
  2748. (defface rst-external '((t :inherit font-lock-type-face))
  2749. "Face used for field names and interpreted text."
  2750. :version "24.1"
  2751. :group 'rst-faces)
  2752. (defcustom rst-external-face 'rst-external
  2753. "Field names and interpreted text."
  2754. :version "24.1"
  2755. :group 'rst-faces
  2756. :type '(face))
  2757. (make-obsolete-variable 'rst-external-face
  2758. "customize the face `rst-external' instead."
  2759. "24.1")
  2760. (defface rst-definition '((t :inherit font-lock-function-name-face))
  2761. "Face used for all other defining constructs."
  2762. :version "24.1"
  2763. :group 'rst-faces)
  2764. (defcustom rst-definition-face 'rst-definition
  2765. "All other defining constructs."
  2766. :version "24.1"
  2767. :group 'rst-faces
  2768. :type '(face))
  2769. (make-obsolete-variable 'rst-definition-face
  2770. "customize the face `rst-definition' instead."
  2771. "24.1")
  2772. ;; XEmacs compatibility (?).
  2773. (defface rst-directive (if (boundp 'font-lock-builtin-face)
  2774. '((t :inherit font-lock-builtin-face))
  2775. '((t :inherit font-lock-preprocessor-face)))
  2776. "Face used for directives and roles."
  2777. :version "24.1"
  2778. :group 'rst-faces)
  2779. (defcustom rst-directive-face 'rst-directive
  2780. "Directives and roles."
  2781. :group 'rst-faces
  2782. :type '(face))
  2783. (make-obsolete-variable 'rst-directive-face
  2784. "customize the face `rst-directive' instead."
  2785. "24.1")
  2786. (defface rst-comment '((t :inherit font-lock-comment-face))
  2787. "Face used for comments."
  2788. :version "24.1"
  2789. :group 'rst-faces)
  2790. (defcustom rst-comment-face 'rst-comment
  2791. "Comments."
  2792. :version "24.1"
  2793. :group 'rst-faces
  2794. :type '(face))
  2795. (make-obsolete-variable 'rst-comment-face
  2796. "customize the face `rst-comment' instead."
  2797. "24.1")
  2798. (defface rst-emphasis1 '((t :inherit italic))
  2799. "Face used for simple emphasis."
  2800. :version "24.1"
  2801. :group 'rst-faces)
  2802. (defcustom rst-emphasis1-face 'rst-emphasis1
  2803. "Simple emphasis."
  2804. :version "24.1"
  2805. :group 'rst-faces
  2806. :type '(face))
  2807. (make-obsolete-variable 'rst-emphasis1-face
  2808. "customize the face `rst-emphasis1' instead."
  2809. "24.1")
  2810. (defface rst-emphasis2 '((t :inherit bold))
  2811. "Face used for double emphasis."
  2812. :version "24.1"
  2813. :group 'rst-faces)
  2814. (defcustom rst-emphasis2-face 'rst-emphasis2
  2815. "Double emphasis."
  2816. :group 'rst-faces
  2817. :type '(face))
  2818. (make-obsolete-variable 'rst-emphasis2-face
  2819. "customize the face `rst-emphasis2' instead."
  2820. "24.1")
  2821. (defface rst-literal '((t :inherit font-lock-string-face))
  2822. "Face used for literal text."
  2823. :version "24.1"
  2824. :group 'rst-faces)
  2825. (defcustom rst-literal-face 'rst-literal
  2826. "Literal text."
  2827. :version "24.1"
  2828. :group 'rst-faces
  2829. :type '(face))
  2830. (make-obsolete-variable 'rst-literal-face
  2831. "customize the face `rst-literal' instead."
  2832. "24.1")
  2833. (defface rst-reference '((t :inherit font-lock-variable-name-face))
  2834. "Face used for references to a definition."
  2835. :version "24.1"
  2836. :group 'rst-faces)
  2837. (defcustom rst-reference-face 'rst-reference
  2838. "References to a definition."
  2839. :version "24.1"
  2840. :group 'rst-faces
  2841. :type '(face))
  2842. (make-obsolete-variable 'rst-reference-face
  2843. "customize the face `rst-reference' instead."
  2844. "24.1")
  2845. (defface rst-transition '((t :inherit font-lock-keyword-face))
  2846. "Face used for a transition."
  2847. :package-version '(rst . "1.3.0")
  2848. :group 'rst-faces)
  2849. (defface rst-adornment '((t :inherit font-lock-keyword-face))
  2850. "Face used for the adornment of a section header."
  2851. :package-version '(rst . "1.3.0")
  2852. :group 'rst-faces)
  2853. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2854. ;; FIXME LEVEL-FACE: May be this complicated mechanism should be replaced
  2855. ;; simply by a number of customizable faces `rst-header-%d'
  2856. ;; which by default are set properly for dark and light
  2857. ;; background. Initialization should come from the old
  2858. ;; variables if they exist. A maximum level of 6 should
  2859. ;; suffice - after that the last level should be repeated.
  2860. ;; Only `rst-adornment-faces-alist' is needed outside this
  2861. ;; block. Would also fix docutils-Bugs-3479594.
  2862. (defgroup rst-faces-defaults nil
  2863. "Values used to generate default faces for section titles on all levels.
  2864. Tweak these if you are content with how section title faces are built in
  2865. general but you do not like the details."
  2866. :group 'rst-faces
  2867. :version "21.1")
  2868. (defun rst-set-level-default (sym val)
  2869. "Set custom variable SYM affecting section title text face.
  2870. Recompute the faces. VAL is the value to set."
  2871. (custom-set-default sym val)
  2872. ;; Also defines the faces initially when all values are available.
  2873. (and (boundp 'rst-level-face-max)
  2874. (boundp 'rst-level-face-format-light)
  2875. (boundp 'rst-level-face-base-color)
  2876. (boundp 'rst-level-face-step-light)
  2877. (boundp 'rst-level-face-base-light)
  2878. (fboundp 'rst-define-level-faces)
  2879. (rst-define-level-faces)))
  2880. ;; Faces for displaying items on several levels. These definitions define
  2881. ;; different shades of gray where the lightest one (i.e. least contrasting on a
  2882. ;; light background) is used for level 1.
  2883. (defcustom rst-level-face-max 6
  2884. "Maximum depth of levels for which section title faces are defined."
  2885. :group 'rst-faces-defaults
  2886. :type '(integer)
  2887. :set 'rst-set-level-default)
  2888. ;; FIXME: It should be possible to give "#RRGGBB" type of color values.
  2889. ;; Together with a `rst-level-face-end-light' this could be used for
  2890. ;; computing steps.
  2891. ;; FIXME: This variable should be combined with `rst-level-face-format-light'
  2892. ;; to a single string.
  2893. (defcustom rst-level-face-base-color "grey"
  2894. "Base name of the color for creating background colors in section title faces."
  2895. :group 'rst-faces-defaults
  2896. :type '(string)
  2897. :set 'rst-set-level-default)
  2898. ;; FIXME LEVEL-FACE: This needs to be done differently: The faces must specify
  2899. ;; how they behave for dark and light background using the
  2900. ;; relevant options explained in `defface'.
  2901. (defcustom rst-level-face-base-light
  2902. (if (eq frame-background-mode 'dark)
  2903. 15
  2904. 85)
  2905. "The lightness factor for the base color. This value is used for level 1.
  2906. The default depends on whether the value of `frame-background-mode' is
  2907. `dark' or not."
  2908. :group 'rst-faces-defaults
  2909. :type '(integer)
  2910. :set 'rst-set-level-default)
  2911. (defcustom rst-level-face-format-light "%2d"
  2912. "The format for the lightness factor appended to the base name of the color.
  2913. This value is expanded by `format' with an integer."
  2914. :group 'rst-faces-defaults
  2915. :type '(string)
  2916. :set 'rst-set-level-default)
  2917. ;; FIXME LEVEL-FACE: This needs to be done differently: The faces must specify
  2918. ;; how they behave for dark and light background using the
  2919. ;; relevant options explained in `defface'.
  2920. ;; FIXME: Alternatively there could be a customizable variable
  2921. ;; `rst-level-face-end-light' which defines the end value and steps are
  2922. ;; computed
  2923. (defcustom rst-level-face-step-light
  2924. (if (eq frame-background-mode 'dark)
  2925. 7
  2926. -7)
  2927. "The step width to use for the next color.
  2928. The formula
  2929. `rst-level-face-base-light'
  2930. + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
  2931. must result in a color level which appended to `rst-level-face-base-color'
  2932. using `rst-level-face-format-light' results in a valid color such as `grey50'.
  2933. This color is used as background for section title text on level
  2934. `rst-level-face-max'."
  2935. :group 'rst-faces-defaults
  2936. :type '(integer)
  2937. :set 'rst-set-level-default)
  2938. (defcustom rst-adornment-faces-alist
  2939. ;; FIXME LEVEL-FACE: Must be redone if `rst-level-face-max' is changed
  2940. (let ((alist (copy-list '((t . rst-transition)
  2941. (nil . rst-adornment))))
  2942. (i 1))
  2943. (while (<= i rst-level-face-max)
  2944. (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
  2945. (setq i (1+ i)))
  2946. alist)
  2947. "Faces for the various adornment types.
  2948. Key is a number (for the section title text of that level
  2949. starting with 1), t (for transitions) or nil (for section title
  2950. adornment). If you generally do not like how section title text
  2951. faces are set up tweak here. If the general idea is ok for you
  2952. but you do not like the details check the Rst Faces Defaults
  2953. group."
  2954. :group 'rst-faces
  2955. :type '(alist
  2956. :key-type
  2957. (choice
  2958. (integer :tag "Section level")
  2959. (const :tag "transitions" t)
  2960. (const :tag "section title adornment" nil))
  2961. :value-type (face))
  2962. :set-after '(rst-level-face-max))
  2963. (defun rst-define-level-faces ()
  2964. "Define the faces for the section title text faces from the values."
  2965. ;; All variables used here must be checked in `rst-set-level-default'.
  2966. (let ((i 1))
  2967. (while (<= i rst-level-face-max)
  2968. (let ((sym (intern (format "rst-level-%d-face" i)))
  2969. (doc (format "Default face for showing section title text at level %d.
  2970. This symbol is *not* meant for customization but modified if a
  2971. variable of the `rst-faces-defaults' group is customized. Use
  2972. `rst-adornment-faces-alist' for customization instead." i))
  2973. (col (format (concat "%s" rst-level-face-format-light)
  2974. rst-level-face-base-color
  2975. (+ (* (1- i) rst-level-face-step-light)
  2976. rst-level-face-base-light))))
  2977. (make-empty-face sym)
  2978. (set-face-doc-string sym doc)
  2979. (set-face-background sym col)
  2980. (set sym sym)
  2981. (setq i (1+ i))))))
  2982. ;; FIXME LEVEL-FACE: This is probably superfluous since it is done by the
  2983. ;; customization / `rst-set-level-default'.
  2984. (rst-define-level-faces)
  2985. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2986. (defvar rst-font-lock-keywords
  2987. ;; The reST-links in the comments below all relate to sections in
  2988. ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html.
  2989. `(;; FIXME: Block markup is not recognized in blocks after explicit markup
  2990. ;; start.
  2991. ;; Simple `Body Elements`_
  2992. ;; `Bullet Lists`_
  2993. ;; FIXME: A bullet directly after a field name is not recognized.
  2994. (,(rst-re 'lin-beg '(:grp bul-sta))
  2995. 1 rst-block-face)
  2996. ;; `Enumerated Lists`_
  2997. (,(rst-re 'lin-beg '(:grp enmany-sta))
  2998. 1 rst-block-face)
  2999. ;; `Definition Lists`_
  3000. ;; FIXME: missing.
  3001. ;; `Field Lists`_
  3002. (,(rst-re 'lin-beg '(:grp fld-tag) 'bli-sfx)
  3003. 1 rst-external-face)
  3004. ;; `Option Lists`_
  3005. (,(rst-re 'lin-beg '(:grp opt-tag (:shy optsep-tag opt-tag) "*")
  3006. '(:alt "$" (:seq hws-prt "\\{2\\}")))
  3007. 1 rst-block-face)
  3008. ;; `Line Blocks`_
  3009. ;; Only for lines containing no more bar - to distinguish from tables.
  3010. (,(rst-re 'lin-beg '(:grp "|" bli-sfx) "[^|\n]*$")
  3011. 1 rst-block-face)
  3012. ;; `Tables`_
  3013. ;; FIXME: missing
  3014. ;; All the `Explicit Markup Blocks`_
  3015. ;; `Footnotes`_ / `Citations`_
  3016. (,(rst-re 'lin-beg 'fnc-sta-2)
  3017. (1 rst-definition-face)
  3018. (2 rst-definition-face))
  3019. ;; `Directives`_ / `Substitution Definitions`_
  3020. (,(rst-re 'lin-beg 'dir-sta-3)
  3021. (1 rst-directive-face)
  3022. (2 rst-definition-face)
  3023. (3 rst-directive-face))
  3024. ;; `Hyperlink Targets`_
  3025. (,(rst-re 'lin-beg
  3026. '(:grp exm-sta "_" (:alt
  3027. (:seq "`" ilcbkqdef-tag "`")
  3028. (:seq (:alt "[^:\\\n]" "\\\\.") "+")) ":")
  3029. 'bli-sfx)
  3030. 1 rst-definition-face)
  3031. (,(rst-re 'lin-beg '(:grp "__") 'bli-sfx)
  3032. 1 rst-definition-face)
  3033. ;; All `Inline Markup`_
  3034. ;; Most of them may be multiline though this is uninteresting.
  3035. ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
  3036. ;; `Strong Emphasis`_.
  3037. (,(rst-re 'ilm-pfx '(:grp "\\*\\*" ilcast-tag "\\*\\*") 'ilm-sfx)
  3038. 1 rst-emphasis2-face)
  3039. ;; `Emphasis`_
  3040. (,(rst-re 'ilm-pfx '(:grp "\\*" ilcast-tag "\\*") 'ilm-sfx)
  3041. 1 rst-emphasis1-face)
  3042. ;; `Inline Literals`_
  3043. (,(rst-re 'ilm-pfx '(:grp "``" ilcbkq-tag "``") 'ilm-sfx)
  3044. 1 rst-literal-face)
  3045. ;; `Inline Internal Targets`_
  3046. (,(rst-re 'ilm-pfx '(:grp "_`" ilcbkq-tag "`") 'ilm-sfx)
  3047. 1 rst-definition-face)
  3048. ;; `Hyperlink References`_
  3049. ;; FIXME: `Embedded URIs`_ not considered.
  3050. ;; FIXME: Directly adjacent marked up words are not fontified correctly
  3051. ;; unless they are not separated by two spaces: foo_ bar_.
  3052. (,(rst-re 'ilm-pfx '(:grp (:alt (:seq "`" ilcbkq-tag "`")
  3053. (:seq "\\sw" (:alt "\\sw" "-") "+\\sw"))
  3054. "__?") 'ilm-sfx)
  3055. 1 rst-reference-face)
  3056. ;; `Interpreted Text`_
  3057. (,(rst-re 'ilm-pfx '(:grp (:shy ":" sym-tag ":") "?")
  3058. '(:grp "`" ilcbkq-tag "`")
  3059. '(:grp (:shy ":" sym-tag ":") "?") 'ilm-sfx)
  3060. (1 rst-directive-face)
  3061. (2 rst-external-face)
  3062. (3 rst-directive-face))
  3063. ;; `Footnote References`_ / `Citation References`_
  3064. (,(rst-re 'ilm-pfx '(:grp fnc-tag "_") 'ilm-sfx)
  3065. 1 rst-reference-face)
  3066. ;; `Substitution References`_
  3067. ;; FIXME: References substitutions like |this|_ or |this|__ are not
  3068. ;; fontified correctly.
  3069. (,(rst-re 'ilm-pfx '(:grp sub-tag) 'ilm-sfx)
  3070. 1 rst-reference-face)
  3071. ;; `Standalone Hyperlinks`_
  3072. ;; FIXME: This takes it easy by using a whitespace as delimiter.
  3073. (,(rst-re 'ilm-pfx '(:grp uri-tag ":\\S +") 'ilm-sfx)
  3074. 1 rst-definition-face)
  3075. (,(rst-re 'ilm-pfx '(:grp sym-tag "@" sym-tag ) 'ilm-sfx)
  3076. 1 rst-definition-face)
  3077. ;; Do all block fontification as late as possible so 'append works.
  3078. ;; Sections_ / Transitions_
  3079. ;; For sections this is multiline.
  3080. (,(rst-re 'ado-beg-2-1)
  3081. (rst-font-lock-handle-adornment-matcher
  3082. (rst-font-lock-handle-adornment-pre-match-form
  3083. (match-string-no-properties 1) (match-end 1))
  3084. nil
  3085. (1 (cdr (assoc nil rst-adornment-faces-alist)) append t)
  3086. (2 (cdr (assoc rst-font-lock-adornment-level
  3087. rst-adornment-faces-alist)) append t)
  3088. (3 (cdr (assoc nil rst-adornment-faces-alist)) append t)))
  3089. ;; FIXME: FACESPEC could be used instead of ordinary faces to set
  3090. ;; properties on comments and literal blocks so they are *not*
  3091. ;; inline fontified. See (elisp)Search-based Fontification.
  3092. ;; FIXME: And / or use `syntax-propertize` functions as in `octave-mod.el`
  3093. ;; and other V24 modes. May make `font-lock-extend-region`
  3094. ;; superfluous.
  3095. ;; `Comments`_
  3096. ;; This is multiline.
  3097. (,(rst-re 'lin-beg 'cmt-sta-1)
  3098. (1 rst-comment-face)
  3099. (rst-font-lock-find-unindented-line-match
  3100. (rst-font-lock-find-unindented-line-limit (match-end 1))
  3101. nil
  3102. (0 rst-comment-face append)))
  3103. (,(rst-re 'lin-beg '(:grp exm-tag) '(:grp hws-tag) "$")
  3104. (1 rst-comment-face)
  3105. (2 rst-comment-face)
  3106. (rst-font-lock-find-unindented-line-match
  3107. (rst-font-lock-find-unindented-line-limit 'next)
  3108. nil
  3109. (0 rst-comment-face append)))
  3110. ;; FIXME: This is not rendered as comment::
  3111. ;; .. .. list-table::
  3112. ;; :stub-columns: 1
  3113. ;; :header-rows: 1
  3114. ;; FIXME: This is rendered wrong::
  3115. ;;
  3116. ;; xxx yyy::
  3117. ;;
  3118. ;; ----|> KKKKK <|----
  3119. ;; / \
  3120. ;; -|> AAAAAAAAAAPPPPPP <|- -|> AAAAAAAAAABBBBBBB <|-
  3121. ;; | | | |
  3122. ;; | | | |
  3123. ;; PPPPPP PPPPPPDDDDDDD BBBBBBB PPPPPPBBBBBBB
  3124. ;;
  3125. ;; Indentation needs to be taken from the line with the ``::`` and not from
  3126. ;; the first content line.
  3127. ;; `Indented Literal Blocks`_
  3128. ;; This is multiline.
  3129. (,(rst-re 'lin-beg 'lit-sta-2)
  3130. (2 rst-block-face)
  3131. (rst-font-lock-find-unindented-line-match
  3132. (rst-font-lock-find-unindented-line-limit t)
  3133. nil
  3134. (0 rst-literal-face append)))
  3135. ;; FIXME: `Quoted Literal Blocks`_ missing.
  3136. ;; This is multiline.
  3137. ;; `Doctest Blocks`_
  3138. ;; FIXME: This is wrong according to the specification:
  3139. ;;
  3140. ;; Doctest blocks are text blocks which begin with ">>> ", the Python
  3141. ;; interactive interpreter main prompt, and end with a blank line.
  3142. ;; Doctest blocks are treated as a special case of literal blocks,
  3143. ;; without requiring the literal block syntax. If both are present, the
  3144. ;; literal block syntax takes priority over Doctest block syntax:
  3145. ;;
  3146. ;; This is an ordinary paragraph.
  3147. ;;
  3148. ;; >>> print 'this is a Doctest block'
  3149. ;; this is a Doctest block
  3150. ;;
  3151. ;; The following is a literal block::
  3152. ;;
  3153. ;; >>> This is not recognized as a doctest block by
  3154. ;; reStructuredText. It *will* be recognized by the doctest
  3155. ;; module, though!
  3156. ;;
  3157. ;; Indentation is not required for doctest blocks.
  3158. (,(rst-re 'lin-beg '(:grp (:alt ">>>" ell-tag)) '(:grp ".+"))
  3159. (1 rst-block-face)
  3160. (2 rst-literal-face))
  3161. )
  3162. "Keywords to highlight in rst mode.")
  3163. (defvar font-lock-beg)
  3164. (defvar font-lock-end)
  3165. (defun rst-font-lock-extend-region ()
  3166. "Extend the font-lock region if it might be in a multi-line construct.
  3167. Return non-nil if so. Font-lock region is from `font-lock-beg'
  3168. to `font-lock-end'."
  3169. (let ((r (rst-font-lock-extend-region-internal font-lock-beg font-lock-end)))
  3170. (when r
  3171. (setq font-lock-beg (car r))
  3172. (setq font-lock-end (cdr r))
  3173. t)))
  3174. (defun rst-font-lock-extend-region-internal (beg end)
  3175. "Check the region BEG / END for being in the middle of a multi-line construct.
  3176. Return nil if not or a cons with new values for BEG / END"
  3177. (let ((nbeg (rst-font-lock-extend-region-extend beg -1))
  3178. (nend (rst-font-lock-extend-region-extend end 1)))
  3179. (if (or nbeg nend)
  3180. (cons (or nbeg beg) (or nend end)))))
  3181. (defun rst-forward-line (&optional n)
  3182. "Like `forward-line' but always end up in column 0 and return accordingly.
  3183. Move N lines forward just as `forward-line'."
  3184. (let ((moved (forward-line n)))
  3185. (if (bolp)
  3186. moved
  3187. (forward-line 0)
  3188. (- moved (rst-signum n)))))
  3189. ;; FIXME: If a single line is made a section header by `rst-adjust' the header
  3190. ;; is not always fontified immediately.
  3191. (defun rst-font-lock-extend-region-extend (pt dir)
  3192. "Extend the region starting at point PT and extending in direction DIR.
  3193. Return extended point or nil if not moved."
  3194. ;; There are many potential multiline constructs but there are two groups
  3195. ;; which are really relevant. The first group consists of
  3196. ;;
  3197. ;; * comment lines without leading explicit markup tag and
  3198. ;;
  3199. ;; * literal blocks following "::"
  3200. ;;
  3201. ;; which are both indented. Thus indentation is the first thing recognized
  3202. ;; here. The second criteria is an explicit markup tag which may be a comment
  3203. ;; or a double colon at the end of a line.
  3204. ;;
  3205. ;; The second group consists of the adornment cases.
  3206. (if (not (get-text-property pt 'font-lock-multiline))
  3207. ;; Move only if we don't start inside a multiline construct already.
  3208. (save-excursion
  3209. (let (;; Non-empty non-indented line, explicit markup tag or literal
  3210. ;; block tag.
  3211. (stop-re (rst-re '(:alt "[^ \t\n]"
  3212. (:seq hws-tag exm-tag)
  3213. (:seq ".*" dcl-tag lin-end)))))
  3214. ;; The comments below are for dir == -1 / dir == 1.
  3215. (goto-char pt)
  3216. (forward-line 0)
  3217. (setq pt (point))
  3218. (while (and (not (looking-at stop-re))
  3219. (zerop (rst-forward-line dir)))) ; try previous / next
  3220. ; line if it exists.
  3221. (if (looking-at (rst-re 'ado-beg-2-1)) ; may be an underline /
  3222. ; overline.
  3223. (if (zerop (rst-forward-line dir))
  3224. (if (looking-at (rst-re 'ttl-beg)) ; title found, i.e.
  3225. ; underline / overline
  3226. ; found.
  3227. (if (zerop (rst-forward-line dir))
  3228. (if (not
  3229. (looking-at (rst-re 'ado-beg-2-1))) ; no
  3230. ; overline /
  3231. ; underline.
  3232. (rst-forward-line (- dir)))) ; step back to title
  3233. ; / adornment.
  3234. (if (< dir 0) ; keep downward adornment.
  3235. (rst-forward-line (- dir))))) ; step back to adornment.
  3236. (if (looking-at (rst-re 'ttl-beg)) ; may be a title.
  3237. (if (zerop (rst-forward-line dir))
  3238. (if (not
  3239. (looking-at (rst-re 'ado-beg-2-1))) ; no overline /
  3240. ; underline.
  3241. (rst-forward-line (- dir)))))) ; step back to line.
  3242. (if (not (= (point) pt))
  3243. (point))))))
  3244. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  3245. ;; Indented blocks
  3246. (defun rst-forward-indented-block (&optional column limit)
  3247. "Move forward across one indented block.
  3248. Find the next non-empty line which is not indented at least to COLUMN (defaults
  3249. to the column of the point). Moves point to first character of this line or the
  3250. first empty line immediately before it and returns that position. If there is
  3251. no such line before LIMIT (defaults to the end of the buffer) returns nil and
  3252. point is not moved."
  3253. (interactive)
  3254. (let ((clm (or column (current-column)))
  3255. (start (point))
  3256. fnd beg cand)
  3257. (if (not limit)
  3258. (setq limit (point-max)))
  3259. (save-match-data
  3260. (while (and (not fnd) (< (point) limit))
  3261. (forward-line 1)
  3262. (when (< (point) limit)
  3263. (setq beg (point))
  3264. (if (looking-at (rst-re 'lin-end))
  3265. (setq cand (or cand beg)) ; An empty line is a candidate.
  3266. (move-to-column clm)
  3267. ;; FIXME: No indentation [(zerop clm)] must be handled in some
  3268. ;; useful way - though it is not clear what this should mean
  3269. ;; at all.
  3270. (if (string-match
  3271. (rst-re 'linemp-tag)
  3272. (buffer-substring-no-properties beg (point)))
  3273. (setq cand nil) ; An indented line resets a candidate.
  3274. (setq fnd (or cand beg)))))))
  3275. (goto-char (or fnd start))
  3276. fnd))
  3277. (defvar rst-font-lock-find-unindented-line-begin nil
  3278. "Beginning of the match if `rst-font-lock-find-unindented-line-end'.")
  3279. (defvar rst-font-lock-find-unindented-line-end nil
  3280. "End of the match as determined by `rst-font-lock-find-unindented-line-limit'.
  3281. Also used as a trigger for
  3282. `rst-font-lock-find-unindented-line-match'.")
  3283. (defun rst-font-lock-find-unindented-line-limit (ind-pnt)
  3284. "Find the next unindented line relative to indentation at IND-PNT.
  3285. Return this point, the end of the buffer or nil if nothing found.
  3286. If IND-PNT is `next' take the indentation from the next line if
  3287. this is not empty and indented more than the current one. If
  3288. IND-PNT is non-nil but not a number take the indentation from the
  3289. next non-empty line if this is indented more than the current
  3290. one."
  3291. (setq rst-font-lock-find-unindented-line-begin ind-pnt)
  3292. (setq rst-font-lock-find-unindented-line-end
  3293. (save-excursion
  3294. (when (not (numberp ind-pnt))
  3295. ;; Find indentation point in next line if any.
  3296. (setq ind-pnt
  3297. ;; FIXME: Should be refactored to two different functions
  3298. ;; giving their result to this function, may be
  3299. ;; integrated in caller.
  3300. (save-match-data
  3301. (let ((cur-ind (current-indentation)))
  3302. (if (eq ind-pnt 'next)
  3303. (when (and (zerop (forward-line 1))
  3304. (< (point) (point-max)))
  3305. ;; Not at EOF.
  3306. (setq rst-font-lock-find-unindented-line-begin
  3307. (point))
  3308. (when (and (not (looking-at (rst-re 'lin-end)))
  3309. (> (current-indentation) cur-ind))
  3310. ;; Use end of indentation if non-empty line.
  3311. (looking-at (rst-re 'hws-tag))
  3312. (match-end 0)))
  3313. ;; Skip until non-empty line or EOF.
  3314. (while (and (zerop (forward-line 1))
  3315. (< (point) (point-max))
  3316. (looking-at (rst-re 'lin-end))))
  3317. (when (< (point) (point-max))
  3318. ;; Not at EOF.
  3319. (setq rst-font-lock-find-unindented-line-begin
  3320. (point))
  3321. (when (> (current-indentation) cur-ind)
  3322. ;; Indentation bigger than line of departure.
  3323. (looking-at (rst-re 'hws-tag))
  3324. (match-end 0))))))))
  3325. (when ind-pnt
  3326. (goto-char ind-pnt)
  3327. (or (rst-forward-indented-block nil (point-max))
  3328. (point-max))))))
  3329. (defun rst-font-lock-find-unindented-line-match (limit)
  3330. "Set the match found earlier if match were found.
  3331. Match has been found by
  3332. `rst-font-lock-find-unindented-line-limit' the first time called
  3333. or no match is found. Return non-nil if match was found. LIMIT
  3334. is not used but mandated by the caller."
  3335. (when rst-font-lock-find-unindented-line-end
  3336. (set-match-data
  3337. (list rst-font-lock-find-unindented-line-begin
  3338. rst-font-lock-find-unindented-line-end))
  3339. (put-text-property rst-font-lock-find-unindented-line-begin
  3340. rst-font-lock-find-unindented-line-end
  3341. 'font-lock-multiline t)
  3342. ;; Make sure this is called only once.
  3343. (setq rst-font-lock-find-unindented-line-end nil)
  3344. t))
  3345. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  3346. ;; Adornments
  3347. (defvar rst-font-lock-adornment-level nil
  3348. "Storage for `rst-font-lock-handle-adornment-matcher'.
  3349. Either section level of the current adornment or t for a transition.")
  3350. (defun rst-adornment-level (key)
  3351. "Return section level for adornment KEY.
  3352. KEY is the first element of the return list of
  3353. `rst-classify-adornment'. If KEY is not a cons return it. If KEY is found
  3354. in the hierarchy return its level. Otherwise return a level one
  3355. beyond the existing hierarchy."
  3356. (if (not (consp key))
  3357. key
  3358. (let* ((hier (rst-get-hierarchy))
  3359. (char (car key))
  3360. (style (cdr key)))
  3361. (1+ (or (lexical-let ((char char)
  3362. (style style)
  3363. (hier hier)) ; Create closure.
  3364. (rst-position-if (lambda (elt)
  3365. (and (equal (car elt) char)
  3366. (equal (cadr elt) style))) hier))
  3367. (length hier))))))
  3368. (defvar rst-font-lock-adornment-match nil
  3369. "Storage for match for current adornment.
  3370. Set by `rst-font-lock-handle-adornment-pre-match-form'. Also used
  3371. as a trigger for `rst-font-lock-handle-adornment-matcher'.")
  3372. (defun rst-font-lock-handle-adornment-pre-match-form (ado ado-end)
  3373. "Determine limit for adornments.
  3374. Determine all things necessary for font-locking section titles
  3375. and transitions and put the result to
  3376. `rst-font-lock-adornment-match' and
  3377. `rst-font-lock-adornment-level'. ADO is the complete adornment
  3378. matched. ADO-END is the point where ADO ends. Return the point
  3379. where the whole adorned construct ends.
  3380. Called as a PRE-MATCH-FORM in the sense of `font-lock-keywords'."
  3381. (let ((ado-data (rst-classify-adornment ado ado-end)))
  3382. (if (not ado-data)
  3383. (setq rst-font-lock-adornment-level nil
  3384. rst-font-lock-adornment-match nil)
  3385. (setq rst-font-lock-adornment-level
  3386. (rst-adornment-level (car ado-data)))
  3387. (setq rst-font-lock-adornment-match (cdr ado-data))
  3388. (goto-char (nth 1 ado-data)) ; Beginning of construct.
  3389. (nth 2 ado-data)))) ; End of construct.
  3390. (defun rst-font-lock-handle-adornment-matcher (limit)
  3391. "Set the match found earlier if match were found.
  3392. Match has been found by
  3393. `rst-font-lock-handle-adornment-pre-match-form' the first time
  3394. called or no match is found. Return non-nil if match was found.
  3395. Called as a MATCHER in the sense of `font-lock-keywords'.
  3396. LIMIT is not used but mandated by the caller."
  3397. (let ((match rst-font-lock-adornment-match))
  3398. ;; May run only once - enforce this.
  3399. (setq rst-font-lock-adornment-match nil)
  3400. (when match
  3401. (set-match-data match)
  3402. (goto-char (match-end 0))
  3403. (put-text-property (match-beginning 0) (match-end 0)
  3404. 'font-lock-multiline t)
  3405. t)))
  3406. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  3407. ;; Compilation
  3408. (defgroup rst-compile nil
  3409. "Settings for support of conversion of reStructuredText
  3410. document with \\[rst-compile]."
  3411. :group 'rst
  3412. :version "21.1")
  3413. (defcustom rst-compile-toolsets
  3414. `((html ,(if (executable-find "rst2html.py") "rst2html.py" "rst2html")
  3415. ".html" nil)
  3416. (latex ,(if (executable-find "rst2latex.py") "rst2latex.py" "rst2latex")
  3417. ".tex" nil)
  3418. (newlatex ,(if (executable-find "rst2newlatex.py") "rst2newlatex.py"
  3419. "rst2newlatex")
  3420. ".tex" nil)
  3421. (pseudoxml ,(if (executable-find "rst2pseudoxml.py") "rst2pseudoxml.py"
  3422. "rst2pseudoxml")
  3423. ".xml" nil)
  3424. (xml ,(if (executable-find "rst2xml.py") "rst2xml.py" "rst2xml")
  3425. ".xml" nil)
  3426. (pdf ,(if (executable-find "rst2pdf.py") "rst2pdf.py" "rst2pdf")
  3427. ".pdf" nil)
  3428. (s5 ,(if (executable-find "rst2s5.py") "rst2s5.py" "rst2s5")
  3429. ".html" nil))
  3430. "Table describing the command to use for each tool-set.
  3431. An association list of the tool-set to a list of the (command to use,
  3432. extension of produced filename, options to the tool (nil or a
  3433. string)) to be used for converting the document."
  3434. ;; FIXME: These are not options but symbols which may be referenced by
  3435. ;; `rst-compile-*-toolset` below.
  3436. :type '(alist :options (html latex newlatex pseudoxml xml pdf s5)
  3437. :key-type symbol
  3438. :value-type (list :tag "Specification"
  3439. (file :tag "Command")
  3440. (string :tag "File extension")
  3441. (choice :tag "Command options"
  3442. (const :tag "No options" nil)
  3443. (string :tag "Options"))))
  3444. :group 'rst
  3445. :package-version "1.2.0")
  3446. ;; FIXME: Must be `defcustom`.
  3447. (defvar rst-compile-primary-toolset 'html
  3448. "The default tool-set for `rst-compile'.")
  3449. ;; FIXME: Must be `defcustom`.
  3450. (defvar rst-compile-secondary-toolset 'latex
  3451. "The default tool-set for `rst-compile' with a prefix argument.")
  3452. (defun rst-compile-find-conf ()
  3453. "Look for the configuration file in the parents of the current path."
  3454. (interactive)
  3455. (let ((file-name "docutils.conf")
  3456. (buffer-file (buffer-file-name)))
  3457. ;; Move up in the dir hierarchy till we find a change log file.
  3458. (let* ((dir (file-name-directory buffer-file))
  3459. (prevdir nil))
  3460. (while (and (or (not (string= dir prevdir))
  3461. (setq dir nil)
  3462. nil)
  3463. (not (file-exists-p (concat dir file-name))))
  3464. ;; Move up to the parent dir and try again.
  3465. (setq prevdir dir)
  3466. (setq dir (expand-file-name (file-name-directory
  3467. (directory-file-name
  3468. (file-name-directory dir)))))
  3469. )
  3470. (or (and dir (concat dir file-name)) nil)
  3471. )))
  3472. (require 'compile)
  3473. (defun rst-compile (&optional use-alt)
  3474. "Compile command to convert reST document into some output file.
  3475. Attempts to find configuration file, if it can, overrides the
  3476. options. There are two commands to choose from, with USE-ALT,
  3477. select the alternative tool-set."
  3478. (interactive "P")
  3479. ;; Note: maybe we want to check if there is a Makefile too and not do anything
  3480. ;; if that is the case. I dunno.
  3481. (let* ((toolset (cdr (assq (if use-alt
  3482. rst-compile-secondary-toolset
  3483. rst-compile-primary-toolset)
  3484. rst-compile-toolsets)))
  3485. (command (car toolset))
  3486. (extension (cadr toolset))
  3487. (options (caddr toolset))
  3488. (conffile (rst-compile-find-conf))
  3489. (bufname (file-name-nondirectory buffer-file-name))
  3490. (outname (file-name-sans-extension bufname)))
  3491. ;; Set compile-command before invocation of compile.
  3492. (set (make-local-variable 'compile-command)
  3493. (mapconcat 'identity
  3494. (list command
  3495. (or options "")
  3496. (if conffile
  3497. (concat "--config=" (shell-quote-argument conffile))
  3498. "")
  3499. (shell-quote-argument bufname)
  3500. (shell-quote-argument (concat outname extension)))
  3501. " "))
  3502. ;; Invoke the compile command.
  3503. (if (or compilation-read-command use-alt)
  3504. (call-interactively 'compile)
  3505. (compile compile-command))
  3506. ))
  3507. (defun rst-compile-alt-toolset ()
  3508. "Compile command with the alternative tool-set."
  3509. (interactive)
  3510. (rst-compile t))
  3511. (defun rst-compile-pseudo-region ()
  3512. "Show pseudo-XML rendering.
  3513. Rendering is done of the current active region, or of the entire
  3514. buffer, if the region is not selected."
  3515. ;; FIXME: The region should be given interactively.
  3516. (interactive)
  3517. (with-output-to-temp-buffer "*pseudoxml*"
  3518. (shell-command-on-region
  3519. (if mark-active (region-beginning) (point-min))
  3520. (if mark-active (region-end) (point-max))
  3521. (cadr (assq 'pseudoxml rst-compile-toolsets))
  3522. standard-output)))
  3523. ;; FIXME: Should be `defcustom`.
  3524. (defvar rst-pdf-program "xpdf"
  3525. "Program used to preview PDF files.")
  3526. (defun rst-compile-pdf-preview ()
  3527. "Convert the document to a PDF file and launch a preview program."
  3528. (interactive)
  3529. (let* ((tmp-filename (make-temp-file "rst_el" nil ".pdf"))
  3530. (command (format "%s %s %s && %s %s ; rm %s"
  3531. (cadr (assq 'pdf rst-compile-toolsets))
  3532. buffer-file-name tmp-filename
  3533. rst-pdf-program tmp-filename tmp-filename)))
  3534. (start-process-shell-command "rst-pdf-preview" nil command)
  3535. ;; Note: you could also use (compile command) to view the compilation
  3536. ;; output.
  3537. ))
  3538. ;; FIXME: Should be `defcustom` or use something like `browse-url`.
  3539. (defvar rst-slides-program "firefox"
  3540. "Program used to preview S5 slides.")
  3541. (defun rst-compile-slides-preview ()
  3542. "Convert the document to an S5 slide presentation and launch a preview program."
  3543. (interactive)
  3544. (let* ((tmp-filename (make-temp-file "rst_el" nil ".html"))
  3545. (command (format "%s %s %s && %s %s ; rm %s"
  3546. (cadr (assq 's5 rst-compile-toolsets))
  3547. buffer-file-name tmp-filename
  3548. rst-slides-program tmp-filename tmp-filename)))
  3549. (start-process-shell-command "rst-slides-preview" nil command)
  3550. ;; Note: you could also use (compile command) to view the compilation
  3551. ;; output.
  3552. ))
  3553. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  3554. ;; Generic text functions that are more convenient than the defaults.
  3555. ;; FIXME: Unbound command - should be bound or removed.
  3556. (defun rst-replace-lines (fromchar tochar)
  3557. "Replace flush-left lines of FROMCHAR with equal-length lines of TOCHAR."
  3558. (interactive "\
  3559. cSearch for flush-left lines of char:
  3560. cand replace with char: ")
  3561. (save-excursion
  3562. (let ((searchre (rst-re "^" fromchar "+\\( *\\)$"))
  3563. (found 0))
  3564. (while (search-forward-regexp searchre nil t)
  3565. (setq found (1+ found))
  3566. (goto-char (match-beginning 1))
  3567. (let ((width (current-column)))
  3568. (rst-delete-entire-line)
  3569. (insert-char tochar width)))
  3570. (message (format "%d lines replaced." found)))))
  3571. ;; FIXME: Unbound command - should be bound or removed.
  3572. (defun rst-join-paragraph ()
  3573. "Join lines in current paragraph into one line, removing end-of-lines."
  3574. (interactive)
  3575. (let ((fill-column 65000)) ; Some big number.
  3576. (call-interactively 'fill-paragraph)))
  3577. ;; FIXME: Unbound command - should be bound or removed.
  3578. (defun rst-force-fill-paragraph ()
  3579. "Fill paragraph at point, first joining the paragraph's lines into one.
  3580. This is useful for filling list item paragraphs."
  3581. (interactive)
  3582. (rst-join-paragraph)
  3583. (fill-paragraph nil))
  3584. ;; FIXME: Unbound command - should be bound or removed.
  3585. ;; Generic character repeater function.
  3586. ;; For sections, better to use the specialized function above, but this can
  3587. ;; be useful for creating separators.
  3588. (defun rst-repeat-last-character (use-next)
  3589. "Fill the current line using the last character on the current line.
  3590. Fill up to the length of the preceding line or up to
  3591. `fill-column' if preceding line is empty.
  3592. If USE-NEXT, use the next line rather than the preceding line.
  3593. If the current line is longer than the desired length, shave the characters off
  3594. the current line to fit the desired length.
  3595. As an added convenience, if the command is repeated immediately, the alternative
  3596. column is used (fill-column vs. end of previous/next line)."
  3597. (interactive "P")
  3598. (let* ((curcol (current-column))
  3599. (curline (+ (count-lines (point-min) (point))
  3600. (if (zerop curcol) 1 0)))
  3601. (lbp (line-beginning-position 0))
  3602. (prevcol (if (and (= curline 1) (not use-next))
  3603. fill-column
  3604. (save-excursion
  3605. (forward-line (if use-next 1 -1))
  3606. (end-of-line)
  3607. (skip-chars-backward " \t" lbp)
  3608. (let ((cc (current-column)))
  3609. (if (zerop cc) fill-column cc)))))
  3610. (rightmost-column
  3611. (cond ((equal last-command 'rst-repeat-last-character)
  3612. (if (= curcol fill-column) prevcol fill-column))
  3613. (t (save-excursion
  3614. (if (zerop prevcol) fill-column prevcol)))
  3615. )) )
  3616. (end-of-line)
  3617. (if (> (current-column) rightmost-column)
  3618. ;; Shave characters off the end.
  3619. (delete-region (- (point)
  3620. (- (current-column) rightmost-column))
  3621. (point))
  3622. ;; Fill with last characters.
  3623. (insert-char (preceding-char)
  3624. (- rightmost-column (current-column))))
  3625. ))
  3626. (defun rst-portable-mark-active-p ()
  3627. "Return non-nil if the mark is active.
  3628. This is a portable function."
  3629. (cond
  3630. ((fboundp 'region-active-p) (region-active-p))
  3631. ((boundp 'transient-mark-mode) (and transient-mark-mode mark-active))
  3632. (t mark-active)))
  3633. ;; LocalWords: docutils http sourceforge rst html wp svn svnroot txt reST regex
  3634. ;; LocalWords: regexes alist seq alt grp keymap abbrev overline overlines toc
  3635. ;; LocalWords: XML PNT propertized
  3636. ;; Local Variables:
  3637. ;; sentence-end-double-space: t
  3638. ;; End:
  3639. (provide 'rst)
  3640. ;;; rst.el ends here