rst.el 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486
  1. ;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
  2. ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
  3. ;; Authors: Martin Blais <blais@furius.ca>,
  4. ;; Stefan Merten <smerten@oekonux.de>,
  5. ;; David Goodger <goodger@python.org>
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; This package provides major mode rst-mode, which supports documents marked up
  19. ;; using the reStructuredText format. Support includes font locking as well as
  20. ;; some convenience functions for editing. It does this by defining a Emacs
  21. ;; major mode: rst-mode (ReST). This mode is derived from text-mode (and
  22. ;; inherits much of it). This package also contains:
  23. ;;
  24. ;; - Functions to automatically adjust and cycle the section underline
  25. ;; decorations;
  26. ;; - A mode that displays the table of contents and allows you to jump anywhere
  27. ;; from it;
  28. ;; - Functions to insert and automatically update a TOC in your source
  29. ;; document;
  30. ;; - Font-lock highlighting of notable reStructuredText structures;
  31. ;; - Some other convenience functions.
  32. ;;
  33. ;; See the accompanying document in the docutils documentation about
  34. ;; the contents of this package and how to use it.
  35. ;;
  36. ;; For more information about reStructuredText, see
  37. ;; http://docutils.sourceforge.net/rst.html
  38. ;;
  39. ;; For full details on how to use the contents of this file, see
  40. ;; http://docutils.sourceforge.net/docs/user/emacs.html
  41. ;;
  42. ;;
  43. ;; There are a number of convenient keybindings provided by rst-mode.
  44. ;; The main one is
  45. ;;
  46. ;; C-c C-a (also C-=): rst-adjust
  47. ;;
  48. ;; Updates or rotates the section title around point or promotes/demotes the
  49. ;; decorations within the region (see full details below). Note that C-= is a
  50. ;; good binding, since it allows you to specify a negative arg easily with C--
  51. ;; C-= (easy to type), as well as ordinary prefix arg with C-u C-=.
  52. ;;
  53. ;; For more on bindings, see rst-mode-map below. There are also many variables
  54. ;; that can be customized, look for defcustom and defvar in this file.
  55. ;;
  56. ;; If you use the table-of-contents feature, you may want to add a hook to
  57. ;; update the TOC automatically everytime you adjust a section title::
  58. ;;
  59. ;; (add-hook 'rst-adjust-hook 'rst-toc-update)
  60. ;;
  61. ;; Syntax highlighting: font-lock is enabled by default. If you want to turn
  62. ;; off syntax highlighting to rst-mode, you can use the following::
  63. ;;
  64. ;; (setq font-lock-global-modes '(not rst-mode ...))
  65. ;;
  66. ;; CUSTOMIZATION
  67. ;;
  68. ;; rst
  69. ;; ---
  70. ;; This group contains some general customizable features.
  71. ;;
  72. ;; The group is contained in the wp group.
  73. ;;
  74. ;; rst-faces
  75. ;; ---------
  76. ;; This group contains all necessary for customizing fonts. The default
  77. ;; settings use standard font-lock-*-face's so if you set these to your
  78. ;; liking they are probably good in rst-mode also.
  79. ;;
  80. ;; The group is contained in the faces group as well as in the rst group.
  81. ;;
  82. ;; rst-faces-defaults
  83. ;; ------------------
  84. ;; This group contains all necessary for customizing the default fonts used for
  85. ;; section title faces.
  86. ;;
  87. ;; The general idea for section title faces is to have a non-default background
  88. ;; but do not change the background. The section level is shown by the
  89. ;; lightness of the background color. If you like this general idea of
  90. ;; generating faces for section titles but do not like the details this group
  91. ;; is the point where you can customize the details. If you do not like the
  92. ;; general idea, however, you should customize the faces used in
  93. ;; rst-adornment-faces-alist.
  94. ;;
  95. ;; Note: If you are using a dark background please make sure the variable
  96. ;; frame-background-mode is set to the symbol dark. This triggers
  97. ;; some default values which are probably right for you.
  98. ;;
  99. ;; The group is contained in the rst-faces group.
  100. ;;
  101. ;; All customizable features have a comment explaining their meaning.
  102. ;; Refer to the customization of your Emacs (try ``M-x customize``).
  103. ;;; DOWNLOAD
  104. ;; The latest version of this file lies in the docutils source code repository:
  105. ;; http://svn.berlios.de/svnroot/repos/docutils/trunk/docutils/tools/editors/emacs/rst.el
  106. ;;; INSTALLATION
  107. ;; Add the following lines to your `.emacs' file:
  108. ;;
  109. ;; (require 'rst)
  110. ;;
  111. ;; If you are using `.txt' as a standard extension for reST files as
  112. ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
  113. ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
  114. ;; provides to set the major mode automatically. For instance you may use::
  115. ;;
  116. ;; .. -*- mode: rst -*-
  117. ;;
  118. ;; in the very first line of your file. The following code is useful if you
  119. ;; want automatically enter rst-mode from any file with compatible extensions:
  120. ;;
  121. ;; (setq auto-mode-alist
  122. ;; (append '(("\\.txt$" . rst-mode)
  123. ;; ("\\.rst$" . rst-mode)
  124. ;; ("\\.rest$" . rst-mode)) auto-mode-alist))
  125. ;;
  126. ;;; BUGS
  127. ;; - rst-enumeration-region: Select a single paragraph, with the top at one
  128. ;; blank line before the beginning, and it will fail.
  129. ;; - The active region goes away when we shift it left or right, and this
  130. ;; prevents us from refilling it automatically when shifting many times.
  131. ;; - The suggested decorations when adjusting should not have to cycle
  132. ;; below one below the last section decoration level preceding the
  133. ;; cursor. We need to fix that.
  134. ;;; TODO LIST
  135. ;; rst-toc-insert features
  136. ;; ------------------------
  137. ;; - rst-toc-insert: We should parse the contents:: options to figure out how
  138. ;; deep to render the inserted TOC.
  139. ;; - On load, detect any existing TOCs and set the properties for links.
  140. ;; - TOC insertion should have an option to add empty lines.
  141. ;; - TOC insertion should deal with multiple lines.
  142. ;; - There is a bug on redo after undo of adjust when rst-adjust-hook uses the
  143. ;; automatic toc update. The cursor ends up in the TOC and this is
  144. ;; annoying. Gotta fix that.
  145. ;; - numbering: automatically detect if we have a section-numbering directive in
  146. ;; the corresponding section, to render the toc.
  147. ;;
  148. ;; bulleted and enumerated list items
  149. ;; ----------------------------------
  150. ;; - We need to provide way to rebullet bulleted lists, and that would include
  151. ;; automatic enumeration as well.
  152. ;;
  153. ;; Other
  154. ;; -----
  155. ;; - It would be nice to differentiate between text files using
  156. ;; reStructuredText_ and other general text files. If we had a
  157. ;; function to automatically guess whether a .txt file is following the
  158. ;; reStructuredText_ conventions, we could trigger rst-mode without
  159. ;; having to hard-code this in every text file, nor forcing the user to
  160. ;; add a local mode variable at the top of the file.
  161. ;; We could perform this guessing by searching for a valid decoration
  162. ;; at the top of the document or searching for reStructuredText_
  163. ;; directives further on.
  164. ;;
  165. ;; - We should support imenu in our major mode, with the menu filled with the
  166. ;; section titles (this should be really easy).
  167. ;;
  168. ;; - We should rename "adornment" to "decoration" or vice-versa in this
  169. ;; document (Stefan's code ("adornment") vs Martin ("decoration")), maybe some
  170. ;; functions even overlap.
  171. ;;
  172. ;; - We need to automatically recenter on rst-forward-section movement commands.
  173. ;;; HISTORY
  174. ;;
  175. ;;; Code:
  176. (defgroup rst nil "Support for reStructuredText documents."
  177. :group 'wp
  178. :version "23.1"
  179. :link '(url-link "http://docutils.sourceforge.net/rst.html"))
  180. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  181. ;; Define some generic support functions.
  182. (eval-when-compile (require 'cl)) ;; We need this for destructuring-bind below.
  183. ;; From Emacs-22
  184. (unless (fboundp 'line-number-at-pos)
  185. (defun line-number-at-pos (&optional pos)
  186. "Return (narrowed) buffer line number at position POS.
  187. If POS is nil, use current buffer location."
  188. (let ((opoint (or pos (point))) start)
  189. (save-excursion
  190. (goto-char (point-min))
  191. (setq start (point))
  192. (goto-char opoint)
  193. (forward-line 0)
  194. (1+ (count-lines start (point)))))) )
  195. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  196. ;; Mode definition.
  197. ;; Key bindings.
  198. (defvar rst-mode-map
  199. (let ((map (make-sparse-keymap)))
  200. ;;
  201. ;; Section Decorations.
  202. ;;
  203. ;; The adjustment function that decorates or rotates a section title.
  204. (define-key map [(control c) (control a)] 'rst-adjust)
  205. (define-key map [(control c) (control ?=)] 'rst-adjust)
  206. (define-key map [(control ?=)] 'rst-adjust) ;; (Does not work on the Mac OSX.)
  207. ;; Display the hierarchy of decorations implied by the current document contents.
  208. (define-key map [(control c) (control h)] 'rst-display-decorations-hierarchy)
  209. ;; Homogenize the decorations in the document.
  210. (define-key map [(control c) (control s)] 'rst-straighten-decorations)
  211. ;; (define-key map [(control c) (control s)] 'rst-straighten-deco-spacing)
  212. ;;
  213. ;; Section Movement and Selection.
  214. ;;
  215. ;; Mark the subsection where the cursor is.
  216. (define-key map [(control c) (control m)] 'rst-mark-section)
  217. ;; Move forward/backward between section titles.
  218. (define-key map [(control c) (control n)] 'rst-forward-section)
  219. (define-key map [(control c) (control p)] 'rst-backward-section)
  220. ;;
  221. ;; Operating on Blocks of Text.
  222. ;;
  223. ;; Makes paragraphs in region as a bullet list.
  224. (define-key map [(control c) (control b)] 'rst-bullet-list-region)
  225. ;; Makes paragraphs in region as a enumeration.
  226. (define-key map [(control c) (control e)] 'rst-enumerate-region)
  227. ;; Converts bullets to an enumeration.
  228. (define-key map [(control c) (control v)] 'rst-convert-bullets-to-enumeration)
  229. ;; Makes region a line-block.
  230. (define-key map [(control c) (control d)] 'rst-line-block-region)
  231. ;; Make sure that all the bullets in the region are consistent.
  232. (define-key map [(control c) (control w)] 'rst-straighten-bullets-region)
  233. ;; Shift region left or right (taking into account of enumerations/bullets, etc.).
  234. (define-key map [(control c) (control l)] 'rst-shift-region-left)
  235. (define-key map [(control c) (control r)] 'rst-shift-region-right)
  236. ;; Comment/uncomment the active region.
  237. (define-key map [(control c) (control c)] 'comment-region)
  238. ;;
  239. ;; Table-of-Contents Features.
  240. ;;
  241. ;; Enter a TOC buffer to view and move to a specific section.
  242. (define-key map [(control c) (control t)] 'rst-toc)
  243. ;; Insert a TOC here.
  244. (define-key map [(control c) (control i)] 'rst-toc-insert)
  245. ;; Update the document's TOC (without changing the cursor position).
  246. (define-key map [(control c) (control u)] 'rst-toc-update)
  247. ;; Got to the section under the cursor (cursor must be in TOC).
  248. (define-key map [(control c) (control f)] 'rst-goto-section)
  249. ;;
  250. ;; Converting Documents from Emacs.
  251. ;;
  252. ;; Run one of two pre-configured toolset commands on the document.
  253. (define-key map [(control c) (?1)] 'rst-compile)
  254. (define-key map [(control c) (?2)] 'rst-compile-alt-toolset)
  255. ;; Convert the active region to pseudo-xml using the docutils tools.
  256. (define-key map [(control c) (?3)] 'rst-compile-pseudo-region)
  257. ;; Convert the current document to PDF and launch a viewer on the results.
  258. (define-key map [(control c) (?4)] 'rst-compile-pdf-preview)
  259. ;; Convert the current document to S5 slides and view in a web browser.
  260. (define-key map [(control c) (?5)] 'rst-compile-slides-preview)
  261. map)
  262. "Keymap for reStructuredText mode commands.
  263. This inherits from Text mode.")
  264. ;; Abbrevs.
  265. (defvar rst-mode-abbrev-table nil
  266. "Abbrev table used while in Rst mode.")
  267. (define-abbrev-table 'rst-mode-abbrev-table
  268. (mapcar (lambda (x) (append x '(nil 0 system)))
  269. '(("contents" ".. contents::\n..\n ")
  270. ("con" ".. contents::\n..\n ")
  271. ("cont" "[...]")
  272. ("skip" "\n\n[...]\n\n ")
  273. ("seq" "\n\n[...]\n\n ")
  274. ;; FIXME: Add footnotes, links, and more.
  275. )))
  276. ;; Syntax table.
  277. (defvar rst-mode-syntax-table
  278. (let ((st (copy-syntax-table text-mode-syntax-table)))
  279. (modify-syntax-entry ?$ "." st)
  280. (modify-syntax-entry ?% "." st)
  281. (modify-syntax-entry ?& "." st)
  282. (modify-syntax-entry ?' "." st)
  283. (modify-syntax-entry ?* "." st)
  284. (modify-syntax-entry ?+ "." st)
  285. (modify-syntax-entry ?. "_" st)
  286. (modify-syntax-entry ?/ "." st)
  287. (modify-syntax-entry ?< "." st)
  288. (modify-syntax-entry ?= "." st)
  289. (modify-syntax-entry ?> "." st)
  290. (modify-syntax-entry ?\\ "\\" st)
  291. (modify-syntax-entry ?| "." st)
  292. (modify-syntax-entry ?_ "." st)
  293. st)
  294. "Syntax table used while in `rst-mode'.")
  295. (defcustom rst-mode-hook nil
  296. "Hook run when Rst mode is turned on.
  297. The hook for Text mode is run before this one."
  298. :group 'rst
  299. :type '(hook))
  300. (defcustom rst-mode-lazy t
  301. "If non-nil Rst mode tries to font-lock multi-line elements correctly.
  302. Because this is really slow it should be set to nil if neither `jit-lock-mode'
  303. not `lazy-lock-mode' and activated.
  304. If nil, comments and literal blocks are font-locked only on the line they start.
  305. The value of this variable is used when Rst mode is turned on."
  306. :group 'rst
  307. :type '(boolean))
  308. ;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files
  309. ;; use *.txt, but this is too generic to be set as a default.
  310. ;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode)))
  311. ;;;###autoload
  312. (define-derived-mode rst-mode text-mode "ReST"
  313. "Major mode for editing reStructuredText documents.
  314. \\<rst-mode-map>
  315. There are a number of convenient keybindings provided by
  316. Rst mode. The main one is \\[rst-adjust], it updates or rotates
  317. the section title around point or promotes/demotes the
  318. decorations within the region (see full details below).
  319. Use negative prefix arg to rotate in the other direction.
  320. Turning on `rst-mode' calls the normal hooks `text-mode-hook'
  321. and `rst-mode-hook'. This mode also supports font-lock
  322. highlighting. You may customize `rst-mode-lazy' to toggle
  323. font-locking of blocks.
  324. \\{rst-mode-map}"
  325. :abbrev-table rst-mode-abbrev-table
  326. :syntax-table rst-mode-syntax-table
  327. :group 'rst
  328. (set (make-local-variable 'paragraph-separate) paragraph-start)
  329. (set (make-local-variable 'indent-line-function) 'indent-relative-maybe)
  330. (set (make-local-variable 'paragraph-start)
  331. "\f\\|>*[ \t]*$\\|>*[ \t]*[-+*] \\|>*[ \t]*[0-9#]+\\. ")
  332. (set (make-local-variable 'adaptive-fill-mode) t)
  333. ;; FIXME: No need to reset this.
  334. ;; (set (make-local-variable 'indent-line-function) 'indent-relative)
  335. ;; The details of the following comment setup is important because it affects
  336. ;; auto-fill, and it is pretty common in running text to have an ellipsis
  337. ;; ("...") which trips because of the rest comment syntax (".. ").
  338. (set (make-local-variable 'comment-start) ".. ")
  339. (set (make-local-variable 'comment-start-skip) "^\\.\\. ")
  340. (set (make-local-variable 'comment-multi-line) nil)
  341. ;; Special variables
  342. (make-local-variable 'rst-adornment-level-alist)
  343. ;; Font lock
  344. (set (make-local-variable 'font-lock-defaults)
  345. '(rst-font-lock-keywords-function
  346. t nil nil nil
  347. (font-lock-mark-block-function . mark-paragraph)))
  348. ;; `jit-lock-mode' has been the default since Emacs-21.1, so there's no
  349. ;; point messing around with font-lock-support-mode any more.
  350. ;; (when (boundp 'font-lock-support-mode)
  351. ;; ;; rst-mode has its own mind about font-lock-support-mode
  352. ;; (make-local-variable 'font-lock-support-mode)
  353. ;; ;; jit-lock-mode replaced lazy-lock-mode in GNU Emacs 21.
  354. ;; (let ((jit-or-lazy-lock-mode
  355. ;; (cond
  356. ;; ((fboundp 'lazy-lock-mode) 'lazy-lock-mode)
  357. ;; ((fboundp 'jit-lock-mode) 'jit-lock-mode)
  358. ;; ;; if neither lazy-lock nor jit-lock is supported,
  359. ;; ;; tell user and disable rst-mode-lazy
  360. ;; (t (when rst-mode-lazy
  361. ;; (message "Disabled lazy fontification, because no known support mode found.")
  362. ;; (setq rst-mode-lazy nil))))))
  363. ;; (cond
  364. ;; ((and (not rst-mode-lazy) (not font-lock-support-mode)))
  365. ;; ;; No support mode set and none required - leave it alone
  366. ;; ((or (not font-lock-support-mode) ;; No support mode set (but required)
  367. ;; (symbolp font-lock-support-mode)) ;; or a fixed mode for all
  368. ;; (setq font-lock-support-mode
  369. ;; (list (cons 'rst-mode (and rst-mode-lazy jit-or-lazy-lock-mode))
  370. ;; (cons t font-lock-support-mode))))
  371. ;; ((and (listp font-lock-support-mode)
  372. ;; (not (assoc 'rst-mode font-lock-support-mode)))
  373. ;; ;; A list of modes missing rst-mode
  374. ;; (setq font-lock-support-mode
  375. ;; (cons (cons 'rst-mode (and rst-mode-lazy jit-or-lazy-lock-mode))
  376. ;; font-lock-support-mode))))))
  377. )
  378. ;;;###autoload
  379. (define-minor-mode rst-minor-mode
  380. "Toggle ReST minor mode.
  381. With a prefix argument ARG, enable ReST minor mode if ARG is
  382. positive, and disable it otherwise. If called from Lisp, enable
  383. the mode if ARG is omitted or nil.
  384. When ReST minor mode is enabled, the ReST mode keybindings
  385. are installed on top of the major mode bindings. Use this
  386. for modes derived from Text mode, like Mail mode."
  387. ;; The initial value.
  388. nil
  389. ;; The indicator for the mode line.
  390. " ReST"
  391. ;; The minor mode bindings.
  392. rst-mode-map
  393. :group 'rst)
  394. ;; FIXME: can I somehow install these too?
  395. ;; :abbrev-table rst-mode-abbrev-table
  396. ;; :syntax-table rst-mode-syntax-table
  397. ;; Bulleted item lists.
  398. (defcustom rst-bullets
  399. '(?- ?* ?+)
  400. "List of all possible bullet characters for bulleted lists."
  401. :group 'rst)
  402. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  403. ;; Section Decoration Adjustment
  404. ;; =============================
  405. ;;
  406. ;; The following functions implement a smart automatic title sectioning feature.
  407. ;; The idea is that with the cursor sitting on a section title, we try to get as
  408. ;; much information from context and try to do the best thing automatically.
  409. ;; This function can be invoked many times and/or with prefix argument to rotate
  410. ;; between the various sectioning decorations.
  411. ;;
  412. ;; Definitions: the two forms of sectioning define semantically separate section
  413. ;; levels. A sectioning DECORATION consists in:
  414. ;;
  415. ;; - a CHARACTER
  416. ;;
  417. ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
  418. ;;
  419. ;; - an INDENT (meaningful for the over-and-under style only) which determines
  420. ;; how many characters and over-and-under style is hanging outside of the
  421. ;; title at the beginning and ending.
  422. ;;
  423. ;; Important note: an existing decoration must be formed by at least two
  424. ;; characters to be recognized.
  425. ;;
  426. ;; Here are two examples of decorations (| represents the window border, column
  427. ;; 0):
  428. ;;
  429. ;; |
  430. ;; 1. char: '-' e |Some Title
  431. ;; style: simple |----------
  432. ;; |
  433. ;; 2. char: '=' |==============
  434. ;; style: over-and-under | Some Title
  435. ;; indent: 2 |==============
  436. ;; |
  437. ;;
  438. ;; Some notes:
  439. ;;
  440. ;; - The underlining character that is used depends on context. The file is
  441. ;; scanned to find other sections and an appropriate character is selected.
  442. ;; If the function is invoked on a section that is complete, the character is
  443. ;; rotated among the existing section decorations.
  444. ;;
  445. ;; Note that when rotating the characters, if we come to the end of the
  446. ;; hierarchy of decorations, the variable rst-preferred-decorations is
  447. ;; consulted to propose a new underline decoration, and if continued, we cycle
  448. ;; the decorations all over again. Set this variable to nil if you want to
  449. ;; limit the underlining character propositions to the existing decorations in
  450. ;; the file.
  451. ;;
  452. ;; - A prefix argument can be used to alternate the style.
  453. ;;
  454. ;; - An underline/overline that is not extended to the column at which it should
  455. ;; be hanging is dubbed INCOMPLETE. For example::
  456. ;;
  457. ;; |Some Title
  458. ;; |-------
  459. ;;
  460. ;; Examples of default invocation:
  461. ;;
  462. ;; |Some Title ---> |Some Title
  463. ;; | |----------
  464. ;;
  465. ;; |Some Title ---> |Some Title
  466. ;; |----- |----------
  467. ;;
  468. ;; | |------------
  469. ;; | Some Title ---> | Some Title
  470. ;; | |------------
  471. ;;
  472. ;; In over-and-under style, when alternating the style, a variable is
  473. ;; available to select how much default indent to use (it can be zero). Note
  474. ;; that if the current section decoration already has an indent, we don't
  475. ;; adjust it to the default, we rather use the current indent that is already
  476. ;; there for adjustment (unless we cycle, in which case we use the indent
  477. ;; that has been found previously).
  478. (defgroup rst-adjust nil
  479. "Settings for adjustment and cycling of section title decorations."
  480. :group 'rst
  481. :version "21.1")
  482. (defcustom rst-preferred-decorations '( (?= over-and-under 1)
  483. (?= simple 0)
  484. (?- simple 0)
  485. (?~ simple 0)
  486. (?+ simple 0)
  487. (?` simple 0)
  488. (?# simple 0)
  489. (?@ simple 0) )
  490. "Preferred ordering of section title decorations.
  491. This sequence is consulted to offer a new decoration suggestion
  492. when we rotate the underlines at the end of the existing
  493. hierarchy of characters, or when there is no existing section
  494. title in the file."
  495. :group 'rst-adjust)
  496. (defcustom rst-default-indent 1
  497. "Number of characters to indent the section title.
  498. This is used for when toggling decoration styles, when switching
  499. from a simple decoration style to a over-and-under decoration
  500. style."
  501. :group 'rst-adjust)
  502. (defvar rst-section-text-regexp "^[ \t]*\\S-*\\w\\S-*"
  503. "Regular expression for valid section title text.")
  504. (defun rst-line-homogeneous-p (&optional accept-special)
  505. "Return true if the line is homogeneous.
  506. Predicate that returns the unique char if the current line is
  507. composed only of a single repeated non-whitespace character.
  508. This returns the char even if there is whitespace at the
  509. beginning of the line.
  510. If ACCEPT-SPECIAL is specified we do not ignore special sequences
  511. which normally we would ignore when doing a search on many lines.
  512. For example, normally we have cases to ignore commonly occurring
  513. patterns, such as :: or ...; with the flag do not ignore them."
  514. (save-excursion
  515. (back-to-indentation)
  516. (unless (looking-at "\n")
  517. (let ((c (thing-at-point 'char)))
  518. (if (and (looking-at (format "[%s]+[ \t]*$" c))
  519. (or accept-special
  520. (and
  521. ;; Common patterns.
  522. (not (looking-at "::[ \t]*$"))
  523. (not (looking-at "\\.\\.\\.[ \t]*$"))
  524. ;; Discard one char line
  525. (not (looking-at ".[ \t]*$"))
  526. )))
  527. (string-to-char c))
  528. ))
  529. ))
  530. (defun rst-line-homogeneous-nodent-p (&optional accept-special)
  531. "Return true if the line is homogeneous with no indent.
  532. See `rst-line-homogeneous-p' about ACCEPT-SPECIAL."
  533. (save-excursion
  534. (beginning-of-line)
  535. (if (looking-at "^[ \t]+")
  536. nil
  537. (rst-line-homogeneous-p accept-special)
  538. )))
  539. (defun rst-compare-decorations (deco1 deco2)
  540. "Compare decorations.
  541. Return true if both DECO1 and DECO2 decorations are equal,
  542. according to restructured text semantics (only the character and
  543. the style are compared, the indentation does not matter)."
  544. (and (eq (car deco1) (car deco2))
  545. (eq (cadr deco1) (cadr deco2))))
  546. (defun rst-get-decoration-match (hier deco)
  547. "Return the index (level) in hierarchy HIER of decoration DECO.
  548. This basically just searches for the item using the appropriate
  549. comparison and returns the index. Return nil if the item is
  550. not found."
  551. (let ((cur hier))
  552. (while (and cur (not (rst-compare-decorations (car cur) deco)))
  553. (setq cur (cdr cur)))
  554. cur))
  555. (defun rst-suggest-new-decoration (alldecos &optional prev)
  556. "Suggest a new, different decoration from all that have been seen.
  557. ALLDECOS is the set of all decorations, including the line numbers.
  558. PREV is the optional previous decoration, in order to suggest a
  559. better match."
  560. ;; For all the preferred decorations...
  561. (let* (
  562. ;; If 'prev' is given, reorder the list to start searching after the
  563. ;; match.
  564. (fplist
  565. (cdr (rst-get-decoration-match rst-preferred-decorations prev)))
  566. ;; List of candidates to search.
  567. (curpotential (append fplist rst-preferred-decorations)))
  568. (while
  569. ;; For all the decorations...
  570. (let ((cur alldecos)
  571. found)
  572. (while (and cur (not found))
  573. (if (rst-compare-decorations (car cur) (car curpotential))
  574. ;; Found it!
  575. (setq found (car curpotential))
  576. (setq cur (cdr cur))))
  577. found)
  578. (setq curpotential (cdr curpotential)))
  579. (copy-sequence (car curpotential))))
  580. (defun rst-delete-entire-line ()
  581. "Delete the entire current line without using the `kill-ring'."
  582. (delete-region (line-beginning-position)
  583. (line-beginning-position 2)))
  584. (defun rst-update-section (char style &optional indent)
  585. "Unconditionally update the style of a section decoration.
  586. Do this using the given character CHAR, with STYLE 'simple
  587. or 'over-and-under, and with indent INDENT. If the STYLE
  588. is 'simple, whitespace before the title is removed (indent
  589. is always assumed to be 0).
  590. If there are existing overline and/or underline from the
  591. existing decoration, they are removed before adding the
  592. requested decoration."
  593. (interactive)
  594. (end-of-line)
  595. (let ((marker (point-marker))
  596. len)
  597. ;; Fixup whitespace at the beginning and end of the line
  598. (if (or (null indent) (eq style 'simple))
  599. (setq indent 0))
  600. (beginning-of-line)
  601. (delete-horizontal-space)
  602. (insert (make-string indent ? ))
  603. (end-of-line)
  604. (delete-horizontal-space)
  605. ;; Set the current column, we're at the end of the title line
  606. (setq len (+ (current-column) indent))
  607. ;; Remove previous line if it consists only of a single repeated character
  608. (save-excursion
  609. (forward-line -1)
  610. (and (rst-line-homogeneous-p 1)
  611. ;; Avoid removing the underline of a title right above us.
  612. (save-excursion (forward-line -1)
  613. (not (looking-at rst-section-text-regexp)))
  614. (rst-delete-entire-line)))
  615. ;; Remove following line if it consists only of a single repeated
  616. ;; character
  617. (save-excursion
  618. (forward-line +1)
  619. (and (rst-line-homogeneous-p 1)
  620. (rst-delete-entire-line))
  621. ;; Add a newline if we're at the end of the buffer, for the subsequence
  622. ;; inserting of the underline
  623. (if (= (point) (buffer-end 1))
  624. (newline 1)))
  625. ;; Insert overline
  626. (if (eq style 'over-and-under)
  627. (save-excursion
  628. (beginning-of-line)
  629. (open-line 1)
  630. (insert (make-string len char))))
  631. ;; Insert underline
  632. (forward-line +1)
  633. (open-line 1)
  634. (insert (make-string len char))
  635. (forward-line +1)
  636. (goto-char marker)
  637. ))
  638. (defun rst-normalize-cursor-position ()
  639. "Normalize the cursor position.
  640. If the cursor is on a decoration line or an empty line , place it
  641. on the section title line (at the end). Returns the line offset
  642. by which the cursor was moved. This works both over or under a
  643. line."
  644. (if (save-excursion (beginning-of-line)
  645. (or (rst-line-homogeneous-p 1)
  646. (looking-at "^[ \t]*$")))
  647. (progn
  648. (beginning-of-line)
  649. (cond
  650. ((save-excursion (forward-line -1)
  651. (beginning-of-line)
  652. (and (looking-at rst-section-text-regexp)
  653. (not (rst-line-homogeneous-p 1))))
  654. (progn (forward-line -1) -1))
  655. ((save-excursion (forward-line +1)
  656. (beginning-of-line)
  657. (and (looking-at rst-section-text-regexp)
  658. (not (rst-line-homogeneous-p 1))))
  659. (progn (forward-line +1) +1))
  660. (t 0)))
  661. 0 ))
  662. (defun rst-find-all-decorations ()
  663. "Find all the decorations in the file.
  664. Return a list of (line, decoration) pairs. Each decoration
  665. consists in a (char, style, indent) triple.
  666. This function does not detect the hierarchy of decorations, it
  667. just finds all of them in a file. You can then invoke another
  668. function to remove redundancies and inconsistencies."
  669. (let ((positions ())
  670. (curline 1))
  671. ;; Iterate over all the section titles/decorations in the file.
  672. (save-excursion
  673. (goto-char (point-min))
  674. (while (< (point) (buffer-end 1))
  675. (if (rst-line-homogeneous-nodent-p)
  676. (progn
  677. (setq curline (+ curline (rst-normalize-cursor-position)))
  678. ;; Here we have found a potential site for a decoration,
  679. ;; characterize it.
  680. (let ((deco (rst-get-decoration)))
  681. (if (cadr deco) ;; Style is existing.
  682. ;; Found a real decoration site.
  683. (progn
  684. (push (cons curline deco) positions)
  685. ;; Push beyond the underline.
  686. (forward-line 1)
  687. (setq curline (+ curline 1))
  688. )))
  689. ))
  690. (forward-line 1)
  691. (setq curline (+ curline 1))
  692. ))
  693. (reverse positions)))
  694. (defun rst-infer-hierarchy (decorations)
  695. "Build a hierarchy of decorations using the list of given DECORATIONS.
  696. This function expects a list of (char, style, indent) decoration
  697. specifications, in order that they appear in a file, and will
  698. infer a hierarchy of section levels by removing decorations that
  699. have already been seen in a forward traversal of the decorations,
  700. comparing just the character and style.
  701. Similarly returns a list of (char, style, indent), where each
  702. list element should be unique."
  703. (let ((hierarchy-alist (list)))
  704. (dolist (x decorations)
  705. (let ((char (car x))
  706. (style (cadr x)))
  707. (unless (assoc (cons char style) hierarchy-alist)
  708. (push (cons (cons char style) x) hierarchy-alist))
  709. ))
  710. (mapcar 'cdr (nreverse hierarchy-alist))
  711. ))
  712. (defun rst-get-hierarchy (&optional alldecos ignore)
  713. "Return the hierarchy of section titles in the file.
  714. Return a list of decorations that represents the hierarchy of
  715. section titles in the file. Reuse the list of decorations
  716. already computed in ALLDECOS if present. If the line number in
  717. IGNORE is specified, the decoration found on that line (if there
  718. is one) is not taken into account when building the hierarchy."
  719. (let ((all (or alldecos (rst-find-all-decorations))))
  720. (setq all (assq-delete-all ignore all))
  721. (rst-infer-hierarchy (mapcar 'cdr all))))
  722. (defun rst-get-decoration (&optional point)
  723. "Get the decoration at POINT.
  724. Looks around point and finds the characteristics of the
  725. decoration that is found there. Assumes that the cursor is
  726. already placed on the title line (and not on the overline or
  727. underline).
  728. This function returns a (char, style, indent) triple. If the
  729. characters of overline and underline are different, return
  730. the underline character. The indent is always calculated.
  731. A decoration can be said to exist if the style is not nil.
  732. A point can be specified to go to the given location before
  733. extracting the decoration."
  734. (let (char style)
  735. (save-excursion
  736. (if point (goto-char point))
  737. (beginning-of-line)
  738. (if (looking-at rst-section-text-regexp)
  739. (let* ((over (save-excursion
  740. (forward-line -1)
  741. (rst-line-homogeneous-nodent-p)))
  742. (under (save-excursion
  743. (forward-line +1)
  744. (rst-line-homogeneous-nodent-p)))
  745. )
  746. ;; Check that the line above the overline is not part of a title
  747. ;; above it.
  748. (if (and over
  749. (save-excursion
  750. (and (equal (forward-line -2) 0)
  751. (looking-at rst-section-text-regexp))))
  752. (setq over nil))
  753. (cond
  754. ;; No decoration found, leave all return values nil.
  755. ((and (eq over nil) (eq under nil)))
  756. ;; Overline only, leave all return values nil.
  757. ;;
  758. ;; Note: we don't return the overline character, but it could
  759. ;; perhaps in some cases be used to do something.
  760. ((and over (eq under nil)))
  761. ;; Underline only.
  762. ((and under (eq over nil))
  763. (setq char under
  764. style 'simple))
  765. ;; Both overline and underline.
  766. (t
  767. (setq char under
  768. style 'over-and-under)))))
  769. ;; Return values.
  770. (list char style
  771. ;; Find indentation.
  772. (save-excursion (back-to-indentation) (current-column))))))
  773. (defun rst-get-decorations-around (&optional alldecos)
  774. "Return the decorations around point.
  775. Given the list of all decorations ALLDECOS (with positions),
  776. find the decorations before and after the given point.
  777. A list of the previous and next decorations is returned."
  778. (let* ((all (or alldecos (rst-find-all-decorations)))
  779. (curline (line-number-at-pos))
  780. prev next
  781. (cur all))
  782. ;; Search for the decorations around the current line.
  783. (while (and cur (< (caar cur) curline))
  784. (setq prev cur
  785. cur (cdr cur)))
  786. ;; 'cur' is the following decoration.
  787. (if (and cur (caar cur))
  788. (setq next (if (= curline (caar cur)) (cdr cur) cur)))
  789. (mapcar 'cdar (list prev next))
  790. ))
  791. (defun rst-decoration-complete-p (deco)
  792. "Return true if the decoration DECO around point is complete."
  793. ;; Note: we assume that the detection of the overline as being the underline
  794. ;; of a preceding title has already been detected, and has been eliminated
  795. ;; from the decoration that is given to us.
  796. ;; There is some sectioning already present, so check if the current
  797. ;; sectioning is complete and correct.
  798. (let* ((char (car deco))
  799. (style (cadr deco))
  800. (indent (caddr deco))
  801. (endcol (save-excursion (end-of-line) (current-column)))
  802. )
  803. (if char
  804. (let ((exps (concat "^"
  805. (regexp-quote (make-string (+ endcol indent) char))
  806. "$")))
  807. (and
  808. (save-excursion (forward-line +1)
  809. (beginning-of-line)
  810. (looking-at exps))
  811. (or (not (eq style 'over-and-under))
  812. (save-excursion (forward-line -1)
  813. (beginning-of-line)
  814. (looking-at exps))))
  815. ))
  816. ))
  817. (defun rst-get-next-decoration
  818. (curdeco hier &optional suggestion reverse-direction)
  819. "Get the next decoration for CURDECO, in given hierarchy HIER.
  820. If suggesting, suggest for new decoration SUGGESTION.
  821. REVERSE-DIRECTION is used to reverse the cycling order."
  822. (let* (
  823. (char (car curdeco))
  824. (style (cadr curdeco))
  825. ;; Build a new list of decorations for the rotation.
  826. (rotdecos
  827. (append hier
  828. ;; Suggest a new decoration.
  829. (list suggestion
  830. ;; If nothing to suggest, use first decoration.
  831. (car hier)))) )
  832. (or
  833. ;; Search for next decoration.
  834. (cadr
  835. (let ((cur (if reverse-direction rotdecos
  836. (reverse rotdecos))))
  837. (while (and cur
  838. (not (and (eq char (caar cur))
  839. (eq style (cadar cur)))))
  840. (setq cur (cdr cur)))
  841. cur))
  842. ;; If not found, take the first of all decorations.
  843. suggestion
  844. )))
  845. (defun rst-adjust ()
  846. "Auto-adjust the decoration around point.
  847. Adjust/rotate the section decoration for the section title
  848. around point or promote/demote the decorations inside the region,
  849. depending on if the region is active. This function is meant to
  850. be invoked possibly multiple times, and can vary its behavior
  851. with a positive prefix argument (toggle style), or with a
  852. negative prefix argument (alternate behavior).
  853. This function is the main focus of this module and is a bit of a
  854. swiss knife. It is meant as the single most essential function
  855. to be bound to invoke to adjust the decorations of a section
  856. title in restructuredtext. It tries to deal with all the
  857. possible cases gracefully and to do `the right thing' in all
  858. cases.
  859. See the documentations of `rst-adjust-decoration' and
  860. `rst-promote-region' for full details.
  861. Prefix Arguments
  862. ================
  863. The method can take either (but not both) of
  864. a. a (non-negative) prefix argument, which means to toggle the
  865. decoration style. Invoke with a prefix arg for example;
  866. b. a negative numerical argument, which generally inverts the
  867. direction of search in the file or hierarchy. Invoke with C--
  868. prefix for example."
  869. (interactive)
  870. (let* (;; Save our original position on the current line.
  871. (origpt (point-marker))
  872. ;; Parse the positive and negative prefix arguments.
  873. (reverse-direction
  874. (and current-prefix-arg
  875. (< (prefix-numeric-value current-prefix-arg) 0)))
  876. (toggle-style
  877. (and current-prefix-arg (not reverse-direction))))
  878. (if (rst-portable-mark-active-p)
  879. ;; Adjust decorations within region.
  880. (rst-promote-region current-prefix-arg)
  881. ;; Adjust decoration around point.
  882. (rst-adjust-decoration toggle-style reverse-direction))
  883. ;; Run the hooks to run after adjusting.
  884. (run-hooks 'rst-adjust-hook)
  885. ;; Make sure to reset the cursor position properly after we're done.
  886. (goto-char origpt)
  887. ))
  888. (defvar rst-adjust-hook nil
  889. "Hooks to be run after running `rst-adjust'.")
  890. (defvar rst-new-decoration-down nil
  891. "Non-nil if new decoration is added deeper.
  892. If non-nil, a new decoration being added will be initialized to
  893. be one level down from the previous decoration. If nil, a new
  894. decoration will be equal to the level of the previous
  895. decoration.")
  896. (defun rst-adjust-decoration (&optional toggle-style reverse-direction)
  897. "Adjust/rotate the section decoration for the section title around point.
  898. This function is meant to be invoked possibly multiple times, and
  899. can vary its behavior with a true TOGGLE-STYLE argument, or with
  900. a REVERSE-DIRECTION argument.
  901. General Behavior
  902. ================
  903. The next action it takes depends on context around the point, and
  904. it is meant to be invoked possibly more than once to rotate among
  905. the various possibilities. Basically, this function deals with:
  906. - adding a decoration if the title does not have one;
  907. - adjusting the length of the underline characters to fit a
  908. modified title;
  909. - rotating the decoration in the set of already existing
  910. sectioning decorations used in the file;
  911. - switching between simple and over-and-under styles.
  912. You should normally not have to read all the following, just
  913. invoke the method and it will do the most obvious thing that you
  914. would expect.
  915. Decoration Definitions
  916. ======================
  917. The decorations consist in
  918. 1. a CHARACTER
  919. 2. a STYLE which can be either of 'simple' or 'over-and-under'.
  920. 3. an INDENT (meaningful for the over-and-under style only)
  921. which determines how many characters and over-and-under
  922. style is hanging outside of the title at the beginning and
  923. ending.
  924. See source code for mode details.
  925. Detailed Behavior Description
  926. =============================
  927. Here are the gory details of the algorithm (it seems quite
  928. complicated, but really, it does the most obvious thing in all
  929. the particular cases):
  930. Before applying the decoration change, the cursor is placed on
  931. the closest line that could contain a section title.
  932. Case 1: No Decoration
  933. ---------------------
  934. If the current line has no decoration around it,
  935. - search backwards for the last previous decoration, and apply
  936. the decoration one level lower to the current line. If there
  937. is no defined level below this previous decoration, we suggest
  938. the most appropriate of the `rst-preferred-decorations'.
  939. If REVERSE-DIRECTION is true, we simply use the previous
  940. decoration found directly.
  941. - if there is no decoration found in the given direction, we use
  942. the first of `rst-preferred-decorations'.
  943. The prefix argument forces a toggle of the prescribed decoration
  944. style.
  945. Case 2: Incomplete Decoration
  946. -----------------------------
  947. If the current line does have an existing decoration, but the
  948. decoration is incomplete, that is, the underline/overline does
  949. not extend to exactly the end of the title line (it is either too
  950. short or too long), we simply extend the length of the
  951. underlines/overlines to fit exactly the section title.
  952. If the prefix argument is given, we toggle the style of the
  953. decoration as well.
  954. REVERSE-DIRECTION has no effect in this case.
  955. Case 3: Complete Existing Decoration
  956. ------------------------------------
  957. If the decoration is complete (i.e. the underline (overline)
  958. length is already adjusted to the end of the title line), we
  959. search/parse the file to establish the hierarchy of all the
  960. decorations (making sure not to include the decoration around
  961. point), and we rotate the current title's decoration from within
  962. that list (by default, going *down* the hierarchy that is present
  963. in the file, i.e. to a lower section level). This is meant to be
  964. used potentially multiple times, until the desired decoration is
  965. found around the title.
  966. If we hit the boundary of the hierarchy, exactly one choice from
  967. the list of preferred decorations is suggested/chosen, the first
  968. of those decoration that has not been seen in the file yet (and
  969. not including the decoration around point), and the next
  970. invocation rolls over to the other end of the hierarchy (i.e. it
  971. cycles). This allows you to avoid having to set which character
  972. to use.
  973. If REVERSE-DIRECTION is true, the effect is to change the
  974. direction of rotation in the hierarchy of decorations, thus
  975. instead going *up* the hierarchy.
  976. However, if there is a non-negative prefix argument, we do not
  977. rotate the decoration, but instead simply toggle the style of the
  978. current decoration (this should be the most common way to toggle
  979. the style of an existing complete decoration).
  980. Point Location
  981. ==============
  982. The invocation of this function can be carried out anywhere
  983. within the section title line, on an existing underline or
  984. overline, as well as on an empty line following a section title.
  985. This is meant to be as convenient as possible.
  986. Indented Sections
  987. =================
  988. Indented section titles such as ::
  989. My Title
  990. --------
  991. are invalid in restructuredtext and thus not recognized by the
  992. parser. This code will thus not work in a way that would support
  993. indented sections (it would be ambiguous anyway).
  994. Joint Sections
  995. ==============
  996. Section titles that are right next to each other may not be
  997. treated well. More work might be needed to support those, and
  998. special conditions on the completeness of existing decorations
  999. might be required to make it non-ambiguous.
  1000. For now we assume that the decorations are disjoint, that is,
  1001. there is at least a single line between the titles/decoration
  1002. lines.
  1003. Suggested Binding
  1004. =================
  1005. We suggest that you bind this function on C-=. It is close to
  1006. C-- so a negative argument can be easily specified with a flick
  1007. of the right hand fingers and the binding is unused in `text-mode'."
  1008. (interactive)
  1009. ;; If we were invoked directly, parse the prefix arguments into the
  1010. ;; arguments of the function.
  1011. (if current-prefix-arg
  1012. (setq reverse-direction
  1013. (and current-prefix-arg
  1014. (< (prefix-numeric-value current-prefix-arg) 0))
  1015. toggle-style
  1016. (and current-prefix-arg (not reverse-direction))))
  1017. (let* (;; Check if we're on an underline around a section title, and move the
  1018. ;; cursor to the title if this is the case.
  1019. (moved (rst-normalize-cursor-position))
  1020. ;; Find the decoration and completeness around point.
  1021. (curdeco (rst-get-decoration))
  1022. (char (car curdeco))
  1023. (style (cadr curdeco))
  1024. (indent (caddr curdeco))
  1025. ;; New values to be computed.
  1026. char-new style-new indent-new
  1027. )
  1028. ;; We've moved the cursor... if we're not looking at some text, we have
  1029. ;; nothing to do.
  1030. (if (save-excursion (beginning-of-line)
  1031. (looking-at rst-section-text-regexp))
  1032. (progn
  1033. (cond
  1034. ;;-------------------------------------------------------------------
  1035. ;; Case 1: No Decoration
  1036. ((and (eq char nil) (eq style nil))
  1037. (let* ((alldecos (rst-find-all-decorations))
  1038. (around (rst-get-decorations-around alldecos))
  1039. (prev (car around))
  1040. cur
  1041. (hier (rst-get-hierarchy alldecos))
  1042. )
  1043. ;; Advance one level down.
  1044. (setq cur
  1045. (if prev
  1046. (if (not reverse-direction)
  1047. (or (funcall (if rst-new-decoration-down 'cadr 'car)
  1048. (rst-get-decoration-match hier prev))
  1049. (rst-suggest-new-decoration hier prev))
  1050. prev)
  1051. (copy-sequence (car rst-preferred-decorations))))
  1052. ;; Invert the style if requested.
  1053. (if toggle-style
  1054. (setcar (cdr cur) (if (eq (cadr cur) 'simple)
  1055. 'over-and-under 'simple)) )
  1056. (setq char-new (car cur)
  1057. style-new (cadr cur)
  1058. indent-new (caddr cur))
  1059. ))
  1060. ;;-------------------------------------------------------------------
  1061. ;; Case 2: Incomplete Decoration
  1062. ((not (rst-decoration-complete-p curdeco))
  1063. ;; Invert the style if requested.
  1064. (if toggle-style
  1065. (setq style (if (eq style 'simple) 'over-and-under 'simple)))
  1066. (setq char-new char
  1067. style-new style
  1068. indent-new indent))
  1069. ;;-------------------------------------------------------------------
  1070. ;; Case 3: Complete Existing Decoration
  1071. (t
  1072. (if toggle-style
  1073. ;; Simply switch the style of the current decoration.
  1074. (setq char-new char
  1075. style-new (if (eq style 'simple) 'over-and-under 'simple)
  1076. indent-new rst-default-indent)
  1077. ;; Else, we rotate, ignoring the decoration around the current
  1078. ;; line...
  1079. (let* ((alldecos (rst-find-all-decorations))
  1080. (hier (rst-get-hierarchy alldecos (line-number-at-pos)))
  1081. ;; Suggestion, in case we need to come up with something
  1082. ;; new
  1083. (suggestion (rst-suggest-new-decoration
  1084. hier
  1085. (car (rst-get-decorations-around alldecos))))
  1086. (nextdeco (rst-get-next-decoration
  1087. curdeco hier suggestion reverse-direction))
  1088. )
  1089. ;; Indent, if present, always overrides the prescribed indent.
  1090. (setq char-new (car nextdeco)
  1091. style-new (cadr nextdeco)
  1092. indent-new (caddr nextdeco))
  1093. )))
  1094. )
  1095. ;; Override indent with present indent!
  1096. (setq indent-new (if (> indent 0) indent indent-new))
  1097. (if (and char-new style-new)
  1098. (rst-update-section char-new style-new indent-new))
  1099. ))
  1100. ;; Correct the position of the cursor to more accurately reflect where it
  1101. ;; was located when the function was invoked.
  1102. (unless (= moved 0)
  1103. (forward-line (- moved))
  1104. (end-of-line))
  1105. ))
  1106. ;; Maintain an alias for compatibility.
  1107. (defalias 'rst-adjust-section-title 'rst-adjust)
  1108. (defun rst-promote-region (&optional demote)
  1109. "Promote the section titles within the region.
  1110. With argument DEMOTE or a prefix argument, demote the section
  1111. titles instead. The algorithm used at the boundaries of the
  1112. hierarchy is similar to that used by `rst-adjust-decoration'."
  1113. (interactive)
  1114. (let* ((demote (or current-prefix-arg demote))
  1115. (alldecos (rst-find-all-decorations))
  1116. (cur alldecos)
  1117. (hier (rst-get-hierarchy alldecos))
  1118. (suggestion (rst-suggest-new-decoration hier))
  1119. (region-begin-line (line-number-at-pos (region-beginning)))
  1120. (region-end-line (line-number-at-pos (region-end)))
  1121. marker-list
  1122. )
  1123. ;; Skip the markers that come before the region beginning
  1124. (while (and cur (< (caar cur) region-begin-line))
  1125. (setq cur (cdr cur)))
  1126. ;; Create a list of markers for all the decorations which are found within
  1127. ;; the region.
  1128. (save-excursion
  1129. (let (line)
  1130. (while (and cur (< (setq line (caar cur)) region-end-line))
  1131. (goto-char (point-min))
  1132. (forward-line (1- line))
  1133. (push (list (point-marker) (cdar cur)) marker-list)
  1134. (setq cur (cdr cur)) ))
  1135. ;; Apply modifications.
  1136. (dolist (p marker-list)
  1137. ;; Go to the decoration to promote.
  1138. (goto-char (car p))
  1139. ;; Update the decoration.
  1140. (apply 'rst-update-section
  1141. ;; Rotate the next decoration.
  1142. (rst-get-next-decoration
  1143. (cadr p) hier suggestion demote))
  1144. ;; Clear marker to avoid slowing down the editing after we're done.
  1145. (set-marker (car p) nil))
  1146. (setq deactivate-mark nil)
  1147. )))
  1148. (defun rst-display-decorations-hierarchy (&optional decorations)
  1149. "Display the current file's section title decorations hierarchy.
  1150. This function expects a list of (char, style, indent) triples in
  1151. DECORATIONS."
  1152. (interactive)
  1153. (if (not decorations)
  1154. (setq decorations (rst-get-hierarchy)))
  1155. (with-output-to-temp-buffer "*rest section hierarchy*"
  1156. (let ((level 1))
  1157. (with-current-buffer standard-output
  1158. (dolist (x decorations)
  1159. (insert (format "\nSection Level %d" level))
  1160. (apply 'rst-update-section x)
  1161. (goto-char (point-max))
  1162. (insert "\n")
  1163. (incf level)
  1164. ))
  1165. )))
  1166. (defun rst-position (elem list)
  1167. "Return position of ELEM in LIST or nil."
  1168. (let ((tail (member elem list)))
  1169. (if tail (- (length list) (length tail)))))
  1170. (defun rst-straighten-decorations ()
  1171. "Redo all the decorations in the current buffer.
  1172. This is done using our preferred set of decorations. This can be
  1173. used, for example, when using somebody else's copy of a document,
  1174. in order to adapt it to our preferred style."
  1175. (interactive)
  1176. (save-excursion
  1177. (let* ((alldecos (rst-find-all-decorations))
  1178. (hier (rst-get-hierarchy alldecos))
  1179. ;; Get a list of pairs of (level . marker)
  1180. (levels-and-markers (mapcar
  1181. (lambda (deco)
  1182. (cons (rst-position (cdr deco) hier)
  1183. (progn
  1184. (goto-char (point-min))
  1185. (forward-line (1- (car deco)))
  1186. (point-marker))))
  1187. alldecos))
  1188. )
  1189. (dolist (lm levels-and-markers)
  1190. ;; Go to the appropriate position
  1191. (goto-char (cdr lm))
  1192. ;; Apply the new styule
  1193. (apply 'rst-update-section (nth (car lm) rst-preferred-decorations))
  1194. ;; Reset the market to avoid slowing down editing until it gets GC'ed
  1195. (set-marker (cdr lm) nil)
  1196. )
  1197. )))
  1198. (defun rst-straighten-deco-spacing ()
  1199. "Adjust the spacing before and after decorations in the entire document.
  1200. The spacing will be set to two blank lines before the first two
  1201. section levels, and one blank line before any of the other
  1202. section levels."
  1203. ;; FIXME: we need to take care of subtitle at some point.
  1204. (interactive)
  1205. (save-excursion
  1206. (let* ((alldecos (rst-find-all-decorations)))
  1207. ;; Work the list from the end, so that we don't have to use markers to
  1208. ;; adjust for the changes in the document.
  1209. (dolist (deco (nreverse alldecos))
  1210. ;; Go to the appropriate position.
  1211. (goto-char (point-min))
  1212. (forward-line (1- (car deco)))
  1213. (insert "@\n")
  1214. ;; FIXME: todo, we
  1215. )
  1216. )))
  1217. (defun rst-find-pfx-in-region (beg end pfx-re)
  1218. "Find all the positions of prefixes in region between BEG and END.
  1219. This is used to find bullets and enumerated list items. PFX-RE
  1220. is a regular expression for matching the lines with items."
  1221. (let ((pfx ()))
  1222. (save-excursion
  1223. (goto-char beg)
  1224. (while (< (point) end)
  1225. (back-to-indentation)
  1226. (when (and
  1227. (looking-at pfx-re)
  1228. (let ((pfx-col (current-column)))
  1229. (save-excursion
  1230. (forward-line -1)
  1231. (back-to-indentation)
  1232. (or (looking-at "^[ \t]*$")
  1233. (> (current-column) pfx-col)
  1234. (and (= (current-column) pfx-col)
  1235. (looking-at pfx-re))))))
  1236. (push (cons (point) (current-column))
  1237. pfx))
  1238. (forward-line 1)) )
  1239. (nreverse pfx)))
  1240. (defvar rst-re-bullets
  1241. (format "\\([%s][ \t]\\)[^ \t]" (regexp-quote (concat rst-bullets)))
  1242. "Regexp for finding bullets.")
  1243. ;; (defvar rst-re-enumerations
  1244. ;; "\\(\\(#\\|[0-9]+\\)\\.[ \t]\\)[^ \t]"
  1245. ;; "Regexp for finding bullets.")
  1246. (defvar rst-re-items
  1247. (format "\\(%s\\|%s\\)[^ \t]"
  1248. (format "[%s][ \t]" (regexp-quote (concat rst-bullets)))
  1249. "\\(#\\|[0-9]+\\)\\.[ \t]")
  1250. "Regexp for finding bullets.")
  1251. (defvar rst-preferred-bullets
  1252. '(?- ?* ?+)
  1253. "List of favorite bullets to set for straightening bullets.")
  1254. (defun rst-straighten-bullets-region (beg end)
  1255. "Make all the bulleted list items in the region consistent.
  1256. The region is specified between BEG and END. You can use this
  1257. after you have merged multiple bulleted lists to make them use
  1258. the same/correct/consistent bullet characters.
  1259. See variable `rst-preferred-bullets' for the list of bullets to
  1260. adjust. If bullets are found on levels beyond the
  1261. `rst-preferred-bullets' list, they are not modified."
  1262. (interactive "r")
  1263. (let ((bullets (rst-find-pfx-in-region beg end
  1264. rst-re-bullets))
  1265. (levtable (make-hash-table :size 4)))
  1266. ;; Create a map of levels to list of positions.
  1267. (dolist (x bullets)
  1268. (let ((key (cdr x)))
  1269. (puthash key
  1270. (append (gethash key levtable (list))
  1271. (list (car x)))
  1272. levtable)))
  1273. ;; Sort this map and create a new map of prefix char and list of positions.
  1274. (let ((poslist ())) ; List of (indent . positions).
  1275. (maphash (lambda (x y) (push (cons x y) poslist)) levtable)
  1276. (let ((bullets rst-preferred-bullets))
  1277. (dolist (x (sort poslist 'car-less-than-car))
  1278. (when bullets
  1279. ;; Apply the characters.
  1280. (dolist (pos (cdr x))
  1281. (goto-char pos)
  1282. (delete-char 1)
  1283. (insert (string (car bullets))))
  1284. (setq bullets (cdr bullets))))))))
  1285. (defun rst-rstrip (str)
  1286. "Strips the whitespace at the end of string STR."
  1287. (string-match "[ \t\n]*\\'" str)
  1288. (substring str 0 (match-beginning 0)))
  1289. (defun rst-get-stripped-line ()
  1290. "Return the line at cursor, stripped from whitespace."
  1291. (re-search-forward "\\S-.*\\S-" (line-end-position))
  1292. (buffer-substring-no-properties (match-beginning 0)
  1293. (match-end 0)) )
  1294. (defun rst-section-tree (alldecos)
  1295. "Get the hierarchical tree of section titles.
  1296. Returns a hierarchical tree of the sections titles in the
  1297. document, for decorations ALLDECOS. This can be used to generate
  1298. a table of contents for the document. The top node will always
  1299. be a nil node, with the top level titles as children (there may
  1300. potentially be more than one).
  1301. Each section title consists in a cons of the stripped title
  1302. string and a marker to the section in the original text document.
  1303. If there are missing section levels, the section titles are
  1304. inserted automatically, and the title string is set to nil, and
  1305. the marker set to the first non-nil child of itself.
  1306. Conceptually, the nil nodes--i.e. those which have no title--are
  1307. to be considered as being the same line as their first non-nil
  1308. child. This has advantages later in processing the graph."
  1309. (let* ((hier (rst-get-hierarchy alldecos))
  1310. (levels (make-hash-table :test 'equal :size 10))
  1311. lines)
  1312. (let ((lev 0))
  1313. (dolist (deco hier)
  1314. ;; Compare just the character and indent in the hash table.
  1315. (puthash (cons (car deco) (cadr deco)) lev levels)
  1316. (incf lev)))
  1317. ;; Create a list of lines that contains (text, level, marker) for each
  1318. ;; decoration.
  1319. (save-excursion
  1320. (setq lines
  1321. (mapcar (lambda (deco)
  1322. (goto-char (point-min))
  1323. (forward-line (1- (car deco)))
  1324. (list (gethash (cons (cadr deco) (caddr deco)) levels)
  1325. (rst-get-stripped-line)
  1326. (progn
  1327. (beginning-of-line 1)
  1328. (point-marker))))
  1329. alldecos)))
  1330. (let ((lcontnr (cons nil lines)))
  1331. (rst-section-tree-rec lcontnr -1))))
  1332. (defun rst-section-tree-rec (decos lev)
  1333. "Recursive guts of the section tree construction.
  1334. DECOS is a cons cell whose cdr is the remaining list of
  1335. decorations, and we change it as we consume them. LEV is
  1336. the current level of that node. This function returns a
  1337. pair of the subtree that was built. This treats the DECOS
  1338. list destructively."
  1339. (let ((ndeco (cadr decos))
  1340. node
  1341. children)
  1342. ;; If the next decoration matches our level
  1343. (when (and ndeco (= (car ndeco) lev))
  1344. ;; Pop the next decoration and create the current node with it
  1345. (setcdr decos (cddr decos))
  1346. (setq node (cdr ndeco)) )
  1347. ;; Else we let the node title/marker be unset.
  1348. ;; Build the child nodes
  1349. (while (and (cdr decos) (> (caadr decos) lev))
  1350. (setq children
  1351. (cons (rst-section-tree-rec decos (1+ lev))
  1352. children)))
  1353. (setq children (reverse children))
  1354. ;; If node is still unset, we use the marker of the first child.
  1355. (when (eq node nil)
  1356. (setq node (cons nil (cdaar children))))
  1357. ;; Return this node with its children.
  1358. (cons node children)
  1359. ))
  1360. (defun rst-section-tree-point (node &optional point)
  1361. "Find tree node at point.
  1362. Given a computed and valid section tree in NODE and a point
  1363. POINT (default being the current point in the current buffer),
  1364. find and return the node within the sectree where the cursor
  1365. lives.
  1366. Return values: a pair of (parent path, container subtree).
  1367. The parent path is simply a list of the nodes above the
  1368. container subtree node that we're returning."
  1369. (let (path outtree)
  1370. (let* ((curpoint (or point (point))))
  1371. ;; Check if we are before the current node.
  1372. (if (and (cadar node) (>= curpoint (cadar node)))
  1373. ;; Iterate all the children, looking for one that might contain the
  1374. ;; current section.
  1375. (let ((curnode (cdr node))
  1376. last)
  1377. (while (and curnode (>= curpoint (cadaar curnode)))
  1378. (setq last curnode
  1379. curnode (cdr curnode)))
  1380. (if last
  1381. (let ((sub (rst-section-tree-point (car last) curpoint)))
  1382. (setq path (car sub)
  1383. outtree (cdr sub)))
  1384. (setq outtree node))
  1385. )))
  1386. (cons (cons (car node) path) outtree)
  1387. ))
  1388. (defgroup rst-toc nil
  1389. "Settings for reStructuredText table of contents."
  1390. :group 'rst
  1391. :version "21.1")
  1392. (defcustom rst-toc-indent 2
  1393. "Indentation for table-of-contents display.
  1394. Also used for formatting insertion, when numbering is disabled."
  1395. :group 'rst-toc)
  1396. (defcustom rst-toc-insert-style 'fixed
  1397. "Insertion style for table-of-contents.
  1398. Set this to one of the following values to determine numbering and
  1399. indentation style:
  1400. - plain: no numbering (fixed indentation)
  1401. - fixed: numbering, but fixed indentation
  1402. - aligned: numbering, titles aligned under each other
  1403. - listed: numbering, with dashes like list items (EXPERIMENTAL)"
  1404. :group 'rst-toc)
  1405. (defcustom rst-toc-insert-number-separator " "
  1406. "Separator that goes between the TOC number and the title."
  1407. :group 'rst-toc)
  1408. ;; This is used to avoid having to change the user's mode.
  1409. (defvar rst-toc-insert-click-keymap
  1410. (let ((map (make-sparse-keymap)))
  1411. (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
  1412. map)
  1413. "(Internal) What happens when you click on propertized text in the TOC.")
  1414. (defcustom rst-toc-insert-max-level nil
  1415. "If non-nil, maximum depth of the inserted TOC."
  1416. :group 'rst-toc)
  1417. (defun rst-toc-insert (&optional pfxarg)
  1418. "Insert a simple text rendering of the table of contents.
  1419. By default the top level is ignored if there is only one, because
  1420. we assume that the document will have a single title.
  1421. If a numeric prefix argument PFXARG is given, insert the TOC up
  1422. to the specified level.
  1423. The TOC is inserted indented at the current column."
  1424. (interactive "P")
  1425. (let* (;; Check maximum level override
  1426. (rst-toc-insert-max-level
  1427. (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
  1428. (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
  1429. ;; Get the section tree for the current cursor point.
  1430. (sectree-pair
  1431. (rst-section-tree-point
  1432. (rst-section-tree (rst-find-all-decorations))))
  1433. ;; Figure out initial indent.
  1434. (initial-indent (make-string (current-column) ? ))
  1435. (init-point (point)))
  1436. (when (cddr sectree-pair)
  1437. (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
  1438. ;; Fixup for the first line.
  1439. (delete-region init-point (+ init-point (length initial-indent)))
  1440. ;; Delete the last newline added.
  1441. (delete-char -1)
  1442. )))
  1443. (defun rst-toc-insert-node (node level indent pfx)
  1444. "Insert tree node NODE in table-of-contents.
  1445. Recursive function that does printing of the inserted toc.
  1446. LEVEL is the depth level of the sections in the tree.
  1447. INDENT is the indentation string. PFX is the prefix numbering,
  1448. that includes the alignment necessary for all the children of
  1449. level to align."
  1450. ;; Note: we do child numbering from the parent, so we start number the
  1451. ;; children one level before we print them.
  1452. (let ((do-print (> level 0))
  1453. (count 1))
  1454. (when do-print
  1455. (insert indent)
  1456. (let ((b (point)))
  1457. (unless (equal rst-toc-insert-style 'plain)
  1458. (insert pfx rst-toc-insert-number-separator))
  1459. (insert (or (caar node) "[missing node]"))
  1460. ;; Add properties to the text, even though in normal text mode it
  1461. ;; won't be doing anything for now. Not sure that I want to change
  1462. ;; mode stuff. At least the highlighting gives the idea that this
  1463. ;; is generated automatically.
  1464. (put-text-property b (point) 'mouse-face 'highlight)
  1465. (put-text-property b (point) 'rst-toc-target (cadar node))
  1466. (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
  1467. )
  1468. (insert "\n")
  1469. ;; Prepare indent for children.
  1470. (setq indent
  1471. (cond
  1472. ((eq rst-toc-insert-style 'plain)
  1473. (concat indent (make-string rst-toc-indent ? )))
  1474. ((eq rst-toc-insert-style 'fixed)
  1475. (concat indent (make-string rst-toc-indent ? )))
  1476. ((eq rst-toc-insert-style 'aligned)
  1477. (concat indent (make-string (+ (length pfx) 2) ? )))
  1478. ((eq rst-toc-insert-style 'listed)
  1479. (concat (substring indent 0 -3)
  1480. (concat (make-string (+ (length pfx) 2) ? ) " - ")))
  1481. ))
  1482. )
  1483. (if (or (eq rst-toc-insert-max-level nil)
  1484. (< level rst-toc-insert-max-level))
  1485. (let ((do-child-numbering (>= level 0))
  1486. fmt)
  1487. (if do-child-numbering
  1488. (progn
  1489. ;; Add a separating dot if there is already a prefix
  1490. (if (> (length pfx) 0)
  1491. (setq pfx (concat (rst-rstrip pfx) ".")))
  1492. ;; Calculate the amount of space that the prefix will require
  1493. ;; for the numbers.
  1494. (if (cdr node)
  1495. (setq fmt (format "%%-%dd"
  1496. (1+ (floor (log10 (length
  1497. (cdr node))))))))
  1498. ))
  1499. (dolist (child (cdr node))
  1500. (rst-toc-insert-node child
  1501. (1+ level)
  1502. indent
  1503. (if do-child-numbering
  1504. (concat pfx (format fmt count)) pfx))
  1505. (incf count)))
  1506. )))
  1507. (defun rst-toc-insert-find-delete-contents ()
  1508. "Find and delete an existing comment after the first contents directive.
  1509. Delete that region. Return t if found and the cursor is left after the comment."
  1510. (goto-char (point-min))
  1511. ;; We look for the following and the following only (in other words, if your
  1512. ;; syntax differs, this won't work. If you would like a more flexible thing,
  1513. ;; contact the author, I just can't imagine that this requirement is
  1514. ;; unreasonable for now).
  1515. ;;
  1516. ;; .. contents:: [...anything here...]
  1517. ;; ..
  1518. ;; XXXXXXXX
  1519. ;; XXXXXXXX
  1520. ;; [more lines]
  1521. ;;
  1522. (let ((beg
  1523. (re-search-forward "^\\.\\. contents[ \t]*::\\(.*\\)\n\\.\\."
  1524. nil t))
  1525. last-real)
  1526. (when beg
  1527. ;; Look for the first line that starts at the first column.
  1528. (forward-line 1)
  1529. (beginning-of-line)
  1530. (while (and
  1531. (< (point) (point-max))
  1532. (or (and (looking-at "[ \t]+[^ \t]") (setq last-real (point)) t)
  1533. (looking-at "[ \t]*$")))
  1534. (forward-line 1)
  1535. )
  1536. (if last-real
  1537. (progn
  1538. (goto-char last-real)
  1539. (end-of-line)
  1540. (delete-region beg (point)))
  1541. (goto-char beg))
  1542. t
  1543. )))
  1544. (defun rst-toc-update ()
  1545. "Automatically find the contents section of a document and update.
  1546. Updates the inserted TOC if present. You can use this in your
  1547. file-write hook to always make it up-to-date automatically."
  1548. (interactive)
  1549. (let ((p (point)))
  1550. (save-excursion
  1551. (when (rst-toc-insert-find-delete-contents)
  1552. (insert "\n ")
  1553. (rst-toc-insert)
  1554. ))
  1555. ;; Somehow save-excursion does not really work well.
  1556. (goto-char p))
  1557. ;; Note: always return nil, because this may be used as a hook.
  1558. )
  1559. ;; Note: we cannot bind the TOC update on file write because it messes with
  1560. ;; undo. If we disable undo, since it adds and removes characters, the
  1561. ;; positions in the undo list are not making sense anymore. Dunno what to do
  1562. ;; with this, it would be nice to update when saving.
  1563. ;;
  1564. ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
  1565. ;; (defun rst-toc-update-fun ()
  1566. ;; ;; Disable undo for the write file hook.
  1567. ;; (let ((buffer-undo-list t)) (rst-toc-update) ))
  1568. (defalias 'rst-toc-insert-update 'rst-toc-update) ;; backwards compat.
  1569. ;;------------------------------------------------------------------------------
  1570. (defun rst-toc-node (node level)
  1571. "Recursive function that does insert NODE at LEVEL in the table-of-contents."
  1572. (if (> level 0)
  1573. (let ((b (point)))
  1574. ;; Insert line text.
  1575. (insert (make-string (* rst-toc-indent (1- level)) ? ))
  1576. (insert (or (caar node) "[missing node]"))
  1577. ;; Highlight lines.
  1578. (put-text-property b (point) 'mouse-face 'highlight)
  1579. ;; Add link on lines.
  1580. (put-text-property b (point) 'rst-toc-target (cadar node))
  1581. (insert "\n")
  1582. ))
  1583. (dolist (child (cdr node))
  1584. (rst-toc-node child (1+ level))))
  1585. (defun rst-toc-count-lines (node target-node)
  1586. "Count the number of lines from NODE to the TARGET-NODE node.
  1587. This recursive function returns a cons of the number of
  1588. additional lines that have been counted for its node and
  1589. children, and t if the node has been found."
  1590. (let ((count 1)
  1591. found)
  1592. (if (eq node target-node)
  1593. (setq found t)
  1594. (let ((child (cdr node)))
  1595. (while (and child (not found))
  1596. (let ((cl (rst-toc-count-lines (car child) target-node)))
  1597. (setq count (+ count (car cl))
  1598. found (cdr cl)
  1599. child (cdr child))))))
  1600. (cons count found)))
  1601. (defvar rst-toc-buffer-name "*Table of Contents*"
  1602. "Name of the Table of Contents buffer.")
  1603. (defvar rst-toc-return-buffer nil
  1604. "Buffer to which to return when leaving the TOC.")
  1605. (defun rst-toc ()
  1606. "Display a table-of-contents.
  1607. Finds all the section titles and their decorations in the
  1608. file, and displays a hierarchically-organized list of the
  1609. titles, which is essentially a table-of-contents of the
  1610. document.
  1611. The Emacs buffer can be navigated, and selecting a section
  1612. brings the cursor in that section."
  1613. (interactive)
  1614. (let* ((curbuf (current-buffer))
  1615. ;; Get the section tree
  1616. (alldecos (rst-find-all-decorations))
  1617. (sectree (rst-section-tree alldecos))
  1618. (our-node (cdr (rst-section-tree-point sectree)))
  1619. line
  1620. ;; Create a temporary buffer.
  1621. (buf (get-buffer-create rst-toc-buffer-name))
  1622. )
  1623. (with-current-buffer buf
  1624. (let ((inhibit-read-only t))
  1625. (rst-toc-mode)
  1626. (delete-region (point-min) (point-max))
  1627. (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
  1628. (put-text-property (point-min) (point)
  1629. 'face (list '(background-color . "gray")))
  1630. (rst-toc-node sectree 0)
  1631. ;; Count the lines to our found node.
  1632. (let ((linefound (rst-toc-count-lines sectree our-node)))
  1633. (setq line (if (cdr linefound) (car linefound) 0)))
  1634. ))
  1635. (display-buffer buf)
  1636. (pop-to-buffer buf)
  1637. ;; Save the buffer to return to.
  1638. (set (make-local-variable 'rst-toc-return-buffer) curbuf)
  1639. ;; Move the cursor near the right section in the TOC.
  1640. (goto-char (point-min))
  1641. (forward-line (1- line))
  1642. ))
  1643. (defun rst-toc-mode-find-section ()
  1644. "Get the section from text property at point."
  1645. (let ((pos (get-text-property (point) 'rst-toc-target)))
  1646. (unless pos
  1647. (error "No section on this line"))
  1648. (unless (buffer-live-p (marker-buffer pos))
  1649. (error "Buffer for this section was killed"))
  1650. pos))
  1651. (defun rst-goto-section (&optional kill)
  1652. "Go to the section the current line describes."
  1653. (interactive)
  1654. (let ((pos (rst-toc-mode-find-section)))
  1655. (when kill
  1656. (kill-buffer (get-buffer rst-toc-buffer-name)))
  1657. (pop-to-buffer (marker-buffer pos))
  1658. (goto-char pos)
  1659. ;; FIXME: make the recentering conditional on scroll.
  1660. (recenter 5)))
  1661. (defun rst-toc-mode-goto-section ()
  1662. "Go to the section the current line describes and kill the TOC buffer."
  1663. (interactive)
  1664. (rst-goto-section t))
  1665. (defun rst-toc-mode-mouse-goto (event)
  1666. "In `rst-toc' mode, go to the occurrence whose line you click on.
  1667. EVENT is the input event."
  1668. (interactive "e")
  1669. (let ((pos
  1670. (with-current-buffer (window-buffer (posn-window (event-end event)))
  1671. (save-excursion
  1672. (goto-char (posn-point (event-end event)))
  1673. (rst-toc-mode-find-section)))))
  1674. (pop-to-buffer (marker-buffer pos))
  1675. (goto-char pos)
  1676. (recenter 5)))
  1677. (defun rst-toc-mode-mouse-goto-kill (event)
  1678. "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well."
  1679. (interactive "e")
  1680. (call-interactively 'rst-toc-mode-mouse-goto event)
  1681. (kill-buffer (get-buffer rst-toc-buffer-name)))
  1682. (defun rst-toc-quit-window ()
  1683. "Leave the current TOC buffer."
  1684. (interactive)
  1685. (quit-window)
  1686. (pop-to-buffer rst-toc-return-buffer))
  1687. (defvar rst-toc-mode-map
  1688. (let ((map (make-sparse-keymap)))
  1689. (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
  1690. (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
  1691. (define-key map "\C-m" 'rst-toc-mode-goto-section)
  1692. (define-key map "f" 'rst-toc-mode-goto-section)
  1693. (define-key map "q" 'rst-toc-quit-window)
  1694. (define-key map "z" 'kill-this-buffer)
  1695. map)
  1696. "Keymap for `rst-toc-mode'.")
  1697. (put 'rst-toc-mode 'mode-class 'special)
  1698. ;; Could inherit from the new `special-mode'.
  1699. (define-derived-mode rst-toc-mode nil "ReST-TOC"
  1700. "Major mode for output from \\[rst-toc], the table-of-contents for the document."
  1701. (setq buffer-read-only t))
  1702. ;; Note: use occur-mode (replace.el) as a good example to complete missing
  1703. ;; features.
  1704. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1705. ;;
  1706. ;; Section movement commands.
  1707. ;;
  1708. (defun rst-forward-section (&optional offset)
  1709. "Skip to the next restructured text section title.
  1710. OFFSET specifies how many titles to skip. Use a negative OFFSET to move
  1711. backwards in the file (default is to use 1)."
  1712. (interactive)
  1713. (let* (;; Default value for offset.
  1714. (offset (or offset 1))
  1715. ;; Get all the decorations in the file, with their line numbers.
  1716. (alldecos (rst-find-all-decorations))
  1717. ;; Get the current line.
  1718. (curline (line-number-at-pos))
  1719. (cur alldecos)
  1720. (idx 0)
  1721. )
  1722. ;; Find the index of the "next" decoration w.r.t. to the current line.
  1723. (while (and cur (< (caar cur) curline))
  1724. (setq cur (cdr cur))
  1725. (incf idx))
  1726. ;; 'cur' is the decoration on or following the current line.
  1727. (if (and (> offset 0) cur (= (caar cur) curline))
  1728. (incf idx))
  1729. ;; Find the final index.
  1730. (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
  1731. (setq cur (nth idx alldecos))
  1732. ;; If the index is positive, goto the line, otherwise go to the buffer
  1733. ;; boundaries.
  1734. (if (and cur (>= idx 0))
  1735. (progn
  1736. (goto-char (point-min))
  1737. (forward-line (1- (car cur))))
  1738. (if (> offset 0) (goto-char (point-max)) (goto-char (point-min))))
  1739. ))
  1740. (defun rst-backward-section ()
  1741. "Like `rst-forward-section', except move back one title."
  1742. (interactive)
  1743. (rst-forward-section -1))
  1744. (defun rst-mark-section (&optional arg allow-extend)
  1745. "Select the section that point is currently in."
  1746. ;; Cloned from mark-paragraph.
  1747. (interactive "p\np")
  1748. (unless arg (setq arg 1))
  1749. (when (zerop arg)
  1750. (error "Cannot mark zero sections"))
  1751. (cond ((and allow-extend
  1752. (or (and (eq last-command this-command) (mark t))
  1753. (rst-portable-mark-active-p)))
  1754. (set-mark
  1755. (save-excursion
  1756. (goto-char (mark))
  1757. (rst-forward-section arg)
  1758. (point))))
  1759. (t
  1760. (rst-forward-section arg)
  1761. (push-mark nil t t)
  1762. (rst-forward-section (- arg)))))
  1763. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1764. ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
  1765. ;; always 2 or 3 characters apart horizontally with rest.
  1766. ;; (FIXME: there is currently a bug that makes the region go away when we do that.)
  1767. (defvar rst-shift-fill-region nil
  1768. "If non-nil, automatically re-fill the region that is being shifted.")
  1769. (defun rst-find-leftmost-column (beg end)
  1770. "Find the leftmost column in the region."
  1771. (let ((mincol 1000))
  1772. (save-excursion
  1773. (goto-char beg)
  1774. (while (< (point) end)
  1775. (back-to-indentation)
  1776. (unless (looking-at "[ \t]*$")
  1777. (setq mincol (min mincol (current-column))))
  1778. (forward-line 1)
  1779. ))
  1780. mincol))
  1781. ;; What we really need to do is compute all the possible alignment possibilities
  1782. ;; and then select one.
  1783. ;;
  1784. ;; .. line-block::
  1785. ;;
  1786. ;; a) sdjsds
  1787. ;;
  1788. ;; - sdjsd jsjds
  1789. ;;
  1790. ;; sdsdsjdsj
  1791. ;;
  1792. ;; 11. sjdss jddjs
  1793. ;;
  1794. ;; * * * * * * *
  1795. ;;
  1796. ;; Move backwards, accumulate the beginning positions, and also the second
  1797. ;; positions, in case the line matches the bullet pattern, and then sort.
  1798. (defun rst-compute-bullet-tabs (&optional pt)
  1799. "Build the list of possible horizontal alignment points.
  1800. Search backwards from point (or point PT if specified) to
  1801. build the list of possible horizontal alignment points that
  1802. includes the beginning and contents of a restructuredtext
  1803. bulleted or enumerated list item. Return a sorted list
  1804. of (COLUMN-NUMBER . LINE) pairs."
  1805. (save-excursion
  1806. (when pt (goto-char pt))
  1807. ;; We work our way backwards and towards the left.
  1808. (let ((leftcol 100000) ;; Current column.
  1809. (tablist nil) ;; List of tab positions.
  1810. )
  1811. ;; Start by skipping the current line.
  1812. (beginning-of-line 0)
  1813. ;; Search backwards for each line.
  1814. (while (and (> (point) (point-min))
  1815. (> leftcol 0))
  1816. ;; Skip empty lines.
  1817. (unless (looking-at "^[ \t]*$")
  1818. ;; Inspect the current non-empty line
  1819. (back-to-indentation)
  1820. ;; Skip lines that are beyond the current column (we want to move
  1821. ;; towards the left).
  1822. (let ((col (current-column)))
  1823. (when (< col leftcol)
  1824. ;; Add the beginning of the line as a tabbing point.
  1825. (unless (memq col (mapcar 'car tablist))
  1826. (push (cons col (point)) tablist))
  1827. ;; Look at the line to figure out if it is a bulleted or enumerate
  1828. ;; list item.
  1829. (when (looking-at
  1830. (concat
  1831. "\\(?:"
  1832. "\\(\\(?:[0-9a-zA-Z#]\\{1,3\\}[.):-]\\|[*+-]\\)[ \t]+\\)[^ \t\n]"
  1833. "\\|"
  1834. (format "\\(%s%s+[ \t]+\\)[^ \t\n]"
  1835. (regexp-quote (thing-at-point 'char))
  1836. (regexp-quote (thing-at-point 'char)))
  1837. "\\)"
  1838. ))
  1839. ;; Add the column of the contained item.
  1840. (let* ((matchlen (length (or (match-string 1) (match-string 2))))
  1841. (newcol (+ col matchlen)))
  1842. (unless (or (>= newcol leftcol)
  1843. (memq (+ col matchlen) (mapcar 'car tablist)))
  1844. (push (cons (+ col matchlen) (+ (point) matchlen))
  1845. tablist)))
  1846. )
  1847. (setq leftcol col)
  1848. )))
  1849. ;; Move backwards one line.
  1850. (beginning-of-line 0))
  1851. (sort tablist (lambda (x y) (<= (car x) (car y))))
  1852. )))
  1853. (defun rst-debug-print-tabs (tablist)
  1854. "Insert a line and place special characters at the tab points in TABLIST."
  1855. (beginning-of-line)
  1856. (insert (concat "\n" (make-string 1000 ? ) "\n"))
  1857. (beginning-of-line 0)
  1858. (dolist (col tablist)
  1859. (beginning-of-line)
  1860. (forward-char (car col))
  1861. (delete-char 1)
  1862. (insert "@")
  1863. ))
  1864. (defun rst-debug-mark-found (tablist)
  1865. "Insert a line and place special characters at the tab points in TABLIST."
  1866. (dolist (col tablist)
  1867. (when (cdr col)
  1868. (goto-char (cdr col))
  1869. (insert "@"))))
  1870. (defvar rst-shift-basic-offset 2
  1871. "Basic horizontal shift distance when there is no preceding alignment tabs.")
  1872. (defun rst-shift-region-guts (find-next-fun offset-fun)
  1873. "(See `rst-shift-region-right' for a description)."
  1874. (let* ((mbeg (copy-marker (region-beginning)))
  1875. (mend (copy-marker (region-end)))
  1876. (tabs (rst-compute-bullet-tabs mbeg))
  1877. (leftmostcol (rst-find-leftmost-column (region-beginning) (region-end)))
  1878. )
  1879. ;; Add basic offset tabs at the end of the list. This is a better
  1880. ;; implementation technique than hysteresis and a basic offset because it
  1881. ;; insures that movement in both directions is consistently using the same
  1882. ;; column positions. This makes it more predictable.
  1883. (setq tabs
  1884. (append tabs
  1885. (mapcar (lambda (x) (cons x nil))
  1886. (let ((maxcol 120)
  1887. (max-lisp-eval-depth 2000))
  1888. (flet ((addnum (x)
  1889. (if (> x maxcol)
  1890. nil
  1891. (cons x (addnum
  1892. (+ x rst-shift-basic-offset))))))
  1893. (addnum (or (caar (last tabs)) 0))))
  1894. )))
  1895. ;; (For debugging.)
  1896. ;;; (save-excursion (goto-char mbeg) (forward-char -1) (rst-debug-print-tabs tabs))))
  1897. ;;; (print tabs)
  1898. ;;; (save-excursion (rst-debug-mark-found tabs))
  1899. ;; Apply the indent.
  1900. (indent-rigidly
  1901. mbeg mend
  1902. ;; Find the next tab after the leftmost column.
  1903. (let ((tab (funcall find-next-fun tabs leftmostcol)))
  1904. (if tab
  1905. (progn
  1906. (when (cdar tab)
  1907. (message "Aligned on '%s'"
  1908. (save-excursion
  1909. (goto-char (cdar tab))
  1910. (buffer-substring-no-properties
  1911. (line-beginning-position)
  1912. (line-end-position))))
  1913. )
  1914. (- (caar tab) leftmostcol)) ;; Num chars.
  1915. ;; Otherwise use the basic offset
  1916. (funcall offset-fun rst-shift-basic-offset)
  1917. )))
  1918. ;; Optionally reindent.
  1919. (when rst-shift-fill-region
  1920. (fill-region mbeg mend))
  1921. ))
  1922. (defun rst-shift-region-right (pfxarg)
  1923. "Indent region rigidly, by a few characters to the right.
  1924. This function first computes all possible alignment columns by
  1925. inspecting the lines preceding the region for bulleted or
  1926. enumerated list items. If the leftmost column is beyond the
  1927. preceding lines, the region is moved to the right by
  1928. `rst-shift-basic-offset'. With a prefix argument, do not
  1929. automatically fill the region."
  1930. (interactive "P")
  1931. (let ((rst-shift-fill-region
  1932. (if (not pfxarg) rst-shift-fill-region)))
  1933. (rst-shift-region-guts (lambda (tabs leftmostcol)
  1934. (let ((cur tabs))
  1935. (while (and cur (<= (caar cur) leftmostcol))
  1936. (setq cur (cdr cur)))
  1937. cur))
  1938. 'identity
  1939. )))
  1940. (defun rst-shift-region-left (pfxarg)
  1941. "Like `rst-shift-region-right', except we move to the left.
  1942. Also, if invoked with a negative prefix arg, the entire
  1943. indentation is removed, up to the leftmost character in the
  1944. region, and automatic filling is disabled."
  1945. (interactive "P")
  1946. (let ((mbeg (copy-marker (region-beginning)))
  1947. (mend (copy-marker (region-end)))
  1948. (leftmostcol (rst-find-leftmost-column
  1949. (region-beginning) (region-end)))
  1950. (rst-shift-fill-region
  1951. (if (not pfxarg) rst-shift-fill-region)))
  1952. (when (> leftmostcol 0)
  1953. (if (and pfxarg (< (prefix-numeric-value pfxarg) 0))
  1954. (progn
  1955. (indent-rigidly (region-beginning) (region-end) (- leftmostcol))
  1956. (when rst-shift-fill-region
  1957. (fill-region mbeg mend))
  1958. )
  1959. (rst-shift-region-guts (lambda (tabs leftmostcol)
  1960. (let ((cur (reverse tabs)))
  1961. (while (and cur (>= (caar cur) leftmostcol))
  1962. (setq cur (cdr cur)))
  1963. cur))
  1964. '-
  1965. ))
  1966. )))
  1967. (defmacro rst-iterate-leftmost-paragraphs
  1968. (beg end first-only body-consequent body-alternative)
  1969. "FIXME This definition is old and deprecated / we need to move
  1970. to the newer version below:
  1971. Call FUN at the beginning of each line, with an argument that
  1972. specifies whether we are at the first line of a paragraph that
  1973. starts at the leftmost column of the given region BEG and END.
  1974. Set FIRST-ONLY to true if you want to callback on the first line
  1975. of each paragraph only."
  1976. `(save-excursion
  1977. (let ((leftcol (rst-find-leftmost-column ,beg ,end))
  1978. (endm (copy-marker ,end)))
  1979. (do* (;; Iterate lines
  1980. (l (progn (goto-char ,beg) (back-to-indentation))
  1981. (progn (forward-line 1) (back-to-indentation)))
  1982. (previous nil valid)
  1983. (curcol (current-column)
  1984. (current-column))
  1985. (valid (and (= curcol leftcol)
  1986. (not (looking-at "[ \t]*$")))
  1987. (and (= curcol leftcol)
  1988. (not (looking-at "[ \t]*$"))))
  1989. )
  1990. ((>= (point) endm))
  1991. (if (if ,first-only
  1992. (and valid (not previous))
  1993. valid)
  1994. ,body-consequent
  1995. ,body-alternative)
  1996. ))))
  1997. (defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body)
  1998. "Evaluate BODY for each line in region defined by BEG END.
  1999. LEFTMOST is set to true if the line is one of the leftmost of the
  2000. entire paragraph. PARABEGIN is set to true if the line is the
  2001. first of a paragraph."
  2002. (declare (indent 1) (debug (sexp body)))
  2003. (destructuring-bind
  2004. (beg end parabegin leftmost isleftmost isempty) spec
  2005. `(save-excursion
  2006. (let ((,leftmost (rst-find-leftmost-column ,beg ,end))
  2007. (endm (copy-marker ,end)))
  2008. (do* (;; Iterate lines
  2009. (l (progn (goto-char ,beg) (back-to-indentation))
  2010. (progn (forward-line 1) (back-to-indentation)))
  2011. (empty-line-previous nil ,isempty)
  2012. (,isempty (looking-at "[ \t]*$")
  2013. (looking-at "[ \t]*$"))
  2014. (,parabegin (not ,isempty)
  2015. (and empty-line-previous
  2016. (not ,isempty)))
  2017. (,isleftmost (and (not ,isempty)
  2018. (= (current-column) ,leftmost))
  2019. (and (not ,isempty)
  2020. (= (current-column) ,leftmost)))
  2021. )
  2022. ((>= (point) endm))
  2023. (progn ,@body)
  2024. )))))
  2025. ;;------------------------------------------------------------------------------
  2026. ;; FIXME: these next functions should become part of a larger effort to redo the
  2027. ;; bullets in bulleted lists. The enumerate would just be one of the possible
  2028. ;; outputs.
  2029. ;;
  2030. ;; FIXME: TODO we need to do the enumeration removal as well.
  2031. (defun rst-enumerate-region (beg end)
  2032. "Add enumeration to all the leftmost paragraphs in the given region.
  2033. The region is specified between BEG and END. With prefix argument,
  2034. do all lines instead of just paragraphs."
  2035. (interactive "r")
  2036. (let ((count 0)
  2037. (last-insert-len nil))
  2038. (rst-iterate-leftmost-paragraphs
  2039. beg end (not current-prefix-arg)
  2040. (let ((ins-string (format "%d. " (incf count))))
  2041. (setq last-insert-len (length ins-string))
  2042. (insert ins-string))
  2043. (insert (make-string last-insert-len ?\ ))
  2044. )))
  2045. (defun rst-bullet-list-region (beg end)
  2046. "Add bullets to all the leftmost paragraphs in the given region.
  2047. The region is specified between BEG and END. With prefix argument,
  2048. do all lines instead of just paragraphs."
  2049. (interactive "r")
  2050. (rst-iterate-leftmost-paragraphs
  2051. beg end (not current-prefix-arg)
  2052. (insert "- ")
  2053. (insert " ")
  2054. ))
  2055. ;; FIXME: there are some problems left with the following function
  2056. ;; implementation:
  2057. ;;
  2058. ;; * It does not deal with a varying number of digits appropriately
  2059. ;; * It does not deal with multiple levels independently, and it should.
  2060. ;;
  2061. ;; I suppose it does 90% of the job for now.
  2062. (defun rst-convert-bullets-to-enumeration (beg end)
  2063. "Convert all the bulleted items and enumerated items in the
  2064. region to enumerated lists, renumbering as necessary."
  2065. (interactive "r")
  2066. (let* (;; Find items and convert the positions to markers.
  2067. (items (mapcar
  2068. (lambda (x)
  2069. (cons (copy-marker (car x))
  2070. (cdr x)))
  2071. (rst-find-pfx-in-region beg end rst-re-items)))
  2072. (count 1)
  2073. )
  2074. (save-excursion
  2075. (dolist (x items)
  2076. (goto-char (car x))
  2077. (looking-at rst-re-items)
  2078. (replace-match (format "%d. " count) nil nil nil 1)
  2079. (incf count)
  2080. ))
  2081. ))
  2082. ;;------------------------------------------------------------------------------
  2083. (defun rst-line-block-region (rbeg rend &optional pfxarg)
  2084. "Toggle line block prefixes for a region.
  2085. With prefix argument set the empty lines too."
  2086. (interactive "r\nP")
  2087. (let ((comment-start "| ")
  2088. (comment-end "")
  2089. (comment-start-skip "| ")
  2090. (comment-style 'indent)
  2091. (force (not (not pfxarg))))
  2092. (rst-iterate-leftmost-paragraphs-2
  2093. (rbeg rend parbegin leftmost isleft isempty)
  2094. (when (or force (not isempty))
  2095. (move-to-column leftmost force)
  2096. (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
  2097. (insert "| ")))))
  2098. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2099. (require 'font-lock)
  2100. (defgroup rst-faces nil "Faces used in Rst Mode."
  2101. :group 'rst
  2102. :group 'faces
  2103. :version "21.1")
  2104. (defface rst-block '((t :inherit font-lock-keyword-face))
  2105. "Face used for all syntax marking up a special block."
  2106. :version "24.1"
  2107. :group 'rst-faces)
  2108. (defcustom rst-block-face 'rst-block
  2109. "All syntax marking up a special block."
  2110. :version "24.1"
  2111. :group 'rst-faces
  2112. :type '(face))
  2113. (make-obsolete-variable 'rst-block-face
  2114. "customize the face `rst-block' instead."
  2115. "24.1")
  2116. (defface rst-external '((t :inherit font-lock-type-face))
  2117. "Face used for field names and interpreted text."
  2118. :version "24.1"
  2119. :group 'rst-faces)
  2120. (defcustom rst-external-face 'rst-external
  2121. "Field names and interpreted text."
  2122. :version "24.1"
  2123. :group 'rst-faces
  2124. :type '(face))
  2125. (make-obsolete-variable 'rst-external-face
  2126. "customize the face `rst-external' instead."
  2127. "24.1")
  2128. (defface rst-definition '((t :inherit font-lock-function-name-face))
  2129. "Face used for all other defining constructs."
  2130. :version "24.1"
  2131. :group 'rst-faces)
  2132. (defcustom rst-definition-face 'rst-definition
  2133. "All other defining constructs."
  2134. :version "24.1"
  2135. :group 'rst-faces
  2136. :type '(face))
  2137. (make-obsolete-variable 'rst-definition-face
  2138. "customize the face `rst-definition' instead."
  2139. "24.1")
  2140. ;; XEmacs compatibility (?).
  2141. (defface rst-directive (if (boundp 'font-lock-builtin-face)
  2142. '((t :inherit font-lock-builtin-face))
  2143. '((t :inherit font-lock-preprocessor-face)))
  2144. "Face used for directives and roles."
  2145. :version "24.1"
  2146. :group 'rst-faces)
  2147. (defcustom rst-directive-face 'rst-directive
  2148. "Directives and roles."
  2149. :group 'rst-faces
  2150. :type '(face))
  2151. (make-obsolete-variable 'rst-directive-face
  2152. "customize the face `rst-directive' instead."
  2153. "24.1")
  2154. (defface rst-comment '((t :inherit font-lock-comment-face))
  2155. "Face used for comments."
  2156. :version "24.1"
  2157. :group 'rst-faces)
  2158. (defcustom rst-comment-face 'rst-comment
  2159. "Comments."
  2160. :version "24.1"
  2161. :group 'rst-faces
  2162. :type '(face))
  2163. (make-obsolete-variable 'rst-comment-face
  2164. "customize the face `rst-comment' instead."
  2165. "24.1")
  2166. (defface rst-emphasis1 '((t :inherit italic))
  2167. "Face used for simple emphasis."
  2168. :version "24.1"
  2169. :group 'rst-faces)
  2170. (defcustom rst-emphasis1-face 'rst-emphasis1
  2171. "Simple emphasis."
  2172. :version "24.1"
  2173. :group 'rst-faces
  2174. :type '(face))
  2175. (make-obsolete-variable 'rst-emphasis1-face
  2176. "customize the face `rst-emphasis1' instead."
  2177. "24.1")
  2178. (defface rst-emphasis2 '((t :inherit bold))
  2179. "Face used for double emphasis."
  2180. :version "24.1"
  2181. :group 'rst-faces)
  2182. (defcustom rst-emphasis2-face 'rst-emphasis2
  2183. "Double emphasis."
  2184. :group 'rst-faces
  2185. :type '(face))
  2186. (make-obsolete-variable 'rst-emphasis2-face
  2187. "customize the face `rst-emphasis2' instead."
  2188. "24.1")
  2189. (defface rst-literal '((t :inherit font-lock-string-face))
  2190. "Face used for literal text."
  2191. :version "24.1"
  2192. :group 'rst-faces)
  2193. (defcustom rst-literal-face 'rst-literal
  2194. "Literal text."
  2195. :version "24.1"
  2196. :group 'rst-faces
  2197. :type '(face))
  2198. (make-obsolete-variable 'rst-literal-face
  2199. "customize the face `rst-literal' instead."
  2200. "24.1")
  2201. (defface rst-reference '((t :inherit font-lock-variable-name-face))
  2202. "Face used for references to a definition."
  2203. :version "24.1"
  2204. :group 'rst-faces)
  2205. (defcustom rst-reference-face 'rst-reference
  2206. "References to a definition."
  2207. :version "24.1"
  2208. :group 'rst-faces
  2209. :type '(face))
  2210. (make-obsolete-variable 'rst-reference-face
  2211. "customize the face `rst-reference' instead."
  2212. "24.1")
  2213. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2214. (defgroup rst-faces-defaults nil
  2215. "Values used to generate default faces for section titles on all levels.
  2216. Tweak these if you are content with how section title faces are built in
  2217. general but you do not like the details."
  2218. :group 'rst-faces
  2219. :version "21.1")
  2220. (defun rst-set-level-default (sym val)
  2221. "Set custom var SYM affecting section title text face and recompute the faces."
  2222. (custom-set-default sym val)
  2223. ;; Also defines the faces initially when all values are available
  2224. (and (boundp 'rst-level-face-max)
  2225. (boundp 'rst-level-face-format-light)
  2226. (boundp 'rst-level-face-base-color)
  2227. (boundp 'rst-level-face-step-light)
  2228. (boundp 'rst-level-face-base-light)
  2229. (fboundp 'rst-define-level-faces)
  2230. (rst-define-level-faces)))
  2231. ;; Faces for displaying items on several levels; these definitions define
  2232. ;; different shades of gray where the lightest one (i.e. least contrasting) is
  2233. ;; used for level 1
  2234. (defcustom rst-level-face-max 6
  2235. "Maximum depth of levels for which section title faces are defined."
  2236. :group 'rst-faces-defaults
  2237. :type '(integer)
  2238. :set 'rst-set-level-default)
  2239. (defcustom rst-level-face-base-color "grey"
  2240. "The base name of the color to be used for creating background colors in
  2241. section title faces for all levels."
  2242. :group 'rst-faces-defaults
  2243. :type '(string)
  2244. :set 'rst-set-level-default)
  2245. (defcustom rst-level-face-base-light
  2246. (if (eq frame-background-mode 'dark)
  2247. 15
  2248. 85)
  2249. "The lightness factor for the base color. This value is used for level 1.
  2250. The default depends on whether the value of `frame-background-mode' is
  2251. `dark' or not."
  2252. :group 'rst-faces-defaults
  2253. :type '(integer)
  2254. :set 'rst-set-level-default)
  2255. (defcustom rst-level-face-format-light "%2d"
  2256. "The format for the lightness factor appended to the base name of the color.
  2257. This value is expanded by `format' with an integer."
  2258. :group 'rst-faces-defaults
  2259. :type '(string)
  2260. :set 'rst-set-level-default)
  2261. (defcustom rst-level-face-step-light
  2262. (if (eq frame-background-mode 'dark)
  2263. 7
  2264. -7)
  2265. "The step width to use for the next color.
  2266. The formula
  2267. `rst-level-face-base-light'
  2268. + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
  2269. must result in a color level which appended to `rst-level-face-base-color'
  2270. using `rst-level-face-format-light' results in a valid color such as `grey50'.
  2271. This color is used as background for section title text on level
  2272. `rst-level-face-max'."
  2273. :group 'rst-faces-defaults
  2274. :type '(integer)
  2275. :set 'rst-set-level-default)
  2276. (defcustom rst-adornment-faces-alist
  2277. (let ((alist '((t . font-lock-keyword-face)
  2278. (nil . font-lock-keyword-face)))
  2279. (i 1))
  2280. (while (<= i rst-level-face-max)
  2281. (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
  2282. (setq i (1+ i)))
  2283. alist)
  2284. "Faces for the various adornment types.
  2285. Key is a number (for the section title text of that level),
  2286. t (for transitions) or nil (for section title adornment).
  2287. If you generally do not like how section title text faces are
  2288. set up tweak here. If the general idea is ok for you but you do not like the
  2289. details check the Rst Faces Defaults group."
  2290. :group 'rst-faces
  2291. :type '(alist
  2292. :key-type
  2293. (choice
  2294. (integer
  2295. :tag
  2296. "Section level (may not be bigger than `rst-level-face-max')")
  2297. (boolean :tag "transitions (on) / section title adornment (off)"))
  2298. :value-type (face))
  2299. :set-after '(rst-level-face-max))
  2300. (defun rst-define-level-faces ()
  2301. "Define the faces for the section title text faces from the values."
  2302. ;; All variables used here must be checked in `rst-set-level-default'
  2303. (let ((i 1))
  2304. (while (<= i rst-level-face-max)
  2305. (let ((sym (intern (format "rst-level-%d-face" i)))
  2306. (doc (format "Face for showing section title text at level %d" i))
  2307. (col (format (concat "%s" rst-level-face-format-light)
  2308. rst-level-face-base-color
  2309. (+ (* (1- i) rst-level-face-step-light)
  2310. rst-level-face-base-light))))
  2311. (unless (facep sym)
  2312. (make-empty-face sym)
  2313. (set-face-doc-string sym doc)
  2314. (set-face-background sym col)
  2315. (set sym sym))
  2316. (setq i (1+ i))))))
  2317. (rst-define-level-faces)
  2318. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2319. ;; Font lock
  2320. (defvar rst-use-char-classes
  2321. (string-match "[[:alpha:]]" "b")
  2322. "Non-nil if we can use the character classes in our regexps.")
  2323. (defun rst-font-lock-keywords-function ()
  2324. "Return keywords to highlight in Rst mode according to current settings."
  2325. ;; The reST-links in the comments below all relate to sections in
  2326. ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
  2327. (let* ( ;; This gets big - so let's define some abbreviations
  2328. ;; horizontal white space
  2329. (re-hws "[\t ]")
  2330. ;; beginning of line with possible indentation
  2331. (re-bol (concat "^" re-hws "*"))
  2332. ;; Separates block lead-ins from their content
  2333. (re-blksep1 (concat "\\(" re-hws "+\\|$\\)"))
  2334. ;; explicit markup tag
  2335. (re-emt "\\.\\.")
  2336. ;; explicit markup start
  2337. (re-ems (concat re-emt re-hws "+"))
  2338. ;; inline markup prefix
  2339. (re-imp1 (concat "\\(^\\|" re-hws "\\|[-'\"([{</:]\\)"))
  2340. ;; inline markup suffix
  2341. (re-ims1 (concat "\\(" re-hws "\\|[]-'\")}>/:.,;!?\\]\\|$\\)"))
  2342. ;; symbol character
  2343. (re-sym1 "\\(\\sw\\|\\s_\\)")
  2344. ;; inline markup content begin
  2345. (re-imbeg2 "\\(\\S \\|\\S \\([^")
  2346. ;; There seems to be a bug leading to error "Stack overflow in regexp
  2347. ;; matcher" when "|" or "\\*" are the characters searched for
  2348. (re-imendbeg "\\]\\|\\\\.")
  2349. ;; inline markup content end
  2350. (re-imend (concat re-imendbeg "\\)*[^\t \\\\]\\)"))
  2351. ;; inline markup content without asterisk
  2352. (re-ima2 (concat re-imbeg2 "*" re-imend))
  2353. ;; inline markup content without backquote
  2354. (re-imb2 (concat re-imbeg2 "`" re-imend))
  2355. ;; inline markup content without vertical bar
  2356. (re-imv2 (concat re-imbeg2 "|" re-imend))
  2357. ;; Supported URI schemes
  2358. (re-uris1 "\\(acap\\|cid\\|data\\|dav\\|fax\\|file\\|ftp\\|gopher\\|http\\|https\\|imap\\|ldap\\|mailto\\|mid\\|modem\\|news\\|nfs\\|nntp\\|pop\\|prospero\\|rtsp\\|service\\|sip\\|tel\\|telnet\\|tip\\|urn\\|vemmi\\|wais\\)")
  2359. ;; Line starting with adornment and optional whitespace; complete
  2360. ;; adornment is in (match-string 1); there must be at least 3
  2361. ;; characters because otherwise explicit markup start would be
  2362. ;; recognized
  2363. (re-ado2 (concat "^\\(\\(["
  2364. (if rst-use-char-classes
  2365. "^[:word:][:space:][:cntrl:]" "^\\w \t\x00-\x1F")
  2366. "]\\)\\2\\2+\\)" re-hws "*$"))
  2367. )
  2368. (list
  2369. ;; FIXME: Block markup is not recognized in blocks after explicit markup
  2370. ;; start
  2371. ;; Simple `Body Elements`_
  2372. ;; `Bullet Lists`_
  2373. `(,(concat re-bol "\\([-*+]" re-blksep1 "\\)")
  2374. 1 rst-block-face)
  2375. ;; `Enumerated Lists`_
  2376. `(,(concat re-bol "\\((?\\(#\\|[0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]"
  2377. re-blksep1 "\\)")
  2378. 1 rst-block-face)
  2379. ;; `Definition Lists`_ FIXME: missing
  2380. ;; `Field Lists`_
  2381. `(,(concat re-bol "\\(:[^:\n]+:\\)" re-blksep1)
  2382. 1 rst-external-face)
  2383. ;; `Option Lists`_
  2384. `(,(concat re-bol "\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*"
  2385. "\\([ =]\\S +\\)?\\)\\(,[\t ]\\)?\\)+\\)\\($\\|[\t ]\\{2\\}\\)")
  2386. 1 rst-block-face)
  2387. ;; `Tables`_ FIXME: missing
  2388. ;; All the `Explicit Markup Blocks`_
  2389. ;; `Footnotes`_ / `Citations`_
  2390. `(,(concat re-bol "\\(" re-ems "\\[[^[\n]+\\]\\)" re-blksep1)
  2391. 1 rst-definition-face)
  2392. ;; `Directives`_ / `Substitution Definitions`_
  2393. `(,(concat re-bol "\\(" re-ems "\\)\\(\\(|[^|\n]+|[\t ]+\\)?\\)\\("
  2394. re-sym1 "+::\\)" re-blksep1)
  2395. (1 rst-directive-face)
  2396. (2 rst-definition-face)
  2397. (4 rst-directive-face))
  2398. ;; `Hyperlink Targets`_
  2399. `(,(concat re-bol "\\(" re-ems "_\\([^:\\`\n]\\|\\\\.\\|`[^`\n]+`\\)+:\\)"
  2400. re-blksep1)
  2401. 1 rst-definition-face)
  2402. `(,(concat re-bol "\\(__\\)" re-blksep1)
  2403. 1 rst-definition-face)
  2404. ;; All `Inline Markup`_
  2405. ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
  2406. ;; `Strong Emphasis`_
  2407. `(,(concat re-imp1 "\\(\\*\\*" re-ima2 "\\*\\*\\)" re-ims1)
  2408. 2 rst-emphasis2-face)
  2409. ;; `Emphasis`_
  2410. `(,(concat re-imp1 "\\(\\*" re-ima2 "\\*\\)" re-ims1)
  2411. 2 rst-emphasis1-face)
  2412. ;; `Inline Literals`_
  2413. `(,(concat re-imp1 "\\(``" re-imb2 "``\\)" re-ims1)
  2414. 2 rst-literal-face)
  2415. ;; `Inline Internal Targets`_
  2416. `(,(concat re-imp1 "\\(_`" re-imb2 "`\\)" re-ims1)
  2417. 2 rst-definition-face)
  2418. ;; `Hyperlink References`_
  2419. ;; FIXME: `Embedded URIs`_ not considered
  2420. `(,(concat re-imp1 "\\(\\(`" re-imb2 "`\\|\\(\\sw\\(\\sw\\|-\\)+\\sw\\)\\)__?\\)" re-ims1)
  2421. 2 rst-reference-face)
  2422. ;; `Interpreted Text`_
  2423. `(,(concat re-imp1 "\\(\\(:" re-sym1 "+:\\)?\\)\\(`" re-imb2 "`\\)\\(\\(:"
  2424. re-sym1 "+:\\)?\\)" re-ims1)
  2425. (2 rst-directive-face)
  2426. (5 rst-external-face)
  2427. (8 rst-directive-face))
  2428. ;; `Footnote References`_ / `Citation References`_
  2429. `(,(concat re-imp1 "\\(\\[[^]]+\\]_\\)" re-ims1)
  2430. 2 rst-reference-face)
  2431. ;; `Substitution References`_
  2432. `(,(concat re-imp1 "\\(|" re-imv2 "|\\)" re-ims1)
  2433. 2 rst-reference-face)
  2434. ;; `Standalone Hyperlinks`_
  2435. `(;; FIXME: This takes it easy by using a whitespace as delimiter
  2436. ,(concat re-imp1 "\\(" re-uris1 ":\\S +\\)" re-ims1)
  2437. 2 rst-definition-face)
  2438. `(,(concat re-imp1 "\\(" re-sym1 "+@" re-sym1 "+\\)" re-ims1)
  2439. 2 rst-definition-face)
  2440. ;; Do all block fontification as late as possible so 'append works
  2441. ;; Sections_ / Transitions_
  2442. (append
  2443. (list
  2444. re-ado2)
  2445. (if (not rst-mode-lazy)
  2446. '(1 rst-block-face)
  2447. (list
  2448. (list 'rst-font-lock-handle-adornment
  2449. '(progn
  2450. (setq rst-font-lock-adornment-point (match-end 1))
  2451. (point-max))
  2452. nil
  2453. (list 1 '(cdr (assoc nil rst-adornment-faces-alist))
  2454. 'append t)
  2455. (list 2 '(cdr (assoc rst-font-lock-level
  2456. rst-adornment-faces-alist))
  2457. 'append t)
  2458. (list 3 '(cdr (assoc nil rst-adornment-faces-alist))
  2459. 'append t)))))
  2460. ;; `Comments`_
  2461. (append
  2462. (list
  2463. (concat re-bol "\\(" re-ems "\\)\[^[|_]\\([^:\n]\\|:\\([^:\n]\\|$\\)\\)*$")
  2464. '(1 rst-comment-face))
  2465. (if rst-mode-lazy
  2466. (list
  2467. (list 'rst-font-lock-find-unindented-line
  2468. '(progn
  2469. (setq rst-font-lock-indentation-point (match-end 1))
  2470. (point-max))
  2471. nil
  2472. '(0 rst-comment-face append)))))
  2473. (append
  2474. (list
  2475. (concat re-bol "\\(" re-emt "\\)\\(\\s *\\)$")
  2476. '(1 rst-comment-face)
  2477. '(2 rst-comment-face))
  2478. (if rst-mode-lazy
  2479. (list
  2480. (list 'rst-font-lock-find-unindented-line
  2481. '(progn
  2482. (setq rst-font-lock-indentation-point 'next)
  2483. (point-max))
  2484. nil
  2485. '(0 rst-comment-face append)))))
  2486. ;; `Literal Blocks`_
  2487. (append
  2488. (list
  2489. (concat re-bol "\\(\\([^.\n]\\|\\.[^.\n]\\).*\\)?\\(::\\)$")
  2490. '(3 rst-block-face))
  2491. (if rst-mode-lazy
  2492. (list
  2493. (list 'rst-font-lock-find-unindented-line
  2494. '(progn
  2495. (setq rst-font-lock-indentation-point t)
  2496. (point-max))
  2497. nil
  2498. '(0 rst-literal-face append)))))
  2499. ;; `Doctest Blocks`_
  2500. (append
  2501. (list
  2502. (concat re-bol "\\(>>>\\|\\.\\.\\.\\)\\(.+\\)")
  2503. '(1 rst-block-face)
  2504. '(2 rst-literal-face)))
  2505. )))
  2506. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2507. ;; Indented blocks
  2508. (defun rst-forward-indented-block (&optional column limit)
  2509. "Move forward across one indented block.
  2510. Find the next non-empty line which is not indented at least to COLUMN (defaults
  2511. to the column of the point). Moves point to first character of this line or the
  2512. first empty line immediately before it and returns that position. If there is
  2513. no such line before LIMIT (defaults to the end of the buffer) returns nil and
  2514. point is not moved."
  2515. (interactive)
  2516. (let ((clm (or column (current-column)))
  2517. (start (point))
  2518. fnd beg cand)
  2519. (if (not limit)
  2520. (setq limit (point-max)))
  2521. (save-match-data
  2522. (while (and (not fnd) (< (point) limit))
  2523. (forward-line 1)
  2524. (when (< (point) limit)
  2525. (setq beg (point))
  2526. (if (looking-at "\\s *$")
  2527. (setq cand (or cand beg)) ; An empty line is a candidate
  2528. (move-to-column clm)
  2529. ;; FIXME: No indentation [(zerop clm)] must be handled in some
  2530. ;; useful way - though it is not clear what this should mean at all
  2531. (if (string-match
  2532. "^\\s *$" (buffer-substring-no-properties beg (point)))
  2533. (setq cand nil) ; An indented line resets a candidate
  2534. (setq fnd (or cand beg)))))))
  2535. (goto-char (or fnd start))
  2536. fnd))
  2537. ;; Stores the point where the current indentation ends if a number. If `next'
  2538. ;; indicates `rst-font-lock-find-unindented-line' shall take the indentation
  2539. ;; from the next line if this is not empty. If non-nil indicates
  2540. ;; `rst-font-lock-find-unindented-line' shall take the indentation from the
  2541. ;; next non-empty line. Also used as a trigger for
  2542. ;; `rst-font-lock-find-unindented-line'.
  2543. (defvar rst-font-lock-indentation-point nil)
  2544. (defun rst-font-lock-find-unindented-line (limit)
  2545. (let* ((ind-pnt rst-font-lock-indentation-point)
  2546. (beg-pnt ind-pnt))
  2547. ;; May run only once - enforce this
  2548. (setq rst-font-lock-indentation-point nil)
  2549. (when (and ind-pnt (not (numberp ind-pnt)))
  2550. ;; Find indentation point in next line if any
  2551. (setq ind-pnt
  2552. (save-excursion
  2553. (save-match-data
  2554. (if (eq ind-pnt 'next)
  2555. (when (and (zerop (forward-line 1)) (< (point) limit))
  2556. (setq beg-pnt (point))
  2557. (when (not (looking-at "\\s *$"))
  2558. (looking-at "\\s *")
  2559. (match-end 0)))
  2560. (while (and (zerop (forward-line 1)) (< (point) limit)
  2561. (looking-at "\\s *$")))
  2562. (when (< (point) limit)
  2563. (setq beg-pnt (point))
  2564. (looking-at "\\s *")
  2565. (match-end 0)))))))
  2566. (when ind-pnt
  2567. (goto-char ind-pnt)
  2568. ;; Always succeeds because the limit set by PRE-MATCH-FORM is the
  2569. ;; ultimate point to find
  2570. (goto-char (or (rst-forward-indented-block nil limit) limit))
  2571. (save-excursion
  2572. ;; Include subsequent empty lines in the font-lock block,
  2573. ;; in case the user subsequently changes the indentation of the next
  2574. ;; non-empty line to move it into the indented element.
  2575. (skip-chars-forward " \t\n")
  2576. (put-text-property beg-pnt (point) 'font-lock-multiline t))
  2577. (set-match-data (list beg-pnt (point)))
  2578. t)))
  2579. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2580. ;; Adornments
  2581. (defvar rst-font-lock-adornment-point nil
  2582. "Stores the point where the current adornment ends.
  2583. Also used as a trigger for `rst-font-lock-handle-adornment'.")
  2584. ;; Here `rst-font-lock-handle-adornment' stores the section level of the
  2585. ;; current adornment or t for a transition.
  2586. (defvar rst-font-lock-level nil)
  2587. ;; FIXME: It would be good if this could be used to markup section titles of
  2588. ;; given level with a special key; it would be even better to be able to
  2589. ;; customize this so it can be used for a generally available personal style
  2590. ;;
  2591. ;; FIXME: There should be some way to reset and reload this variable - probably
  2592. ;; a special key
  2593. ;;
  2594. ;; FIXME: Some support for `outline-mode' would be nice which should be based
  2595. ;; on this information
  2596. (defvar rst-adornment-level-alist nil
  2597. "Associates adornments with section levels.
  2598. The key is a two character string. The first character is the adornment
  2599. character. The second character distinguishes underline section titles (`u')
  2600. from overline/underline section titles (`o'). The value is the section level.
  2601. This is made buffer local on start and adornments found during font lock are
  2602. entered.")
  2603. ;; Returns section level for adornment key KEY. Adds new section level if KEY
  2604. ;; is not found and ADD. If KEY is not a string it is simply returned.
  2605. (defun rst-adornment-level (key &optional add)
  2606. (let ((fnd (assoc key rst-adornment-level-alist))
  2607. (new 1))
  2608. (cond
  2609. ((not (stringp key))
  2610. key)
  2611. (fnd
  2612. (cdr fnd))
  2613. (add
  2614. (while (rassoc new rst-adornment-level-alist)
  2615. (setq new (1+ new)))
  2616. (setq rst-adornment-level-alist
  2617. (append rst-adornment-level-alist (list (cons key new))))
  2618. new))))
  2619. ;; Classifies adornment for section titles and transitions. ADORNMENT is the
  2620. ;; complete adornment string as found in the buffer. END is the point after the
  2621. ;; last character of ADORNMENT. For overline section adornment LIMIT limits the
  2622. ;; search for the matching underline. Returns a list. The first entry is t for
  2623. ;; a transition, or a key string for `rst-adornment-level' for a section title.
  2624. ;; The following eight values forming four match groups as can be used for
  2625. ;; `set-match-data'. First match group contains the maximum points of the whole
  2626. ;; construct. Second and last match group matched pure section title adornment
  2627. ;; while third match group matched the section title text or the transition.
  2628. ;; Each group but the first may or may not exist.
  2629. (defun rst-classify-adornment (adornment end limit)
  2630. (save-excursion
  2631. (save-match-data
  2632. (goto-char end)
  2633. (let ((ado-ch (aref adornment 0))
  2634. (ado-re (regexp-quote adornment))
  2635. (end-pnt (point))
  2636. (beg-pnt (progn
  2637. (forward-line 0)
  2638. (point)))
  2639. (nxt-emp
  2640. (save-excursion
  2641. (or (not (zerop (forward-line 1)))
  2642. (looking-at "\\s *$"))))
  2643. (prv-emp
  2644. (save-excursion
  2645. (or (not (zerop (forward-line -1)))
  2646. (looking-at "\\s *$"))))
  2647. key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
  2648. (cond
  2649. ((and nxt-emp prv-emp)
  2650. ;; A transition
  2651. (setq key t)
  2652. (setq beg-txt beg-pnt)
  2653. (setq end-txt end-pnt))
  2654. (prv-emp
  2655. ;; An overline
  2656. (setq key (concat (list ado-ch) "o"))
  2657. (setq beg-ovr beg-pnt)
  2658. (setq end-ovr end-pnt)
  2659. (forward-line 1)
  2660. (setq beg-txt (point))
  2661. (while (and (< (point) limit) (not end-txt))
  2662. (if (looking-at "\\s *$")
  2663. ;; No underline found
  2664. (setq end-txt (1- (point)))
  2665. (when (looking-at (concat "\\(" ado-re "\\)\\s *$"))
  2666. (setq end-und (match-end 1))
  2667. (setq beg-und (point))
  2668. (setq end-txt (1- beg-und))))
  2669. (forward-line 1)))
  2670. (t
  2671. ;; An underline
  2672. (setq key (concat (list ado-ch) "u"))
  2673. (setq beg-und beg-pnt)
  2674. (setq end-und end-pnt)
  2675. (setq end-txt (1- beg-und))
  2676. (setq beg-txt (progn
  2677. (if (re-search-backward "^\\s *$" 1 'move)
  2678. (forward-line 1))
  2679. (point)))))
  2680. (list key
  2681. (or beg-ovr beg-txt beg-und)
  2682. (or end-und end-txt end-und)
  2683. beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))
  2684. ;; Handles adornments for font-locking section titles and transitions. Returns
  2685. ;; three match groups. First and last match group matched pure overline /
  2686. ;; underline adornment while second group matched section title text. Each
  2687. ;; group may not exist.
  2688. (defun rst-font-lock-handle-adornment (limit)
  2689. (let ((ado-pnt rst-font-lock-adornment-point))
  2690. ;; May run only once - enforce this
  2691. (setq rst-font-lock-adornment-point nil)
  2692. (if ado-pnt
  2693. (let* ((ado (rst-classify-adornment (match-string-no-properties 1)
  2694. ado-pnt limit))
  2695. (key (car ado))
  2696. (mtc (cdr ado)))
  2697. (setq rst-font-lock-level (rst-adornment-level key t))
  2698. (goto-char (nth 1 mtc))
  2699. (put-text-property (nth 0 mtc) (nth 1 mtc) 'font-lock-multiline t)
  2700. (set-match-data mtc)
  2701. t))))
  2702. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2703. ;; Support for conversion from within Emacs
  2704. (defgroup rst-compile nil
  2705. "Settings for support of conversion of reStructuredText
  2706. document with \\[rst-compile]."
  2707. :group 'rst
  2708. :version "21.1")
  2709. (defcustom rst-compile-toolsets
  2710. `((html ,(if (executable-find "rst2html.py") "rst2html.py" "rst2html")
  2711. ".html" nil)
  2712. (latex ,(if (executable-find "rst2latex.py") "rst2latex.py" "rst2latex")
  2713. ".tex" nil)
  2714. (newlatex ,(if (executable-find "rst2newlatex.py") "rst2newlatex.py"
  2715. "rst2newlatex")
  2716. ".tex" nil)
  2717. (pseudoxml ,(if (executable-find "rst2pseudoxml.py") "rst2pseudoxml.py"
  2718. "rst2pseudoxml")
  2719. ".xml" nil)
  2720. (xml ,(if (executable-find "rst2xml.py") "rst2xml.py" "rst2xml")
  2721. ".xml" nil)
  2722. (pdf ,(if (executable-find "rst2pdf.py") "rst2pdf.py" "rst2pdf")
  2723. ".pdf" nil)
  2724. (s5 ,(if (executable-find "rst2s5.py") "rst2s5.py" "rst2s5")
  2725. ".html" nil))
  2726. "Table describing the command to use for each toolset.
  2727. An association list of the toolset to a list of the (command to use,
  2728. extension of produced filename, options to the tool (nil or a
  2729. string)) to be used for converting the document."
  2730. :type '(alist :options (html latex newlatex pseudoxml xml pdf s5)
  2731. :key-type symbol
  2732. :value-type (list :tag "Specification"
  2733. (file :tag "Command")
  2734. (string :tag "File extension")
  2735. (choice :tag "Command options"
  2736. (const :tag "No options" nil)
  2737. (string :tag "Options"))))
  2738. :group 'rst
  2739. :version "24.1")
  2740. ;; Note for Python programmers not familiar with association lists: you can set
  2741. ;; values in an alists like this, e.g. :
  2742. ;; (setcdr (assq 'html rst-compile-toolsets)
  2743. ;; '("rst2html.py" ".htm" "--stylesheet=/docutils.css"))
  2744. (defvar rst-compile-primary-toolset 'html
  2745. "The default toolset for `rst-compile'.")
  2746. (defvar rst-compile-secondary-toolset 'latex
  2747. "The default toolset for `rst-compile' with a prefix argument.")
  2748. (defun rst-compile-find-conf ()
  2749. "Look for the configuration file in the parents of the current path."
  2750. (interactive)
  2751. (let ((file-name "docutils.conf")
  2752. (buffer-file (buffer-file-name)))
  2753. ;; Move up in the dir hierarchy till we find a change log file.
  2754. (let* ((dir (file-name-directory buffer-file))
  2755. (prevdir nil))
  2756. (while (and (or (not (string= dir prevdir))
  2757. (setq dir nil)
  2758. nil)
  2759. (not (file-exists-p (concat dir file-name))))
  2760. ;; Move up to the parent dir and try again.
  2761. (setq prevdir dir)
  2762. (setq dir (expand-file-name (file-name-directory
  2763. (directory-file-name
  2764. (file-name-directory dir)))))
  2765. )
  2766. (or (and dir (concat dir file-name)) nil)
  2767. )))
  2768. (require 'compile)
  2769. (defun rst-compile (&optional pfxarg)
  2770. "Compile command to convert reST document into some output file.
  2771. Attempts to find configuration file, if it can, overrides the
  2772. options. There are two commands to choose from, with a prefix
  2773. argument, select the alternative toolset."
  2774. (interactive "P")
  2775. ;; Note: maybe we want to check if there is a Makefile too and not do anything
  2776. ;; if that is the case. I dunno.
  2777. (let* ((toolset (cdr (assq (if pfxarg
  2778. rst-compile-secondary-toolset
  2779. rst-compile-primary-toolset)
  2780. rst-compile-toolsets)))
  2781. (command (car toolset))
  2782. (extension (cadr toolset))
  2783. (options (caddr toolset))
  2784. (conffile (rst-compile-find-conf))
  2785. (bufname (file-name-nondirectory buffer-file-name))
  2786. (outname (file-name-sans-extension bufname)))
  2787. ;; Set compile-command before invocation of compile.
  2788. (set (make-local-variable 'compile-command)
  2789. (mapconcat 'identity
  2790. (list command
  2791. (or options "")
  2792. (if conffile
  2793. (concat "--config=\"" conffile "\"")
  2794. "")
  2795. bufname
  2796. (concat outname extension))
  2797. " "))
  2798. ;; Invoke the compile command.
  2799. (if (or compilation-read-command current-prefix-arg)
  2800. (call-interactively 'compile)
  2801. (compile compile-command))
  2802. ))
  2803. (defun rst-compile-alt-toolset ()
  2804. "Compile command with the alternative toolset."
  2805. (interactive)
  2806. (rst-compile 't))
  2807. (defun rst-compile-pseudo-region ()
  2808. "Show the pseudo-XML rendering of the current active region,
  2809. or of the entire buffer, if the region is not selected."
  2810. (interactive)
  2811. (with-output-to-temp-buffer "*pseudoxml*"
  2812. (shell-command-on-region
  2813. (if mark-active (region-beginning) (point-min))
  2814. (if mark-active (region-end) (point-max))
  2815. (cadr (assq 'pseudoxml rst-compile-toolsets))
  2816. standard-output)))
  2817. (defvar rst-pdf-program "xpdf"
  2818. "Program used to preview PDF files.")
  2819. (defun rst-compile-pdf-preview ()
  2820. "Convert the document to a PDF file and launch a preview program."
  2821. (interactive)
  2822. (let* ((tmp-filename (make-temp-file "rst-out" nil ".pdf"))
  2823. (command (format "%s %s %s && %s %s"
  2824. (cadr (assq 'pdf rst-compile-toolsets))
  2825. buffer-file-name tmp-filename
  2826. rst-pdf-program tmp-filename)))
  2827. (start-process-shell-command "rst-pdf-preview" nil command)
  2828. ;; Note: you could also use (compile command) to view the compilation
  2829. ;; output.
  2830. ))
  2831. (defvar rst-slides-program "firefox"
  2832. "Program used to preview S5 slides.")
  2833. (defun rst-compile-slides-preview ()
  2834. "Convert the document to an S5 slide presentation and launch a preview program."
  2835. (interactive)
  2836. (let* ((tmp-filename (make-temp-file "rst-slides" nil ".html"))
  2837. (command (format "%s %s %s && %s %s"
  2838. (cadr (assq 's5 rst-compile-toolsets))
  2839. buffer-file-name tmp-filename
  2840. rst-slides-program tmp-filename)))
  2841. (start-process-shell-command "rst-slides-preview" nil command)
  2842. ;; Note: you could also use (compile command) to view the compilation
  2843. ;; output.
  2844. ))
  2845. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2846. ;;
  2847. ;; Generic text functions that are more convenient than the defaults.
  2848. ;;
  2849. (defun rst-replace-lines (fromchar tochar)
  2850. "Replace flush-left lines, consisting of multiple FROMCHAR characters,
  2851. with equal-length lines of TOCHAR."
  2852. (interactive "\
  2853. cSearch for flush-left lines of char:
  2854. cand replace with char: ")
  2855. (save-excursion
  2856. (let ((searchre (concat "^" (regexp-quote (string fromchar)) "+\\( *\\)$"))
  2857. (found 0))
  2858. (while (search-forward-regexp searchre nil t)
  2859. (setq found (1+ found))
  2860. (goto-char (match-beginning 1))
  2861. (let ((width (current-column)))
  2862. (rst-delete-entire-line)
  2863. (insert-char tochar width)))
  2864. (message (format "%d lines replaced." found)))))
  2865. (defun rst-join-paragraph ()
  2866. "Join lines in current paragraph into one line, removing end-of-lines."
  2867. (interactive)
  2868. (let ((fill-column 65000)) ; some big number
  2869. (call-interactively 'fill-paragraph)))
  2870. (defun rst-force-fill-paragraph ()
  2871. "Fill paragraph at point, first joining the paragraph's lines into one.
  2872. This is useful for filling list item paragraphs."
  2873. (interactive)
  2874. (rst-join-paragraph)
  2875. (fill-paragraph nil))
  2876. ;; Generic character repeater function.
  2877. ;; For sections, better to use the specialized function above, but this can
  2878. ;; be useful for creating separators.
  2879. (defun rst-repeat-last-character (&optional tofill)
  2880. "Fill the current line up to the length of the preceding line (if not
  2881. empty), using the last character on the current line. If the preceding line is
  2882. empty, we use the `fill-column'.
  2883. If a prefix argument is provided, use the next line rather than the preceding
  2884. line.
  2885. If the current line is longer than the desired length, shave the characters off
  2886. the current line to fit the desired length.
  2887. As an added convenience, if the command is repeated immediately, the alternative
  2888. column is used (fill-column vs. end of previous/next line)."
  2889. (interactive)
  2890. (let* ((curcol (current-column))
  2891. (curline (+ (count-lines (point-min) (point))
  2892. (if (eq curcol 0) 1 0)))
  2893. (lbp (line-beginning-position 0))
  2894. (prevcol (if (and (= curline 1) (not current-prefix-arg))
  2895. fill-column
  2896. (save-excursion
  2897. (forward-line (if current-prefix-arg 1 -1))
  2898. (end-of-line)
  2899. (skip-chars-backward " \t" lbp)
  2900. (let ((cc (current-column)))
  2901. (if (= cc 0) fill-column cc)))))
  2902. (rightmost-column
  2903. (cond (tofill fill-column)
  2904. ((equal last-command 'rst-repeat-last-character)
  2905. (if (= curcol fill-column) prevcol fill-column))
  2906. (t (save-excursion
  2907. (if (= prevcol 0) fill-column prevcol)))
  2908. )) )
  2909. (end-of-line)
  2910. (if (> (current-column) rightmost-column)
  2911. ;; shave characters off the end
  2912. (delete-region (- (point)
  2913. (- (current-column) rightmost-column))
  2914. (point))
  2915. ;; fill with last characters
  2916. (insert-char (preceding-char)
  2917. (- rightmost-column (current-column))))
  2918. ))
  2919. (defun rst-portable-mark-active-p ()
  2920. "A portable function that returns non-nil if the mark is active."
  2921. (cond
  2922. ((fboundp 'region-active-p) (region-active-p))
  2923. ((boundp 'transient-mark-mode) (and transient-mark-mode mark-active))
  2924. (t mark-active)))
  2925. (provide 'rst)
  2926. ;;; rst.el ends here