org-list.el 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  1. ;;; org-list.el --- Plain lists for Org-mode
  2. ;;
  3. ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
  4. ;; Free Software Foundation, Inc.
  5. ;;
  6. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Bastien Guerry <bzg AT altern DOT org>
  8. ;; Keywords: outlines, hypermedia, calendar, wp
  9. ;; Homepage: http://orgmode.org
  10. ;; Version: 7.4
  11. ;;
  12. ;; This file is part of GNU Emacs.
  13. ;;
  14. ;; GNU Emacs is free software: you can redistribute it and/or modify
  15. ;; it under the terms of the GNU General Public License as published by
  16. ;; the Free Software Foundation, either version 3 of the License, or
  17. ;; (at your option) any later version.
  18. ;; GNU Emacs is distributed in the hope that it will be useful,
  19. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. ;; GNU General Public License for more details.
  22. ;; You should have received a copy of the GNU General Public License
  23. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  24. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  25. ;;
  26. ;;; Commentary:
  27. ;; This file contains the code dealing with plain lists in Org-mode.
  28. ;; The fundamental idea behind lists work is to use structures. A
  29. ;; structure is a snapshot of the list, in the shape of data tree (see
  30. ;; `org-list-struct').
  31. ;; Once the list structure is stored, it is possible to make changes
  32. ;; directly on it or get useful information about the list, with the
  33. ;; two helper functions, namely `org-list-parents-alist' and
  34. ;; `org-list-prevs-alist', and using accessors or methods.
  35. ;; Structure is eventually applied to the buffer with
  36. ;; `org-list-write-struct'. This function repairs (bullets,
  37. ;; indentation, checkboxes) the structure before applying it. It
  38. ;; should be called near the end of any function working on
  39. ;; structures.
  40. ;; Thus, a function applying to lists should usually follow this
  41. ;; template:
  42. ;; 1. Verify point is in a list and grab item beginning (with the same
  43. ;; function `org-in-item-p'). If the function requires the cursor
  44. ;; to be at item's bullet, `org-at-item-p' is more selective. If
  45. ;; the cursor is amidst the buffer, it is possible to find the
  46. ;; closest item with `org-list-search-backward', or
  47. ;; `org-list-search-forward', applied to `org-item-beginning-re'.
  48. ;; 2. Get list structure with `org-list-struct'.
  49. ;; 3. Compute one, or both, helper functions,
  50. ;; (`org-list-parents-alist', `org-list-prevs-alist') depending on
  51. ;; needed accessors.
  52. ;; 4. Proceed with the modifications, using methods and accessors.
  53. ;; 5. Verify and apply structure to buffer, using
  54. ;; `org-list-write-struct'. Possibly use
  55. ;; `org-update-checkbox-count-maybe' if checkboxes might have been
  56. ;; modified.
  57. ;; Computing a list structure can be a costly operation on huge lists
  58. ;; (a few thousand lines long). Thus, code should follow the rule :
  59. ;; "collect once, use many". As a corollary, it is usally a bad idea
  60. ;; to use directly an interactive function inside the code, as those,
  61. ;; being independant entities, read the whole list structure another
  62. ;; time.
  63. ;;; Code:
  64. (eval-when-compile
  65. (require 'cl))
  66. (require 'org-macs)
  67. (require 'org-compat)
  68. (defvar org-blank-before-new-entry)
  69. (defvar org-complex-heading-regexp)
  70. (defvar org-drawer-regexp)
  71. (defvar org-drawers)
  72. (defvar org-M-RET-may-split-line)
  73. (defvar org-odd-levels-only)
  74. (defvar org-outline-regexp)
  75. (defvar org-ts-regexp)
  76. (defvar org-ts-regexp-both)
  77. (declare-function org-at-heading-p "org" (&optional ignored))
  78. (declare-function org-back-over-empty-lines "org" ())
  79. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  80. (declare-function org-combine-plists "org" (&rest plists))
  81. (declare-function org-count "org" (cl-item cl-seq))
  82. (declare-function org-current-level "org" ())
  83. (declare-function org-entry-get "org"
  84. (pom property &optional inherit literal-nil))
  85. (declare-function org-get-indentation "org" (&optional line))
  86. (declare-function org-icompleting-read "org" (&rest args))
  87. (declare-function org-in-regexp "org" (re &optional nlines visually))
  88. (declare-function org-in-regexps-block-p "org"
  89. (start-re end-re &optional bound))
  90. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  91. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  92. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  93. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  94. (declare-function org-invisible-p "org" ())
  95. (declare-function org-level-increment "org" ())
  96. (declare-function org-narrow-to-subtree "org" ())
  97. (declare-function org-on-heading-p "org" (&optional invisible-ok))
  98. (declare-function org-previous-line-empty-p "org" ())
  99. (declare-function org-remove-if "org" (predicate seq))
  100. (declare-function org-show-subtree "org" ())
  101. (declare-function org-time-string-to-seconds "org" (s))
  102. (declare-function org-timer-hms-to-secs "org-timer" (hms))
  103. (declare-function org-timer-item "org-timer" (&optional arg))
  104. (declare-function org-trim "org" (s))
  105. (declare-function org-uniquify "org" (list))
  106. (declare-function outline-next-heading "outline" ())
  107. (declare-function outline-previous-heading "outline" ())
  108. ;;; Configuration variables
  109. (defgroup org-plain-lists nil
  110. "Options concerning plain lists in Org-mode."
  111. :tag "Org Plain lists"
  112. :group 'org-structure)
  113. (defcustom org-cycle-include-plain-lists t
  114. "When t, make TAB cycle visibility on plain list items.
  115. Cycling plain lists works only when the cursor is on a plain list
  116. item. When the cursor is on an outline heading, plain lists are
  117. treated as text. This is the most stable way of handling this,
  118. which is why it is the default.
  119. When this is the symbol `integrate', then during cycling, plain
  120. list items will *temporarily* be interpreted as outline headlines
  121. with a level given by 1000+i where i is the indentation of the
  122. bullet. This setting can lead to strange effects when switching
  123. visibility to `children', because the first \"child\" in a
  124. subtree decides what children should be listed. If that first
  125. \"child\" is a plain list item with an implied large level
  126. number, all true children and grand children of the outline
  127. heading will be exposed in a children' view."
  128. :group 'org-plain-lists
  129. :type '(choice
  130. (const :tag "Never" nil)
  131. (const :tag "With cursor in plain list (recommended)" t)
  132. (const :tag "As children of outline headings" integrate)))
  133. (defcustom org-list-demote-modify-bullet nil
  134. "Default bullet type installed when demoting an item.
  135. This is an association list, for each bullet type, this alist will point
  136. to the bullet that should be used when this item is demoted.
  137. For example,
  138. (setq org-list-demote-modify-bullet
  139. '((\"+\" . \"-\") (\"-\" . \"+\") (\"*\" . \"+\")))
  140. will make
  141. + Movies
  142. + Silence of the Lambs
  143. + My Cousin Vinny
  144. + Books
  145. + The Hunt for Red October
  146. + The Road to Omaha
  147. into
  148. + Movies
  149. - Silence of the Lambs
  150. - My Cousin Vinny
  151. + Books
  152. - The Hunt for Red October
  153. - The Road to Omaha"
  154. :group 'org-plain-lists
  155. :type '(repeat
  156. (cons
  157. (choice :tag "If the current bullet is "
  158. (const "-")
  159. (const "+")
  160. (const "*")
  161. (const "1.")
  162. (const "1)"))
  163. (choice :tag "demotion will change it to"
  164. (const "-")
  165. (const "+")
  166. (const "*")
  167. (const "1.")
  168. (const "1)")))))
  169. (defcustom org-plain-list-ordered-item-terminator t
  170. "The character that makes a line with leading number an ordered list item.
  171. Valid values are ?. and ?\). To get both terminators, use t. While
  172. ?. may look nicer, it creates the danger that a line with leading
  173. number may be incorrectly interpreted as an item. ?\) therefore is
  174. the safe choice."
  175. :group 'org-plain-lists
  176. :type '(choice (const :tag "dot like in \"2.\"" ?.)
  177. (const :tag "paren like in \"2)\"" ?\))
  178. (const :tab "both" t)))
  179. (defcustom org-alphabetical-lists nil
  180. "Non-nil means single character alphabetical bullets are allowed.
  181. Both uppercase and lowercase are handled. Lists with more than 26
  182. items will fallback to standard numbering. Alphabetical counters
  183. like \"[@c]\" will be recognized."
  184. :group 'org-plain-lists
  185. :type 'boolean)
  186. (defcustom org-list-two-spaces-after-bullet-regexp nil
  187. "A regular expression matching bullets that should have 2 spaces after them.
  188. When nil, no bullet will have two spaces after them.
  189. When a string, it will be used as a regular expression. When the
  190. bullet type of a list is changed, the new bullet type will be
  191. matched against this regexp. If it matches, there will be two
  192. spaces instead of one after the bullet in each item of the list."
  193. :group 'org-plain-lists
  194. :type '(choice
  195. (const :tag "never" nil)
  196. (regexp)))
  197. (defcustom org-list-ending-method 'both
  198. "Determine where plain lists should end.
  199. Valid values are: `regexp', `indent' or `both'.
  200. When set to `regexp', Org will look into two variables,
  201. `org-empty-line-terminates-plain-lists' and the more general
  202. `org-list-end-regexp', to determine what will end lists.
  203. When set to `indent', a list will end whenever a line following
  204. an item, but not starting one, is less or equally indented than
  205. the first item of the list.
  206. When set to `both', each of the preceding methods is applied to
  207. determine lists endings. This is the default method."
  208. :group 'org-plain-lists
  209. :type '(choice
  210. (const :tag "With a regexp defining ending" regexp)
  211. (const :tag "With indentation of regular (no bullet) text" indent)
  212. (const :tag "With both methods" both)))
  213. (defcustom org-empty-line-terminates-plain-lists nil
  214. "Non-nil means an empty line ends all plain list levels.
  215. This variable only makes sense if `org-list-ending-method' is set
  216. to `regexp' or `both'. This is then equivalent to set
  217. `org-list-end-regexp' to \"^[ \\t]*$\"."
  218. :group 'org-plain-lists
  219. :type 'boolean)
  220. (defcustom org-list-end-regexp "^[ \t]*\n[ \t]*\n"
  221. "Regexp matching the end of all plain list levels.
  222. It must start with \"^\" and end with \"\\n\". It defaults to 2
  223. blank lines. `org-empty-line-terminates-plain-lists' has
  224. precedence over it."
  225. :group 'org-plain-lists
  226. :type 'string)
  227. (defcustom org-list-automatic-rules '((bullet . t)
  228. (checkbox . t)
  229. (indent . t))
  230. "Non-nil means apply set of rules when acting on lists.
  231. By default, automatic actions are taken when using
  232. \\[org-meta-return], \\[org-metaright], \\[org-metaleft],
  233. \\[org-shiftmetaright], \\[org-shiftmetaleft],
  234. \\[org-ctrl-c-minus], \\[org-toggle-checkbox] or
  235. \\[org-insert-todo-heading]. You can disable individually these
  236. rules by setting them to nil. Valid rules are:
  237. bullet when non-nil, cycling bullet do not allow lists at
  238. column 0 to have * as a bullet and descriptions lists
  239. to be numbered.
  240. checkbox when non-nil, checkbox statistics is updated each time
  241. you either insert a new checkbox or toggle a checkbox.
  242. It also prevents from inserting a checkbox in a
  243. description item.
  244. indent when non-nil, indenting or outdenting list top-item
  245. with its subtree will move the whole list and
  246. outdenting a list whose bullet is * to column 0 will
  247. change that bullet to \"-\"."
  248. :group 'org-plain-lists
  249. :type '(alist :tag "Sets of rules"
  250. :key-type
  251. (choice
  252. (const :tag "Bullet" bullet)
  253. (const :tag "Checkbox" checkbox)
  254. (const :tag "Indent" indent))
  255. :value-type
  256. (boolean :tag "Activate" :value t)))
  257. (defvar org-checkbox-statistics-hook nil
  258. "Hook that is run whenever Org thinks checkbox statistics should be updated.
  259. This hook runs even if checkbox rule in
  260. `org-list-automatic-rules' does not apply, so it can be used to
  261. implement alternative ways of collecting statistics
  262. information.")
  263. (defcustom org-hierarchical-checkbox-statistics t
  264. "Non-nil means checkbox statistics counts only the state of direct children.
  265. When nil, all boxes below the cookie are counted.
  266. This can be set to nil on a per-node basis using a COOKIE_DATA property
  267. with the word \"recursive\" in the value."
  268. :group 'org-plain-lists
  269. :type 'boolean)
  270. (defcustom org-description-max-indent 20
  271. "Maximum indentation for the second line of a description list.
  272. When the indentation would be larger than this, it will become
  273. 5 characters instead."
  274. :group 'org-plain-lists
  275. :type 'integer)
  276. (defcustom org-list-radio-list-templates
  277. '((latex-mode "% BEGIN RECEIVE ORGLST %n
  278. % END RECEIVE ORGLST %n
  279. \\begin{comment}
  280. #+ORGLST: SEND %n org-list-to-latex
  281. -
  282. \\end{comment}\n")
  283. (texinfo-mode "@c BEGIN RECEIVE ORGLST %n
  284. @c END RECEIVE ORGLST %n
  285. @ignore
  286. #+ORGLST: SEND %n org-list-to-texinfo
  287. -
  288. @end ignore\n")
  289. (html-mode "<!-- BEGIN RECEIVE ORGLST %n -->
  290. <!-- END RECEIVE ORGLST %n -->
  291. <!--
  292. #+ORGLST: SEND %n org-list-to-html
  293. -
  294. -->\n"))
  295. "Templates for radio lists in different major modes.
  296. All occurrences of %n in a template will be replaced with the name of the
  297. list, obtained by prompting the user."
  298. :group 'org-plain-lists
  299. :type '(repeat
  300. (list (symbol :tag "Major mode")
  301. (string :tag "Format"))))
  302. (defvar org-list-forbidden-blocks '("example" "verse" "src")
  303. "Names of blocks where lists are not allowed.
  304. Names must be in lower case.")
  305. (defvar org-list-export-context '(block inlinetask)
  306. "Context types where lists will be interpreted during export.
  307. Valid types are `drawer', `inlinetask' and `block'. More
  308. specifically, type `block' is determined by the variable
  309. `org-list-forbidden-blocks'.")
  310. ;;; Predicates and regexps
  311. (defconst org-list-end-re (if org-empty-line-terminates-plain-lists
  312. "^[ \t]*\n"
  313. org-list-end-regexp)
  314. "Regex corresponding to the end of a list.
  315. It depends on `org-empty-line-terminates-plain-lists'.")
  316. (defconst org-list-full-item-re
  317. (concat "^[ \t]*\\(\\(?:[-+*]\\|\\(?:[0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\\)"
  318. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\]\\)?"
  319. "\\(?:\\(\\[[ X-]\\]\\)[ \t]+\\)?"
  320. "\\(?:\\(.*\\)[ \t]+::[ \t]+\\)?")
  321. "Matches a list item and puts everything into groups:
  322. group 1: bullet
  323. group 2: counter
  324. group 3: checkbox
  325. group 4: description tag")
  326. (defun org-item-re ()
  327. "Return the correct regular expression for plain lists."
  328. (let ((term (cond
  329. ((eq org-plain-list-ordered-item-terminator t) "[.)]")
  330. ((= org-plain-list-ordered-item-terminator ?\)) ")")
  331. ((= org-plain-list-ordered-item-terminator ?.) "\\.")
  332. (t "[.)]")))
  333. (alpha (if org-alphabetical-lists "\\|[A-Za-z]" "")))
  334. (concat "\\([ \t]*\\([-+]\\|\\(\\([0-9]+" alpha "\\)" term
  335. "\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")))
  336. (defsubst org-item-beginning-re ()
  337. "Regexp matching the beginning of a plain list item."
  338. (concat "^" (org-item-re)))
  339. (defun org-list-at-regexp-after-bullet-p (regexp)
  340. "Is point at a list item with REGEXP after bullet?"
  341. (and (org-at-item-p)
  342. (save-excursion
  343. (goto-char (match-end 0))
  344. ;; Ignore counter if any
  345. (when (looking-at "\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?")
  346. (goto-char (match-end 0)))
  347. (looking-at regexp))))
  348. (defun org-in-item-p ()
  349. "Return item beginning position when in a plain list, nil otherwise.
  350. This checks `org-list-ending-method'."
  351. (save-excursion
  352. (beginning-of-line)
  353. (let* ((case-fold-search t)
  354. (context (org-list-context))
  355. (lim-up (car context))
  356. (inlinetask-re (and (featurep 'org-inlinetask)
  357. (org-inlinetask-outline-regexp)))
  358. ;; Indentation isn't meaningful when point starts at an empty
  359. ;; line or an inline task.
  360. (ind-ref (if (or (looking-at "^[ \t]*$")
  361. (and inlinetask-re (looking-at inlinetask-re)))
  362. 10000
  363. (org-get-indentation))))
  364. (cond
  365. ((eq (nth 2 context) 'invalid) nil)
  366. ((org-at-item-p) (point))
  367. (t
  368. ;; Detect if cursor in amidst `org-list-end-re'. First, count
  369. ;; number HL of hard lines it takes, then call `org-in-regexp'
  370. ;; to compute its boundaries END-BOUNDS. When point is
  371. ;; in-between, move cursor before regexp beginning.
  372. (let ((hl 0) (i -1) end-bounds)
  373. (when (and (not (eq org-list-ending-method 'indent))
  374. (progn
  375. (while (setq i (string-match
  376. "[\r\n]" org-list-end-re (1+ i)))
  377. (setq hl (1+ hl)))
  378. (setq end-bounds (org-in-regexp org-list-end-re hl)))
  379. (>= (point) (car end-bounds))
  380. (< (point) (cdr end-bounds)))
  381. (goto-char (car end-bounds))
  382. (forward-line -1)))
  383. ;; Look for an item, less indented that reference line if
  384. ;; `org-list-ending-method' isn't `regexp'.
  385. (catch 'exit
  386. (while t
  387. (let ((ind (org-get-indentation)))
  388. (cond
  389. ;; This is exactly what we want.
  390. ((and (org-at-item-p)
  391. (or (< ind ind-ref)
  392. (eq org-list-ending-method 'regexp)))
  393. (throw 'exit (point)))
  394. ;; At upper bound of search or looking at the end of a
  395. ;; previous list: search is over.
  396. ((<= (point) lim-up) (throw 'exit nil))
  397. ((and (not (eq org-list-ending-method 'indent))
  398. (looking-at org-list-end-re))
  399. (throw 'exit nil))
  400. ;; Skip blocks, drawers, inline-tasks, blank lines
  401. ((looking-at "^[ \t]*#\\+end_")
  402. (re-search-backward "^[ \t]*#\\+begin_" nil t))
  403. ((looking-at "^[ \t]*:END:")
  404. (re-search-backward org-drawer-regexp nil t)
  405. (beginning-of-line))
  406. ((and inlinetask-re (looking-at inlinetask-re))
  407. (org-inlinetask-goto-beginning)
  408. (forward-line -1))
  409. ((looking-at "^[ \t]*$") (forward-line -1))
  410. ;; Text at column 0 cannot belong to a list: stop.
  411. ((zerop ind) (throw 'exit nil))
  412. ;; Normal text less indented than reference line, take
  413. ;; it as new reference.
  414. ((< ind ind-ref)
  415. (setq ind-ref ind)
  416. (forward-line -1))
  417. (t (forward-line -1)))))))))))
  418. (defun org-at-item-p ()
  419. "Is point in a line starting a hand-formatted item?"
  420. (save-excursion (beginning-of-line) (looking-at (org-item-beginning-re))))
  421. (defun org-at-item-bullet-p ()
  422. "Is point at the bullet of a plain list item?"
  423. (and (org-at-item-p)
  424. (not (member (char-after) '(?\ ?\t)))
  425. (< (point) (match-end 0))))
  426. (defun org-at-item-timer-p ()
  427. "Is point at a line starting a plain list item with a timer?"
  428. (org-list-at-regexp-after-bullet-p
  429. "\\([0-9]+:[0-9]+:[0-9]+\\)[ \t]+::[ \t]+"))
  430. (defun org-at-item-description-p ()
  431. "Is point at a description list item?"
  432. (org-list-at-regexp-after-bullet-p "\\(\\S-.+\\)[ \t]+::[ \t]+"))
  433. (defun org-at-item-checkbox-p ()
  434. "Is point at a line starting a plain-list item with a checklet?"
  435. (org-list-at-regexp-after-bullet-p "\\(\\[[- X]\\]\\)[ \t]+"))
  436. (defun org-at-item-counter-p ()
  437. "Is point at a line starting a plain-list item with a counter?"
  438. (and (org-at-item-p)
  439. (looking-at org-list-full-item-re)
  440. (match-string 2)))
  441. ;;; Structures and helper functions
  442. (defun org-list-context ()
  443. "Determine context, and its boundaries, around point.
  444. Context will be a cell like (MIN MAX CONTEXT) where MIN and MAX
  445. are boundaries and CONTEXT is a symbol among `drawer', `block',
  446. `invalid', `inlinetask' and nil.
  447. Contexts `block' and `invalid' refer to
  448. `org-list-forbidden-blocks'."
  449. (save-match-data
  450. (save-excursion
  451. (beginning-of-line)
  452. (let* ((outline-regexp (org-get-limited-outline-regexp))
  453. ;; Can't use org-drawers-regexp as this function might be
  454. ;; called in buffers not in Org mode
  455. (drawers-re (concat "^[ \t]*:\\("
  456. (mapconcat 'regexp-quote org-drawers "\\|")
  457. "\\):[ \t]*$"))
  458. (case-fold-search t)
  459. ;; Compute position of surrounding headings. This is the
  460. ;; default context.
  461. (heading
  462. (save-excursion
  463. (list
  464. (or (and (org-at-heading-p) (point-at-bol))
  465. (outline-previous-heading)
  466. (point-min))
  467. (or (outline-next-heading)
  468. (point-max))
  469. nil)))
  470. (prev-head (car heading))
  471. (next-head (nth 1 heading))
  472. ;; Is point inside a drawer?
  473. (drawerp
  474. (when (and (org-in-regexps-block-p
  475. drawers-re "^[ \t]*:END:" prev-head)
  476. (save-excursion
  477. (beginning-of-line)
  478. (and (not (looking-at drawers-re))
  479. (not (looking-at "^[ \t]*:END:")))))
  480. (save-excursion
  481. (list
  482. (progn
  483. (re-search-backward drawers-re prev-head t)
  484. (1+ (point-at-eol)))
  485. (if (re-search-forward "^[ \t]*:END:" next-head t)
  486. (1- (point-at-bol))
  487. next-head)
  488. 'drawer))))
  489. ;; Is point strictly in a block, and of which type?
  490. (blockp
  491. (save-excursion
  492. (when (and (org-in-regexps-block-p
  493. "^[ \t]*#\\+begin_" "^[ \t]*#\\+end_" prev-head)
  494. (save-excursion
  495. (beginning-of-line)
  496. (not (looking-at
  497. "^[ \t]*#\\+\\(begin\\|end\\)_"))))
  498. (list
  499. (progn
  500. (re-search-backward
  501. "^[ \t]*#\\+begin_\\(\\S-+\\)" prev-head t)
  502. (1+ (point-at-eol)))
  503. (save-match-data
  504. (if (re-search-forward "^[ \t]*#\\+end_" next-head t)
  505. (1- (point-at-bol))
  506. next-head))
  507. (if (member (downcase (match-string 1))
  508. org-list-forbidden-blocks)
  509. 'invalid
  510. 'block)))))
  511. ;; Is point in an inlinetask?
  512. (inlinetaskp
  513. (when (and (featurep 'org-inlinetask)
  514. (org-inlinetask-in-task-p)
  515. (not (looking-at "^\\*+")))
  516. (save-excursion
  517. (list
  518. (progn (org-inlinetask-goto-beginning)
  519. (1+ (point-at-eol)))
  520. (progn
  521. (org-inlinetask-goto-end)
  522. (forward-line -1)
  523. (1- (point-at-bol)))
  524. 'inlinetask))))
  525. ;; List actual candidates
  526. (context-list
  527. (delq nil (list heading drawerp blockp inlinetaskp))))
  528. ;; Return the closest context around
  529. (assq (apply 'max (mapcar 'car context-list)) context-list)))))
  530. (defun org-list-struct ()
  531. "Return structure of list at point.
  532. A list structure is an alist where keys is point at item, and
  533. values are:
  534. 1. indentation,
  535. 2. bullet with trailing whitespace,
  536. 3. bullet counter, if any,
  537. 4. checkbox, if any,
  538. 5. position at item end,
  539. 6. description tag, if any.
  540. Thus the following list, where numbers in parens are
  541. point-at-bol:
  542. - [X] first item (1)
  543. 1. sub-item 1 (18)
  544. 5. [@5] sub-item 2 (34)
  545. some other text belonging to first item (55)
  546. - last item (97)
  547. + tag :: description (109)
  548. (131)
  549. will get the following structure:
  550. \(\(1 0 \"- \" nil \"[X]\" nil 97\)
  551. \(18 2 \"1. \" nil nil nil 34\)
  552. \(34 2 \"5. \" \"5\" nil nil 55\)
  553. \(97 0 \"- \" nil nil nil 131\)
  554. \(109 2 \"+ \" nil nil \"tag\" 131\)
  555. Assume point is at an item."
  556. (save-excursion
  557. (beginning-of-line)
  558. (let* ((case-fold-search t)
  559. (context (org-list-context))
  560. (lim-up (car context))
  561. (lim-down (nth 1 context))
  562. (text-min-ind 10000)
  563. (item-re (org-item-re))
  564. (drawers-re (concat "^[ \t]*:\\("
  565. (mapconcat 'regexp-quote org-drawers "\\|")
  566. "\\):[ \t]*$"))
  567. (inlinetask-re (and (featurep 'org-inlinetask)
  568. (org-inlinetask-outline-regexp)))
  569. (beg-cell (cons (point) (org-get-indentation)))
  570. ind itm-lst itm-lst-2 end-lst end-lst-2 struct
  571. (assoc-at-point
  572. ;; Return an association whose key is point and values are
  573. ;; indentation, bullet string, bullet counter, and
  574. ;; checkbox.
  575. (function
  576. (lambda (ind)
  577. (looking-at org-list-full-item-re)
  578. (list (point)
  579. ind
  580. (match-string-no-properties 1) ; bullet
  581. (match-string-no-properties 2) ; counter
  582. (match-string-no-properties 3) ; checkbox
  583. (match-string-no-properties 4))))) ; description tag
  584. (end-before-blank
  585. ;; Ensure list ends at the first blank line.
  586. (function
  587. (lambda ()
  588. (skip-chars-backward " \r\t\n")
  589. (min (1+ (point-at-eol)) lim-down)))))
  590. ;; 1. Read list from starting item to its beginning, and save
  591. ;; top item position and indentation in BEG-CELL. Also store
  592. ;; ending position of items in END-LST.
  593. (save-excursion
  594. (catch 'exit
  595. (while t
  596. (let ((ind (+ (or (get-text-property (point) 'original-indentation) 0)
  597. (org-get-indentation))))
  598. (cond
  599. ((<= (point) lim-up)
  600. ;; At upward limit: if we ended at an item, store it,
  601. ;; else dimiss useless data recorded above BEG-CELL.
  602. ;; Jump to part 2.
  603. (throw 'exit
  604. (setq itm-lst
  605. (if (or (not (looking-at item-re))
  606. (get-text-property (point) 'org-example))
  607. (memq (assq (car beg-cell) itm-lst) itm-lst)
  608. (setq beg-cell (cons (point) ind))
  609. (cons (funcall assoc-at-point ind) itm-lst)))))
  610. ;; At a verbatim block, go before its beginning. Move
  611. ;; from eol to ensure `previous-single-property-change'
  612. ;; will return a value.
  613. ((get-text-property (point) 'org-example)
  614. (goto-char (previous-single-property-change
  615. (point-at-eol) 'org-example nil lim-up))
  616. (forward-line -1))
  617. ;; Looking at a list ending regexp. Dismiss useless
  618. ;; data recorded above BEG-CELL. Jump to part 2.
  619. ((and (not (eq org-list-ending-method 'indent))
  620. (looking-at org-list-end-re))
  621. (throw 'exit
  622. (setq itm-lst
  623. (memq (assq (car beg-cell) itm-lst) itm-lst))))
  624. ;; Skip blocks, drawers, inline tasks, blank lines
  625. ;; along the way.
  626. ((looking-at "^[ \t]*#\\+end_")
  627. (re-search-backward "^[ \t]*#\\+begin_" nil t))
  628. ((looking-at "^[ \t]*:END:")
  629. (re-search-backward drawers-re nil t)
  630. (beginning-of-line))
  631. ((and inlinetask-re (looking-at inlinetask-re))
  632. (org-inlinetask-goto-beginning)
  633. (forward-line -1))
  634. ((looking-at "^[ \t]*$")
  635. (forward-line -1))
  636. ((looking-at item-re)
  637. ;; Point is at an item. Add data to ITM-LST. It may
  638. ;; also end a previous item: save it in END-LST. If
  639. ;; ind is less or equal than BEG-CELL and there is no
  640. ;; end at this ind or lesser, this item becomes the
  641. ;; new BEG-CELL.
  642. (push (funcall assoc-at-point ind) itm-lst)
  643. (push (cons ind (point-at-bol)) end-lst)
  644. (when (or (and (eq org-list-ending-method 'regexp)
  645. (<= ind (cdr beg-cell)))
  646. (< ind text-min-ind))
  647. (setq beg-cell (cons (point-at-bol) ind)))
  648. (forward-line -1))
  649. (t
  650. ;; Point is not at an item. Unless ending method is
  651. ;; `regexp', interpret line's indentation:
  652. ;;
  653. ;; - text at column 0 is necessarily out of any list.
  654. ;; Dismiss data recorded above BEG-CELL. Jump to
  655. ;; part 2.
  656. ;;
  657. ;; - any other case, it can possibly be an ending
  658. ;; position for an item above. Save it and proceed.
  659. (cond
  660. ((eq org-list-ending-method 'regexp))
  661. ((= ind 0)
  662. (throw 'exit
  663. (setq itm-lst
  664. (memq (assq (car beg-cell) itm-lst) itm-lst))))
  665. (t
  666. (when (< ind text-min-ind) (setq text-min-ind ind))
  667. (push (cons ind (point-at-bol)) end-lst)))
  668. (forward-line -1)))))))
  669. ;; 2. Read list from starting point to its end, that is until we
  670. ;; get out of context, or a non-item line is less or equally
  671. ;; indented that BEG-CELL's cdr. Also store ending position
  672. ;; of items in END-LST-2.
  673. (catch 'exit
  674. (while t
  675. (let ((ind (+ (or (get-text-property (point) 'original-indentation) 0)
  676. (org-get-indentation))))
  677. (cond
  678. ((>= (point) lim-down)
  679. ;; At downward limit: this is de facto the end of the
  680. ;; list. Save point as an ending position, and jump to
  681. ;; part 3.
  682. (throw 'exit
  683. (push (cons 0 (funcall end-before-blank)) end-lst-2)))
  684. ;; At a verbatim block, move to its end. Point is at bol
  685. ;; and 'org-example property is set by whole lines:
  686. ;; `next-single-property-change' always return a value.
  687. ((get-text-property (point) 'org-example)
  688. (goto-char
  689. (next-single-property-change (point) 'org-example nil lim-down)))
  690. ;; Looking at a list ending regexp. Save point as an
  691. ;; ending position and jump to part 3.
  692. ((and (not (eq org-list-ending-method 'indent))
  693. (looking-at org-list-end-re))
  694. (throw 'exit (push (cons 0 (point-at-bol)) end-lst-2)))
  695. ;; Skip blocks, drawers, inline tasks and blank lines
  696. ;; along the way
  697. ((looking-at "^[ \t]*#\\+begin_")
  698. (re-search-forward "^[ \t]*#\\+end_")
  699. (forward-line 1))
  700. ((looking-at drawers-re)
  701. (re-search-forward "^[ \t]*:END:" nil t)
  702. (forward-line 1))
  703. ((and inlinetask-re (looking-at inlinetask-re))
  704. (org-inlinetask-goto-end))
  705. ((looking-at "^[ \t]*$")
  706. (forward-line 1))
  707. ((looking-at item-re)
  708. ;; Point is at an item. Add data to ITM-LST-2. It may also
  709. ;; end a previous item, so save it in END-LST-2.
  710. (push (funcall assoc-at-point ind) itm-lst-2)
  711. (push (cons ind (point-at-bol)) end-lst-2)
  712. (forward-line 1))
  713. (t
  714. ;; Point is not at an item. If ending method is not
  715. ;; `regexp', two situations are of interest:
  716. ;;
  717. ;; - ind is lesser or equal than BEG-CELL's. The list is
  718. ;; over. Store point as an ending position and jump to
  719. ;; part 3.
  720. ;;
  721. ;; - ind is lesser or equal than previous item's. This
  722. ;; is an ending position. Store it and proceed.
  723. (cond
  724. ((eq org-list-ending-method 'regexp))
  725. ((<= ind (cdr beg-cell))
  726. (push (cons ind (funcall end-before-blank)) end-lst-2)
  727. (throw 'exit nil))
  728. ((<= ind (nth 1 (car itm-lst-2)))
  729. (push (cons ind (point-at-bol)) end-lst-2)))
  730. (forward-line 1))))))
  731. (setq struct (append itm-lst (cdr (nreverse itm-lst-2))))
  732. (setq end-lst (append end-lst (cdr (nreverse end-lst-2))))
  733. ;; 3. Correct ill-formed lists by making sure top item has the
  734. ;; least indentation of the list
  735. (let ((min-ind (nth 1 (car struct))))
  736. (mapc (lambda (item)
  737. (let ((ind (nth 1 item)))
  738. (when (< ind min-ind) (setcar (cdr item) min-ind))))
  739. struct))
  740. ;; 4. Associate each item to its end pos.
  741. (org-list-struct-assoc-end struct end-lst)
  742. ;; 5. Return STRUCT
  743. struct)))
  744. (defun org-list-struct-assoc-end (struct end-list)
  745. "Associate proper ending point to items in STRUCT.
  746. END-LIST is a pseudo-alist where car is indentation and cdr is
  747. ending position.
  748. This function modifies STRUCT."
  749. (let ((endings end-list))
  750. (mapc
  751. (lambda (elt)
  752. (let ((pos (car elt))
  753. (ind (nth 1 elt)))
  754. ;; Remove end candidates behind current item
  755. (while (or (<= (cdar endings) pos))
  756. (pop endings))
  757. ;; Add end position to item assoc
  758. (let ((old-end (nthcdr 6 elt))
  759. (new-end (assoc-default ind endings '<=)))
  760. (if old-end
  761. (setcar old-end new-end)
  762. (setcdr elt (append (cdr elt) (list new-end)))))))
  763. struct)))
  764. (defun org-list-prevs-alist (struct)
  765. "Return alist between item and previous item in STRUCT."
  766. (let ((item-end-alist (mapcar (lambda (e) (cons (car e) (nth 6 e)))
  767. struct)))
  768. (mapcar (lambda (e)
  769. (let ((prev (car (rassq (car e) item-end-alist))))
  770. (cons (car e) prev)))
  771. struct)))
  772. (defun org-list-parents-alist (struct)
  773. "Return alist between item and parent in STRUCT."
  774. (let ((ind-to-ori (list (list (nth 1 (car struct)))))
  775. (prev-pos (list (caar struct))))
  776. (cons prev-pos
  777. (mapcar (lambda (item)
  778. (let ((pos (car item))
  779. (ind (nth 1 item))
  780. (prev-ind (caar ind-to-ori)))
  781. (push pos prev-pos)
  782. (cond
  783. ((> prev-ind ind)
  784. (setq ind-to-ori
  785. (member (assq ind ind-to-ori) ind-to-ori))
  786. (cons pos (cdar ind-to-ori)))
  787. ((< prev-ind ind)
  788. (let ((origin (nth 1 prev-pos)))
  789. (push (cons ind origin) ind-to-ori)
  790. (cons pos origin)))
  791. (t (cons pos (cdar ind-to-ori))))))
  792. (cdr struct)))))
  793. ;;; Accessors
  794. (defsubst org-list-get-nth (n key struct)
  795. "Return the Nth value of KEY in STRUCT."
  796. (nth n (assq key struct)))
  797. (defun org-list-set-nth (n key struct new)
  798. "Set the Nth value of KEY in STRUCT to NEW.
  799. \nThis function modifies STRUCT."
  800. (setcar (nthcdr n (assq key struct)) new))
  801. (defsubst org-list-get-ind (item struct)
  802. "Return indentation of ITEM in STRUCT."
  803. (org-list-get-nth 1 item struct))
  804. (defun org-list-set-ind (item struct ind)
  805. "Set indentation of ITEM in STRUCT to IND.
  806. \nThis function modifies STRUCT."
  807. (org-list-set-nth 1 item struct ind))
  808. (defsubst org-list-get-bullet (item struct)
  809. "Return bullet of ITEM in STRUCT."
  810. (org-list-get-nth 2 item struct))
  811. (defun org-list-set-bullet (item struct bullet)
  812. "Set bullet of ITEM in STRUCT to BULLET.
  813. \nThis function modifies STRUCT."
  814. (org-list-set-nth 2 item struct bullet))
  815. (defsubst org-list-get-counter (item struct)
  816. "Return counter of ITEM in STRUCT."
  817. (org-list-get-nth 3 item struct))
  818. (defsubst org-list-get-checkbox (item struct)
  819. "Return checkbox of ITEM in STRUCT or nil."
  820. (org-list-get-nth 4 item struct))
  821. (defun org-list-set-checkbox (item struct checkbox)
  822. "Set checkbox of ITEM in STRUCT to CHECKBOX.
  823. \nThis function modifies STRUCT."
  824. (org-list-set-nth 4 item struct checkbox))
  825. (defsubst org-list-get-tag (item struct)
  826. "Return end position of ITEM in STRUCT."
  827. (org-list-get-nth 5 item struct))
  828. (defun org-list-get-item-end (item struct)
  829. "Return end position of ITEM in STRUCT."
  830. (org-list-get-nth 6 item struct))
  831. (defun org-list-get-item-end-before-blank (item struct)
  832. "Return point at end of ITEM in STRUCT, before any blank line.
  833. Point returned is at end of line."
  834. (save-excursion
  835. (goto-char (org-list-get-item-end item struct))
  836. (skip-chars-backward " \r\t\n")
  837. (point-at-eol)))
  838. (defun org-list-get-parent (item struct parents)
  839. "Return parent of ITEM in STRUCT, or nil.
  840. PARENTS is the alist of items' parent. See
  841. `org-list-parents-alist'."
  842. (let ((parents (or parents (org-list-parents-alist struct))))
  843. (cdr (assq item parents))))
  844. (defun org-list-has-child-p (item struct)
  845. "Return a non-nil value if ITEM in STRUCT has a child.
  846. Value returned is the position of the first child of ITEM."
  847. (let ((ind (org-list-get-ind item struct))
  848. (child-maybe (car (nth 1 (member (assq item struct) struct)))))
  849. (when (and child-maybe
  850. (< ind (org-list-get-ind child-maybe struct)))
  851. child-maybe)))
  852. (defun org-list-get-next-item (item struct prevs)
  853. "Return next item in same sub-list as ITEM in STRUCT, or nil.
  854. PREVS is the alist of previous items. See
  855. `org-list-prevs-alist'."
  856. (car (rassq item prevs)))
  857. (defun org-list-get-prev-item (item struct prevs)
  858. "Return previous item in same sub-list as ITEM in STRUCT, or nil.
  859. PREVS is the alist of previous items. See
  860. `org-list-prevs-alist'."
  861. (cdr (assq item prevs)))
  862. (defun org-list-get-subtree (item struct)
  863. "Return all items with ITEM as a common ancestor or nil.
  864. STRUCT is the list structure considered."
  865. (let* ((item-end (org-list-get-item-end item struct))
  866. (sub-struct (cdr (member (assq item struct) struct)))
  867. subtree)
  868. (catch 'exit
  869. (mapc (lambda (e)
  870. (let ((pos (car e)))
  871. (if (< pos item-end) (push pos subtree) (throw 'exit nil))))
  872. sub-struct))
  873. (nreverse subtree)))
  874. (defun org-list-get-all-items (item struct prevs)
  875. "List of items in the same sub-list as ITEM in STRUCT.
  876. PREVS is the alist of previous items. See
  877. `org-list-prevs-alist'."
  878. (let ((prev-item item)
  879. (next-item item)
  880. before-item after-item)
  881. (while (setq prev-item (org-list-get-prev-item prev-item struct prevs))
  882. (push prev-item before-item))
  883. (while (setq next-item (org-list-get-next-item next-item struct prevs))
  884. (push next-item after-item))
  885. (append before-item (list item) (nreverse after-item))))
  886. (defun org-list-get-children (item struct parents)
  887. "List all children of ITEM in STRUCT, or nil.
  888. PARENTS is the alist of items' parent. See
  889. `org-list-parents-alist'."
  890. (let (all child)
  891. (while (setq child (car (rassq item parents)))
  892. (setq parents (cdr (member (assq child parents) parents)))
  893. (push child all))
  894. (nreverse all)))
  895. (defun org-list-get-top-point (struct)
  896. "Return point at beginning of list.
  897. STRUCT is the structure of the list."
  898. (caar struct))
  899. (defun org-list-get-bottom-point (struct)
  900. "Return point at bottom of list.
  901. STRUCT is the structure of the list."
  902. (apply 'max
  903. (mapcar (lambda (e) (org-list-get-item-end (car e) struct)) struct)))
  904. (defun org-list-get-list-begin (item struct prevs)
  905. "Return point at beginning of sub-list ITEM belongs.
  906. STRUCT is the structure of the list. PREVS is the alist of
  907. previous items. See `org-list-prevs-alist'."
  908. (let ((first-item item) prev-item)
  909. (while (setq prev-item (org-list-get-prev-item first-item struct prevs))
  910. (setq first-item prev-item))
  911. first-item))
  912. (defalias 'org-list-get-first-item 'org-list-get-list-begin)
  913. (defun org-list-get-last-item (item struct prevs)
  914. "Return point at last item of sub-list ITEM belongs.
  915. STRUCT is the structure of the list. PREVS is the alist of
  916. previous items. See `org-list-prevs-alist'."
  917. (let ((last-item item) next-item)
  918. (while (setq next-item (org-list-get-next-item last-item struct prevs))
  919. (setq last-item next-item))
  920. last-item))
  921. (defun org-list-get-list-end (item struct prevs)
  922. "Return point at end of sub-list ITEM belongs.
  923. STRUCT is the structure of the list. PREVS is the alist of
  924. previous items. See `org-list-prevs-alist'."
  925. (org-list-get-item-end (org-list-get-last-item item struct prevs) struct))
  926. (defun org-list-get-list-type (item struct prevs)
  927. "Return the type of the list containing ITEM as a symbol.
  928. STRUCT is the structure of the list, as returned by
  929. `org-list-struct'. PREVS is the alist of previous items. See
  930. `org-list-prevs-alist'.
  931. Possible types are `descriptive', `ordered' and `unordered'. The
  932. type is determined by the first item of the list."
  933. (let ((first (org-list-get-list-begin item struct prevs)))
  934. (cond
  935. ((org-list-get-tag first struct) 'descriptive)
  936. ((string-match "[[:alnum:]]" (org-list-get-bullet first struct)) 'ordered)
  937. (t 'unordered))))
  938. ;;; Searching
  939. (defun org-list-search-generic (search re bound noerr)
  940. "Search a string in valid contexts for lists.
  941. Arguments SEARCH, RE, BOUND and NOERR are similar to those in
  942. `re-search-forward'."
  943. (catch 'exit
  944. (let ((origin (point)))
  945. (while t
  946. ;; 1. No match: return to origin or bound, depending on NOERR.
  947. (unless (funcall search re bound noerr)
  948. (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound))
  949. nil)))
  950. ;; 2. Match in an `invalid' context: continue searching. Else,
  951. ;; return point.
  952. (unless (eq (org-list-context) 'invalid) (throw 'exit (point)))))))
  953. (defun org-list-search-backward (regexp &optional bound noerror)
  954. "Like `re-search-backward' but stop only where lists are recognized.
  955. Arguments REGEXP, BOUND and NOERROR are similar to those used in
  956. `re-search-backward'."
  957. (org-list-search-generic #'re-search-backward
  958. regexp (or bound (point-min)) noerror))
  959. (defun org-list-search-forward (regexp &optional bound noerror)
  960. "Like `re-search-forward' but stop only where lists are recognized.
  961. Arguments REGEXP, BOUND and NOERROR are similar to those used in
  962. `re-search-forward'."
  963. (org-list-search-generic #'re-search-forward
  964. regexp (or bound (point-max)) noerror))
  965. ;;; Methods on structures
  966. (defsubst org-list-bullet-string (bullet)
  967. "Return BULLET with the correct number of whitespaces.
  968. It determines the number of whitespaces to append by looking at
  969. `org-list-two-spaces-after-bullet-regexp'."
  970. (save-match-data
  971. (let ((spaces (if (and org-list-two-spaces-after-bullet-regexp
  972. (string-match
  973. org-list-two-spaces-after-bullet-regexp bullet))
  974. " "
  975. " ")))
  976. (string-match "\\S-+\\([ \t]*\\)" bullet)
  977. (replace-match spaces nil nil bullet 1))))
  978. (defun org-list-separating-blank-lines-number (pos struct prevs)
  979. "Return number of blank lines that should separate items in list.
  980. POS is the position at item beginning to be considered. STRUCT is
  981. the list structure. PREVS is the alist of previous items. See
  982. `org-list-prevs-alist'.
  983. Assume point is at item's beginning. If the item is alone, apply
  984. some heuristics to guess the result."
  985. (save-excursion
  986. (let ((insert-blank-p
  987. (cdr (assq 'plain-list-item org-blank-before-new-entry)))
  988. usr-blank)
  989. (cond
  990. ;; Trivial cases where there should be none.
  991. ((or (and (not (eq org-list-ending-method 'indent))
  992. org-empty-line-terminates-plain-lists)
  993. (not insert-blank-p)) 0)
  994. ;; When `org-blank-before-new-entry' says so, it is 1.
  995. ((eq insert-blank-p t) 1)
  996. ;; plain-list-item is 'auto. Count blank lines separating
  997. ;; neighbours items in list.
  998. (t (let ((next-p (org-list-get-next-item (point) struct prevs)))
  999. (cond
  1000. ;; Is there a next item?
  1001. (next-p (goto-char next-p)
  1002. (org-back-over-empty-lines))
  1003. ;; Is there a previous item?
  1004. ((org-list-get-prev-item (point) struct prevs)
  1005. (org-back-over-empty-lines))
  1006. ;; User inserted blank lines, trust him
  1007. ((and (> pos (org-list-get-item-end-before-blank pos struct))
  1008. (> (save-excursion
  1009. (goto-char pos)
  1010. (skip-chars-backward " \t")
  1011. (setq usr-blank (org-back-over-empty-lines))) 0))
  1012. usr-blank)
  1013. ;; Are there blank lines inside the item ?
  1014. ((save-excursion
  1015. (org-list-search-forward
  1016. "^[ \t]*$" (org-list-get-item-end-before-blank pos struct) t))
  1017. 1)
  1018. ;; No parent: no blank line.
  1019. (t 0))))))))
  1020. (defun org-list-insert-item (pos struct prevs &optional checkbox after-bullet)
  1021. "Insert a new list item at POS.
  1022. If POS is before first character after bullet of the item, the
  1023. new item will be created before the current one.
  1024. STRUCT is the list structure, as returned by `org-list-struct'.
  1025. PREVS is the the alist of previous items. See
  1026. `org-list-prevs-alist'.
  1027. Insert a checkbox if CHECKBOX is non-nil, and string AFTER-BULLET
  1028. after the bullet. Cursor will be after this text once the
  1029. function ends.
  1030. Return the new structure of the list."
  1031. (let ((case-fold-search t))
  1032. ;; 1. Get information about list: structure, usual helper
  1033. ;; functions, position of point with regards to item start
  1034. ;; (BEFOREP), blank lines number separating items (BLANK-NB),
  1035. ;; position of split (POS) if we're allowed to (SPLIT-LINE-P).
  1036. (let* ((item (goto-char (org-list-get-item-begin)))
  1037. (item-end (org-list-get-item-end item struct))
  1038. (item-end-no-blank (org-list-get-item-end-before-blank item struct))
  1039. (beforep (and (looking-at org-list-full-item-re)
  1040. (<= pos (match-end 0))))
  1041. (split-line-p (org-get-alist-option org-M-RET-may-split-line 'item))
  1042. (blank-nb (org-list-separating-blank-lines-number
  1043. item struct prevs))
  1044. ;; 2. Build the new item to be created. Concatenate same
  1045. ;; bullet as item, checkbox, text AFTER-BULLET if
  1046. ;; provided, and text cut from point to end of item
  1047. ;; (TEXT-CUT) to form item's BODY. TEXT-CUT depends on
  1048. ;; BEFOREP and SPLIT-LINE-P. The difference of size
  1049. ;; between what was cut and what was inserted in buffer
  1050. ;; is stored in SIZE-OFFSET.
  1051. (ind (org-list-get-ind item struct))
  1052. (bullet (org-list-bullet-string (org-list-get-bullet item struct)))
  1053. (box (when checkbox "[ ]"))
  1054. (text-cut
  1055. (and (not beforep) split-line-p
  1056. (progn
  1057. (goto-char pos)
  1058. (skip-chars-backward " \r\t\n")
  1059. (setq pos (point))
  1060. (delete-and-extract-region pos item-end-no-blank))))
  1061. (body (concat bullet (when box (concat box " ")) after-bullet
  1062. (or (and text-cut
  1063. (if (string-match "\\`[ \t]+" text-cut)
  1064. (replace-match "" t t text-cut)
  1065. text-cut))
  1066. "")))
  1067. (item-sep (make-string (1+ blank-nb) ?\n))
  1068. (item-size (+ ind (length body) (length item-sep)))
  1069. (size-offset (- item-size (length text-cut))))
  1070. ;; 4. Insert effectively item into buffer
  1071. (goto-char item)
  1072. (org-indent-to-column ind)
  1073. (insert body)
  1074. (insert item-sep)
  1075. ;; 5. Add new item to STRUCT.
  1076. (mapc (lambda (e)
  1077. (let ((p (car e))
  1078. (end (nth 6 e)))
  1079. (cond
  1080. ;; Before inserted item, positions don't change but
  1081. ;; an item ending after insertion has its end shifted
  1082. ;; by SIZE-OFFSET.
  1083. ((< p item)
  1084. (when (> end item) (setcar (nthcdr 6 e) (+ end size-offset))))
  1085. ;; Trivial cases where current item isn't split in
  1086. ;; two. Just shift every item after new one by
  1087. ;; ITEM-SIZE.
  1088. ((or beforep (not split-line-p))
  1089. (setcar e (+ p item-size))
  1090. (setcar (nthcdr 6 e) (+ end item-size)))
  1091. ;; Item is split in two: elements before POS are just
  1092. ;; shifted by ITEM-SIZE. In the case item would end
  1093. ;; after split POS, ending is only shifted by
  1094. ;; SIZE-OFFSET.
  1095. ((< p pos)
  1096. (setcar e (+ p item-size))
  1097. (if (< end pos)
  1098. (setcar (nthcdr 6 e) (+ end item-size))
  1099. (setcar (nthcdr 6 e) (+ end size-offset))))
  1100. ;; Elements after POS are moved into new item. Length
  1101. ;; of ITEM-SEP has to be removed as ITEM-SEP
  1102. ;; doesn't appear in buffer yet.
  1103. ((< p item-end)
  1104. (setcar e (+ p size-offset (- item pos (length item-sep))))
  1105. (if (= end item-end)
  1106. (setcar (nthcdr 6 e) (+ item item-size))
  1107. (setcar (nthcdr 6 e)
  1108. (+ end size-offset
  1109. (- item pos (length item-sep))))))
  1110. ;; Elements at ITEM-END or after are only shifted by
  1111. ;; SIZE-OFFSET.
  1112. (t (setcar e (+ p size-offset))
  1113. (setcar (nthcdr 6 e) (+ end size-offset))))))
  1114. struct)
  1115. (push (list item ind bullet nil box nil (+ item item-size)) struct)
  1116. (setq struct (sort struct (lambda (e1 e2) (< (car e1) (car e2)))))
  1117. ;; 6. If not BEFOREP, new item must appear after ITEM, so
  1118. ;; exchange ITEM with the next item in list. Position cursor
  1119. ;; after bullet, counter, checkbox, and label.
  1120. (if beforep
  1121. (goto-char item)
  1122. (setq struct (org-list-exchange-items item (+ item item-size) struct))
  1123. (goto-char (org-list-get-next-item
  1124. item struct (org-list-prevs-alist struct))))
  1125. struct)))
  1126. (defun org-list-exchange-items (beg-A beg-B struct)
  1127. "Swap item starting at BEG-A with item starting at BEG-B in STRUCT.
  1128. Blank lines at the end of items are left in place. Return the new
  1129. structure after the changes.
  1130. Assume BEG-A is lesser than BEG-B and that BEG-A and BEG-B belong
  1131. to the same sub-list.
  1132. This function modifies STRUCT."
  1133. (save-excursion
  1134. (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
  1135. (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
  1136. (end-A (org-list-get-item-end beg-A struct))
  1137. (end-B (org-list-get-item-end beg-B struct))
  1138. (size-A (- end-A-no-blank beg-A))
  1139. (size-B (- end-B-no-blank beg-B))
  1140. (body-A (buffer-substring beg-A end-A-no-blank))
  1141. (body-B (buffer-substring beg-B end-B-no-blank))
  1142. (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
  1143. (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
  1144. (sub-B (cons beg-B (org-list-get-subtree beg-B struct))))
  1145. ;; 1. Move effectively items in buffer.
  1146. (goto-char beg-A)
  1147. (delete-region beg-A end-B-no-blank)
  1148. (insert (concat body-B between-A-no-blank-and-B body-A))
  1149. ;; 2. Now modify struct. No need to re-read the list, the
  1150. ;; transformation is just a shift of positions. Some special
  1151. ;; attention is required for items ending at END-A and END-B
  1152. ;; as empty spaces are not moved there. In others words, item
  1153. ;; BEG-A will end with whitespaces that were at the end of
  1154. ;; BEG-B and the same applies to BEG-B.
  1155. (mapc (lambda (e)
  1156. (let ((pos (car e)))
  1157. (cond
  1158. ((< pos beg-A))
  1159. ((memq pos sub-A)
  1160. (let ((end-e (nth 6 e)))
  1161. (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
  1162. (setcar (nthcdr 6 e)
  1163. (+ end-e (- end-B-no-blank end-A-no-blank)))
  1164. (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
  1165. ((memq pos sub-B)
  1166. (let ((end-e (nth 6 e)))
  1167. (setcar e (- (+ pos beg-A) beg-B))
  1168. (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
  1169. (when (= end-e end-B)
  1170. (setcar (nthcdr 6 e)
  1171. (+ beg-A size-B (- end-A end-A-no-blank))))))
  1172. ((< pos beg-B)
  1173. (let ((end-e (nth 6 e)))
  1174. (setcar e (+ pos (- size-B size-A)))
  1175. (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
  1176. struct)
  1177. (sort struct (lambda (e1 e2) (< (car e1) (car e2)))))))
  1178. (defun org-list-struct-outdent (start end struct parents)
  1179. "Outdent items between START and END in structure STRUCT.
  1180. PARENTS is the alist of items' parents. See
  1181. `org-list-parents-alist'.
  1182. START is included, END excluded."
  1183. (let* (acc
  1184. (out (lambda (cell)
  1185. (let* ((item (car cell))
  1186. (parent (cdr cell)))
  1187. (cond
  1188. ;; Item not yet in zone: keep association
  1189. ((< item start) cell)
  1190. ;; Item out of zone: follow associations in acc
  1191. ((>= item end)
  1192. (let ((convert (and parent (assq parent acc))))
  1193. (if convert (cons item (cdr convert)) cell)))
  1194. ;; Item has no parent: error
  1195. ((not parent)
  1196. (error "Cannot outdent top-level items"))
  1197. ;; Parent is outdented: keep association
  1198. ((>= parent start)
  1199. (push (cons parent item) acc) cell)
  1200. (t
  1201. ;; Parent isn't outdented: reparent to grand-parent
  1202. (let ((grand-parent (org-list-get-parent
  1203. parent struct parents)))
  1204. (push (cons parent item) acc)
  1205. (cons item grand-parent))))))))
  1206. (mapcar out parents)))
  1207. (defun org-list-struct-indent (start end struct parents prevs)
  1208. "Indent items between START and END in structure STRUCT.
  1209. PARENTS is the alist of parents. See `org-list-parents-alist'.
  1210. PREVS is the alist of previous items. See `org-list-prevs-alist'.
  1211. START is included and END excluded.
  1212. STRUCT may be modified if `org-list-demote-modify-bullet' matches
  1213. bullets between START and END."
  1214. (let* (acc
  1215. (set-assoc (lambda (cell) (push cell acc) cell))
  1216. (change-bullet-maybe
  1217. (function
  1218. (lambda (item)
  1219. (let* ((bul (org-trim (org-list-get-bullet item struct)))
  1220. (new-bul-p (cdr (assoc bul org-list-demote-modify-bullet))))
  1221. (when new-bul-p (org-list-set-bullet item struct new-bul-p))))))
  1222. (ind
  1223. (lambda (cell)
  1224. (let* ((item (car cell))
  1225. (parent (cdr cell)))
  1226. (cond
  1227. ;; Item not yet in zone: keep association
  1228. ((< item start) cell)
  1229. ((>= item end)
  1230. ;; Item out of zone: follow associations in acc
  1231. (let ((convert (assq parent acc)))
  1232. (if convert (cons item (cdr convert)) cell)))
  1233. (t
  1234. ;; Item is in zone...
  1235. (let ((prev (org-list-get-prev-item item struct prevs)))
  1236. ;; Check if bullet needs to be changed
  1237. (funcall change-bullet-maybe item)
  1238. (cond
  1239. ;; First item indented but not parent: error
  1240. ((and (not prev) (< parent start))
  1241. (error "Cannot indent the first item of a list"))
  1242. ;; First item and parent indented: keep same parent
  1243. ((not prev) (funcall set-assoc cell))
  1244. ;; Previous item not indented: reparent to it
  1245. ((< prev start) (funcall set-assoc (cons item prev)))
  1246. ;; Previous item indented: reparent like it
  1247. (t
  1248. (funcall set-assoc
  1249. (cons item (cdr (assq prev acc)))))))))))))
  1250. (mapcar ind parents)))
  1251. ;;; Repairing structures
  1252. (defun org-list-use-alpha-bul-p (first struct prevs)
  1253. "Can list starting at FIRST use alphabetical bullets?
  1254. STRUCT is list structure. See `org-list-struct'. PREVS is the
  1255. alist of previous items. See `org-list-prevs-alist'."
  1256. (and org-alphabetical-lists
  1257. (catch 'exit
  1258. (let ((item first) (ascii 64) (case-fold-search nil))
  1259. ;; Pretend that bullets are uppercase and check if alphabet
  1260. ;; is sufficient, taking counters into account.
  1261. (while item
  1262. (let ((bul (org-list-get-bullet item struct))
  1263. (count (org-list-get-counter item struct)))
  1264. ;; Virtually determine current bullet
  1265. (if (and count (string-match "[a-zA-Z]" count))
  1266. ;; Counters are not case-sensitive.
  1267. (setq ascii (string-to-char (upcase count)))
  1268. (setq ascii (1+ ascii)))
  1269. ;; Test if bullet would be over z or Z.
  1270. (if (> ascii 90)
  1271. (throw 'exit nil)
  1272. (setq item (org-list-get-next-item item struct prevs)))))
  1273. ;; All items checked. All good.
  1274. t))))
  1275. (defun org-list-inc-bullet-maybe (bullet)
  1276. "Increment BULLET if applicable."
  1277. (let ((case-fold-search nil))
  1278. (cond
  1279. ;; Num bullet: increment it.
  1280. ((string-match "[0-9]+" bullet)
  1281. (replace-match
  1282. (number-to-string (1+ (string-to-number (match-string 0 bullet))))
  1283. nil nil bullet))
  1284. ;; Alpha bullet: increment it.
  1285. ((string-match "[A-Za-z]" bullet)
  1286. (replace-match
  1287. (char-to-string (1+ (string-to-char (match-string 0 bullet))))
  1288. nil nil bullet))
  1289. ;; Unordered bullet: leave it.
  1290. (t bullet))))
  1291. (defun org-list-struct-fix-bul (struct prevs)
  1292. "Verify and correct bullets for every association in STRUCT.
  1293. PREVS is the alist of previous items. See
  1294. `org-list-prevs-alist'.
  1295. This function modifies STRUCT."
  1296. (let ((case-fold-search nil)
  1297. (fix-bul
  1298. (function
  1299. ;; Set bullet of ITEM in STRUCT, depending on the type of
  1300. ;; first item of the list, the previous bullet and counter
  1301. ;; if any.
  1302. (lambda (item)
  1303. (let* ((prev (org-list-get-prev-item item struct prevs))
  1304. (prev-bul (and prev (org-list-get-bullet prev struct)))
  1305. (counter (org-list-get-counter item struct))
  1306. (bullet (org-list-get-bullet item struct))
  1307. (alphap (and (not prev)
  1308. (org-list-use-alpha-bul-p item struct prevs))))
  1309. (org-list-set-bullet
  1310. item struct
  1311. (org-list-bullet-string
  1312. (cond
  1313. ;; Alpha counter in alpha list: use counter.
  1314. ((and prev counter
  1315. (string-match "[a-zA-Z]" counter)
  1316. (string-match "[a-zA-Z]" prev-bul))
  1317. ;; Use cond to be sure `string-match' is used in
  1318. ;; both cases.
  1319. (let ((real-count
  1320. (cond
  1321. ((string-match "[a-z]" prev-bul) (downcase counter))
  1322. ((string-match "[A-Z]" prev-bul) (upcase counter)))))
  1323. (replace-match real-count nil nil prev-bul)))
  1324. ;; Num counter in a num list: use counter.
  1325. ((and prev counter
  1326. (string-match "[0-9]+" counter)
  1327. (string-match "[0-9]+" prev-bul))
  1328. (replace-match counter nil nil prev-bul))
  1329. ;; No counter: increase, if needed, previous bullet.
  1330. (prev
  1331. (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
  1332. ;; Alpha counter at first item: use counter.
  1333. ((and counter (org-list-use-alpha-bul-p item struct prevs)
  1334. (string-match "[A-Za-z]" counter)
  1335. (string-match "[A-Za-z]" bullet))
  1336. (let ((real-count
  1337. (cond
  1338. ((string-match "[a-z]" bullet) (downcase counter))
  1339. ((string-match "[A-Z]" bullet) (upcase counter)))))
  1340. (replace-match real-count nil nil bullet)))
  1341. ;; Num counter at first item: use counter.
  1342. ((and counter
  1343. (string-match "[0-9]+" counter)
  1344. (string-match "[0-9]+" bullet))
  1345. (replace-match counter nil nil bullet))
  1346. ;; First bullet is alpha uppercase: use "A".
  1347. ((and alphap (string-match "[A-Z]" bullet))
  1348. (replace-match "A" nil nil bullet))
  1349. ;; First bullet is alpha lowercase: use "a".
  1350. ((and alphap (string-match "[a-z]" bullet))
  1351. (replace-match "a" nil nil bullet))
  1352. ;; First bullet is num: use "1".
  1353. ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet)
  1354. (replace-match "1" nil nil bullet))
  1355. ;; Not an ordered list: keep bullet.
  1356. (t bullet)))))))))
  1357. (mapc fix-bul (mapcar 'car struct))))
  1358. (defun org-list-struct-fix-ind (struct parents &optional bullet-size)
  1359. "Verify and correct indentation for every association in STRUCT.
  1360. PARENTS is the alist of items' parents. See
  1361. `org-list-parents-alist'.
  1362. If numeric optional argument BULLET-SIZE is set, assume all
  1363. bullets in list have this length to determine new indentation.
  1364. This function modifies STRUCT."
  1365. (let* ((ancestor (org-list-get-top-point struct))
  1366. (top-ind (org-list-get-ind ancestor struct))
  1367. (new-ind
  1368. (lambda (item)
  1369. (let ((parent (org-list-get-parent item struct parents)))
  1370. (if parent
  1371. ;; Indent like parent + length of parent's bullet
  1372. (org-list-set-ind
  1373. item struct (+ (or bullet-size
  1374. (length
  1375. (org-list-get-bullet parent struct)))
  1376. (org-list-get-ind parent struct)))
  1377. ;; If no parent, indent like top-point
  1378. (org-list-set-ind item struct top-ind))))))
  1379. (mapc new-ind (mapcar 'car (cdr struct)))))
  1380. (defun org-list-struct-fix-box (struct parents prevs &optional ordered)
  1381. "Verify and correct checkboxes for every association in STRUCT.
  1382. PARENTS is the alist of items' parents. See
  1383. `org-list-parents-alist'. PREVS is the alist of previous items.
  1384. See `org-list-prevs-alist'.
  1385. If ORDERED is non-nil, a checkbox can only be checked when every
  1386. checkbox before it is checked too. If there was an attempt to
  1387. break this rule, the function will return the blocking item. In
  1388. all others cases, the return value will be nil.
  1389. This function modifies STRUCT."
  1390. (let ((all-items (mapcar 'car struct))
  1391. (set-parent-box
  1392. (function
  1393. (lambda (item)
  1394. (let* ((box-list
  1395. (mapcar (lambda (child)
  1396. (org-list-get-checkbox child struct))
  1397. (org-list-get-children item struct parents))))
  1398. (org-list-set-checkbox
  1399. item struct
  1400. (cond
  1401. ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
  1402. ((member "[-]" box-list) "[-]")
  1403. ((member "[X]" box-list) "[X]")
  1404. ((member "[ ]" box-list) "[ ]")
  1405. ;; parent has no boxed child: leave box as-is
  1406. (t (org-list-get-checkbox item struct))))))))
  1407. parent-list)
  1408. ;; 1. List all parents with a checkbox
  1409. (mapc
  1410. (lambda (e)
  1411. (let* ((parent (org-list-get-parent e struct parents))
  1412. (parent-box-p (org-list-get-checkbox parent struct)))
  1413. (when (and parent-box-p (not (memq parent parent-list)))
  1414. (push parent parent-list))))
  1415. all-items)
  1416. ;; 2. Sort those parents by decreasing indentation
  1417. (setq parent-list (sort parent-list
  1418. (lambda (e1 e2)
  1419. (> (org-list-get-ind e1 struct)
  1420. (org-list-get-ind e2 struct)))))
  1421. ;; 3. For each parent, get all children's checkboxes to determine
  1422. ;; and set its checkbox accordingly
  1423. (mapc set-parent-box parent-list)
  1424. ;; 4. If ORDERED is set, see if we need to uncheck some boxes
  1425. (when ordered
  1426. (let* ((box-list
  1427. (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
  1428. (after-unchecked (member "[ ]" box-list)))
  1429. ;; there are boxes checked after an unchecked one: fix that
  1430. (when (member "[X]" after-unchecked)
  1431. (let ((index (- (length struct) (length after-unchecked))))
  1432. (mapc (lambda (e) (org-list-set-checkbox e struct "[ ]"))
  1433. (nthcdr index all-items))
  1434. ;; Verify once again the structure, without ORDERED
  1435. (org-list-struct-fix-box struct parents prevs nil)
  1436. ;; return blocking item
  1437. (nth index all-items)))))))
  1438. (defun org-list-struct-apply-struct (struct old-struct)
  1439. "Apply modifications to list so it mirrors STRUCT.
  1440. OLD-STRUCT is the structure before any modifications. Thus, the
  1441. function is smart enough to modify only parts of buffer which
  1442. have changed.
  1443. Initial position of cursor is restored after the changes."
  1444. (let* ((pos (copy-marker (point)))
  1445. (shift-body-ind
  1446. (function
  1447. ;; Shift the indentation between END and BEG by DELTA.
  1448. ;; Start from the line before END.
  1449. (lambda (end beg delta)
  1450. (goto-char end)
  1451. (skip-chars-backward " \r\t\n")
  1452. (beginning-of-line)
  1453. (while (or (> (point) beg)
  1454. (and (= (point) beg) (not (org-at-item-p))))
  1455. (when (org-looking-at-p "^[ \t]*\\S-")
  1456. (let ((i (org-get-indentation)))
  1457. (org-indent-line-to (+ i delta))))
  1458. (forward-line -1)))))
  1459. (modify-item
  1460. (function
  1461. ;; Replace ITEM first line elements with new elements from
  1462. ;; STRUCT, if appropriate.
  1463. (lambda (item)
  1464. (goto-char item)
  1465. (let* ((new-ind (org-list-get-ind item struct))
  1466. (old-ind (org-list-get-ind item old-struct))
  1467. (new-bul (org-list-bullet-string
  1468. (org-list-get-bullet item struct)))
  1469. (old-bul (org-list-get-bullet item old-struct))
  1470. (new-box (org-list-get-checkbox item struct)))
  1471. (looking-at org-list-full-item-re)
  1472. ;; a. Replace bullet
  1473. (unless (equal old-bul new-bul)
  1474. (replace-match new-bul nil nil nil 1))
  1475. ;; b. Replace checkbox
  1476. (cond
  1477. ((and new-box
  1478. (save-match-data (org-at-item-description-p))
  1479. (cdr (assq 'checkbox org-list-automatic-rules)))
  1480. (message "Cannot add a checkbox to a description list item"))
  1481. ((equal (match-string 3) new-box))
  1482. ((and (match-string 3) new-box)
  1483. (replace-match new-box nil nil nil 3))
  1484. ((match-string 3)
  1485. (goto-char (or (match-end 2) (match-end 1)))
  1486. (looking-at "\\[[ X-]\\][ \t]+")
  1487. (replace-match ""))
  1488. (t (goto-char (or (match-end 2) (match-end 1)))
  1489. (insert (concat new-box " "))))
  1490. ;; c. Indent item to appropriate column
  1491. (unless (= new-ind old-ind)
  1492. (delete-region (goto-char (point-at-bol))
  1493. (progn (skip-chars-forward " \t") (point)))
  1494. (indent-to new-ind)))))))
  1495. ;; 1. First get list of items and position endings. We maintain
  1496. ;; two alists: ITM-SHIFT, determining indentation shift needed
  1497. ;; at item, and END-POS, a pseudo-alist where key is ending
  1498. ;; position and value point
  1499. (let (end-list acc-end itm-shift all-ends sliced-struct)
  1500. (mapc (lambda (e)
  1501. (let* ((pos (car e))
  1502. (ind-pos (org-list-get-ind pos struct))
  1503. (ind-old (org-list-get-ind pos old-struct))
  1504. (bul-pos (org-list-get-bullet pos struct))
  1505. (bul-old (org-list-get-bullet pos old-struct))
  1506. (ind-shift (- (+ ind-pos (length bul-pos))
  1507. (+ ind-old (length bul-old))))
  1508. (end-pos (org-list-get-item-end pos old-struct)))
  1509. (push (cons pos ind-shift) itm-shift)
  1510. (unless (assq end-pos old-struct)
  1511. ;; To determine real ind of an ending position that is
  1512. ;; not at an item, we have to find the item it belongs
  1513. ;; to: it is the last item (ITEM-UP), whose ending is
  1514. ;; further than the position we're interested in.
  1515. (let ((item-up (assoc-default end-pos acc-end '>)))
  1516. (push (cons end-pos item-up) end-list)))
  1517. (push (cons end-pos pos) acc-end)))
  1518. old-struct)
  1519. ;; 2. Slice the items into parts that should be shifted by the
  1520. ;; same amount of indentation. The slices are returned in
  1521. ;; reverse order so changes modifying buffer do not change
  1522. ;; positions they refer to.
  1523. (setq all-ends (sort (append (mapcar 'car itm-shift)
  1524. (org-uniquify (mapcar 'car end-list)))
  1525. '<))
  1526. (while (cdr all-ends)
  1527. (let* ((up (pop all-ends))
  1528. (down (car all-ends))
  1529. (ind (if (assq up struct)
  1530. (cdr (assq up itm-shift))
  1531. (cdr (assq (cdr (assq up end-list)) itm-shift)))))
  1532. (push (list down up ind) sliced-struct)))
  1533. ;; 3. Shift each slice in buffer, provided delta isn't 0, from
  1534. ;; end to beginning. Take a special action when beginning is
  1535. ;; at item bullet.
  1536. (mapc (lambda (e)
  1537. (unless (zerop (nth 2 e)) (apply shift-body-ind e))
  1538. (let* ((beg (nth 1 e))
  1539. (cell (assq beg struct)))
  1540. (unless (or (not cell) (equal cell (assq beg old-struct)))
  1541. (funcall modify-item beg))))
  1542. sliced-struct))
  1543. ;; 4. Go back to initial position
  1544. (goto-char pos)))
  1545. (defun org-list-write-struct (struct parents)
  1546. "Verify bullets, checkboxes, indentation in STRUCT and apply it to buffer.
  1547. PARENTS is the alist of items' parents. See
  1548. `org-list-parents-alist'."
  1549. ;; Order of functions matters here: checkboxes and endings need
  1550. ;; correct indentation to be set, and indentation needs correct
  1551. ;; bullets.
  1552. ;;
  1553. ;; 0. Save a copy of structure before modifications
  1554. (let ((old-struct (copy-tree struct)))
  1555. ;; 1. Set a temporary, but coherent with PARENTS, indentation in
  1556. ;; order to get items endings and bullets properly
  1557. (org-list-struct-fix-ind struct parents 2)
  1558. ;; 2. Get pseudo-alist of ending positions and sort it by position.
  1559. ;; Then associate them to the structure.
  1560. (let (end-list acc-end)
  1561. (mapc (lambda (e)
  1562. (let* ((pos (car e))
  1563. (ind-pos (org-list-get-ind pos struct))
  1564. (end-pos (org-list-get-item-end pos struct)))
  1565. (unless (assq end-pos struct)
  1566. ;; To determine real ind of an ending position that is
  1567. ;; not at an item, we have to find the item it belongs
  1568. ;; to: it is the last item (ITEM-UP), whose ending is
  1569. ;; further than the position we're interested in.
  1570. (let ((item-up (assoc-default end-pos acc-end '>)))
  1571. (push (cons
  1572. ;; Else part is for the bottom point
  1573. (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
  1574. end-pos)
  1575. end-list)))
  1576. (push (cons ind-pos pos) end-list)
  1577. (push (cons end-pos pos) acc-end)))
  1578. struct)
  1579. (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
  1580. (org-list-struct-assoc-end struct end-list))
  1581. ;; 3. Get bullets right
  1582. (let ((prevs (org-list-prevs-alist struct)))
  1583. (org-list-struct-fix-bul struct prevs)
  1584. ;; 4. Now get real indentation
  1585. (org-list-struct-fix-ind struct parents)
  1586. ;; 5. Eventually fix checkboxes
  1587. (org-list-struct-fix-box struct parents prevs))
  1588. ;; 6. Apply structure modifications to buffer
  1589. (org-list-struct-apply-struct struct old-struct)))
  1590. ;;; Misc Tools
  1591. (defun org-apply-on-list (function init-value &rest args)
  1592. "Call FUNCTION on each item of the list at point.
  1593. FUNCTION must be called with at least one argument: INIT-VALUE,
  1594. that will contain the value returned by the function at the
  1595. previous item, plus ARGS extra arguments.
  1596. FUNCTION is applied on items in reverse order.
  1597. As an example, (org-apply-on-list (lambda (result) (1+ result)) 0)
  1598. will return the number of items in the current list.
  1599. Sublists of the list are skipped. Cursor is always at the
  1600. beginning of the item."
  1601. (let* ((struct (org-list-struct))
  1602. (prevs (org-list-prevs-alist struct))
  1603. (item (copy-marker (point-at-bol)))
  1604. (all (org-list-get-all-items (marker-position item) struct prevs))
  1605. (value init-value))
  1606. (mapc (lambda (e)
  1607. (goto-char e)
  1608. (setq value (apply function value args)))
  1609. (nreverse all))
  1610. (goto-char item)
  1611. value))
  1612. ;;; Interactive functions
  1613. (defalias 'org-list-get-item-begin 'org-in-item-p)
  1614. (defun org-beginning-of-item ()
  1615. "Go to the beginning of the current hand-formatted item.
  1616. If the cursor is not in an item, throw an error."
  1617. (interactive)
  1618. (let ((begin (org-in-item-p)))
  1619. (if begin (goto-char begin) (error "Not in an item"))))
  1620. (defun org-beginning-of-item-list ()
  1621. "Go to the beginning item of the current list or sublist.
  1622. Return an error if not in a list."
  1623. (interactive)
  1624. (let ((begin (org-in-item-p)))
  1625. (if (not begin)
  1626. (error "Not in an item")
  1627. (goto-char begin)
  1628. (let* ((struct (org-list-struct))
  1629. (prevs (org-list-prevs-alist struct)))
  1630. (goto-char (org-list-get-list-begin begin struct prevs))))))
  1631. (defun org-end-of-item-list ()
  1632. "Go to the end of the current list or sublist.
  1633. If the cursor in not in an item, throw an error."
  1634. (interactive)
  1635. (let ((begin (org-in-item-p)))
  1636. (if (not begin)
  1637. (error "Not in an item")
  1638. (goto-char begin)
  1639. (let* ((struct (org-list-struct))
  1640. (prevs (org-list-prevs-alist struct)))
  1641. (goto-char (org-list-get-list-end begin struct prevs))))))
  1642. (defun org-end-of-item ()
  1643. "Go to the end of the current hand-formatted item.
  1644. If the cursor is not in an item, throw an error."
  1645. (interactive)
  1646. (let ((begin (org-in-item-p)))
  1647. (if (not begin)
  1648. (error "Not in an item")
  1649. (goto-char begin)
  1650. (let ((struct (org-list-struct)))
  1651. (goto-char (org-list-get-item-end begin struct))))))
  1652. (defun org-previous-item ()
  1653. "Move to the beginning of the previous item.
  1654. Item is at the same level in the current plain list. Error if not
  1655. in a plain list, or if this is the first item in the list."
  1656. (interactive)
  1657. (let ((begin (org-in-item-p)))
  1658. (if (not begin)
  1659. (error "Not in an item")
  1660. (goto-char begin)
  1661. (let* ((struct (org-list-struct))
  1662. (prevs (org-list-prevs-alist struct))
  1663. (prevp (org-list-get-prev-item begin struct prevs)))
  1664. (if prevp (goto-char prevp) (error "On first item"))))))
  1665. (defun org-next-item ()
  1666. "Move to the beginning of the next item.
  1667. Item is at the same level in the current plain list. Error if not
  1668. in a plain list, or if this is the last item in the list."
  1669. (interactive)
  1670. (let ((begin (org-in-item-p)))
  1671. (if (not begin)
  1672. (error "Not in an item")
  1673. (goto-char begin)
  1674. (let* ((struct (org-list-struct))
  1675. (prevs (org-list-prevs-alist struct))
  1676. (prevp (org-list-get-next-item begin struct prevs)))
  1677. (if prevp (goto-char prevp) (error "On last item"))))))
  1678. (defun org-move-item-down ()
  1679. "Move the plain list item at point down, i.e. swap with following item.
  1680. Subitems (items with larger indentation) are considered part of the item,
  1681. so this really moves item trees."
  1682. (interactive)
  1683. (unless (org-at-item-p) (error "Not at an item"))
  1684. (let* ((pos (point))
  1685. (col (current-column))
  1686. (actual-item (point-at-bol))
  1687. (struct (org-list-struct))
  1688. (prevs (org-list-prevs-alist struct))
  1689. (next-item (org-list-get-next-item (point-at-bol) struct prevs)))
  1690. (if (not next-item)
  1691. (progn
  1692. (goto-char pos)
  1693. (error "Cannot move this item further down"))
  1694. (setq struct
  1695. (org-list-exchange-items actual-item next-item struct))
  1696. ;; Use a short variation of `org-list-write-struct' as there's
  1697. ;; no need to go through all the steps.
  1698. (let ((old-struct (copy-tree struct))
  1699. (prevs (org-list-prevs-alist struct))
  1700. (parents (org-list-parents-alist struct)))
  1701. (org-list-struct-fix-bul struct prevs)
  1702. (org-list-struct-fix-ind struct parents)
  1703. (org-list-struct-apply-struct struct old-struct)
  1704. (goto-char (org-list-get-next-item (point-at-bol) struct prevs)))
  1705. (org-move-to-column col))))
  1706. (defun org-move-item-up ()
  1707. "Move the plain list item at point up, i.e. swap with previous item.
  1708. Subitems (items with larger indentation) are considered part of the item,
  1709. so this really moves item trees."
  1710. (interactive)
  1711. (unless (org-at-item-p) (error "Not at an item"))
  1712. (let* ((pos (point))
  1713. (col (current-column))
  1714. (actual-item (point-at-bol))
  1715. (struct (org-list-struct))
  1716. (prevs (org-list-prevs-alist struct))
  1717. (prev-item (org-list-get-prev-item (point-at-bol) struct prevs)))
  1718. (if (not prev-item)
  1719. (progn
  1720. (goto-char pos)
  1721. (error "Cannot move this item further up"))
  1722. (setq struct
  1723. (org-list-exchange-items prev-item actual-item struct))
  1724. ;; Use a short variation of `org-list-write-struct' as there's
  1725. ;; no need to go through all the steps.
  1726. (let ((old-struct (copy-tree struct))
  1727. (prevs (org-list-prevs-alist struct))
  1728. (parents (org-list-parents-alist struct)))
  1729. (org-list-struct-fix-bul struct prevs)
  1730. (org-list-struct-fix-ind struct parents)
  1731. (org-list-struct-apply-struct struct old-struct))
  1732. (org-move-to-column col))))
  1733. (defun org-insert-item (&optional checkbox)
  1734. "Insert a new item at the current level.
  1735. If cursor is before first character after bullet of the item, the
  1736. new item will be created before the current one.
  1737. If CHECKBOX is non-nil, add a checkbox next to the bullet.
  1738. Return t when things worked, nil when we are not in an item, or
  1739. item is invisible."
  1740. (let ((itemp (org-in-item-p))
  1741. (pos (point)))
  1742. ;; If cursor isn't is a list or if list is invisible, return nil.
  1743. (unless (or (not itemp)
  1744. (save-excursion
  1745. (goto-char itemp)
  1746. (org-invisible-p)))
  1747. (if (save-excursion
  1748. (goto-char itemp)
  1749. (org-at-item-timer-p))
  1750. ;; Timer list: delegate to `org-timer-item'.
  1751. (progn (org-timer-item) t)
  1752. (goto-char itemp)
  1753. (let* ((struct (org-list-struct))
  1754. (prevs (org-list-prevs-alist struct))
  1755. ;; If we're in a description list, ask for the new term.
  1756. (desc (when (org-list-get-tag itemp struct)
  1757. (concat (read-string "Term: ") " :: ")))
  1758. ;; Don't insert a checkbox if checkbox rule is applied
  1759. ;; and it is a description item.
  1760. (checkp (and checkbox
  1761. (or (not desc)
  1762. (not (cdr (assq 'checkbox
  1763. org-list-automatic-rules)))))))
  1764. (setq struct
  1765. (org-list-insert-item pos struct prevs checkp desc))
  1766. (org-list-write-struct struct (org-list-parents-alist struct))
  1767. (when checkp (org-update-checkbox-count-maybe))
  1768. (looking-at org-list-full-item-re)
  1769. (goto-char (match-end 0))
  1770. t)))))
  1771. (defun org-list-repair ()
  1772. "Make sure all items are correctly indented, with the right bullet.
  1773. This function scans the list at point, along with any sublist."
  1774. (interactive)
  1775. (unless (org-at-item-p) (error "This is not a list"))
  1776. (let* ((struct (org-list-struct))
  1777. (parents (org-list-parents-alist struct)))
  1778. (org-list-write-struct struct parents)))
  1779. (defun org-cycle-list-bullet (&optional which)
  1780. "Cycle through the different itemize/enumerate bullets.
  1781. This cycle the entire list level through the sequence:
  1782. `-' -> `+' -> `*' -> `1.' -> `1)'
  1783. If WHICH is a valid string, use that as the new bullet. If WHICH
  1784. is an integer, 0 means `-', 1 means `+' etc. If WHICH is
  1785. `previous', cycle backwards."
  1786. (interactive "P")
  1787. (unless (org-at-item-p) (error "This is not a list"))
  1788. (save-excursion
  1789. (beginning-of-line)
  1790. (let* ((struct (org-list-struct))
  1791. (parents (org-list-parents-alist struct))
  1792. (prevs (org-list-prevs-alist struct))
  1793. (list-beg (org-list-get-first-item (point) struct prevs))
  1794. (bullet (org-list-get-bullet list-beg struct))
  1795. (bullet-rule-p (cdr (assq 'bullet org-list-automatic-rules)))
  1796. (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
  1797. (case-fold-search nil)
  1798. (current (cond
  1799. ((string-match "[a-z]\\." bullet) "a.")
  1800. ((string-match "[a-z])" bullet) "a)")
  1801. ((string-match "[A-Z]\\." bullet) "A.")
  1802. ((string-match "[A-Z])" bullet) "A)")
  1803. ((string-match "\\." bullet) "1.")
  1804. ((string-match ")" bullet) "1)")
  1805. (t (org-trim bullet))))
  1806. ;; Compute list of possible bullets, depending on context
  1807. (bullet-list
  1808. (append '("-" "+" )
  1809. ;; *-bullets are not allowed at column 0
  1810. (unless (and bullet-rule-p
  1811. (looking-at "\\S-")) '("*"))
  1812. ;; Description items cannot be numbered
  1813. (unless (or (eq org-plain-list-ordered-item-terminator ?\))
  1814. (and bullet-rule-p (org-at-item-description-p)))
  1815. '("1."))
  1816. (unless (or (eq org-plain-list-ordered-item-terminator ?.)
  1817. (and bullet-rule-p (org-at-item-description-p)))
  1818. '("1)"))
  1819. (unless (or (not alpha-p)
  1820. (eq org-plain-list-ordered-item-terminator ?\))
  1821. (and bullet-rule-p (org-at-item-description-p)))
  1822. '("a." "A."))
  1823. (unless (or (not alpha-p)
  1824. (eq org-plain-list-ordered-item-terminator ?.)
  1825. (and bullet-rule-p (org-at-item-description-p)))
  1826. '("a)" "A)"))))
  1827. (len (length bullet-list))
  1828. (item-index (- len (length (member current bullet-list))))
  1829. (get-value (lambda (index) (nth (mod index len) bullet-list)))
  1830. (new (cond
  1831. ((member which bullet-list) which)
  1832. ((numberp which) (funcall get-value which))
  1833. ((eq 'previous which) (funcall get-value (1- item-index)))
  1834. (t (funcall get-value (1+ item-index))))))
  1835. ;; Use a short variation of `org-list-write-struct' as there's
  1836. ;; no need to go through all the steps.
  1837. (let ((old-struct (copy-tree struct)))
  1838. (org-list-set-bullet list-beg struct (org-list-bullet-string new))
  1839. (org-list-struct-fix-bul struct prevs)
  1840. (org-list-struct-fix-ind struct parents)
  1841. (org-list-struct-apply-struct struct old-struct)))))
  1842. (defun org-toggle-checkbox (&optional toggle-presence)
  1843. "Toggle the checkbox in the current line.
  1844. With prefix arg TOGGLE-PRESENCE, add or remove checkboxes. With
  1845. double prefix, set checkbox to [-].
  1846. When there is an active region, toggle status or presence of the
  1847. first checkbox there, and make every item inside have the
  1848. same status or presence, respectively.
  1849. If the cursor is in a headline, apply this to all checkbox items
  1850. in the text below the heading, taking as reference the first item
  1851. in subtree, ignoring drawers."
  1852. (interactive "P")
  1853. (save-excursion
  1854. (let* (singlep
  1855. block-item
  1856. lim-up
  1857. lim-down
  1858. (orderedp (ignore-errors (org-entry-get nil "ORDERED")))
  1859. (bounds
  1860. ;; In a region, start at first item in region
  1861. (cond
  1862. ((org-region-active-p)
  1863. (let ((limit (region-end)))
  1864. (goto-char (region-beginning))
  1865. (if (org-list-search-forward (org-item-beginning-re) limit t)
  1866. (setq lim-up (point-at-bol))
  1867. (error "No item in region"))
  1868. (setq lim-down (copy-marker limit))))
  1869. ((org-on-heading-p)
  1870. ;; On an heading, start at first item after drawers
  1871. (let ((limit (save-excursion (outline-next-heading) (point))))
  1872. (forward-line 1)
  1873. (when (looking-at org-drawer-regexp)
  1874. (re-search-forward "^[ \t]*:END:" limit nil))
  1875. (if (org-list-search-forward (org-item-beginning-re) limit t)
  1876. (setq lim-up (point-at-bol))
  1877. (error "No item in subtree"))
  1878. (setq lim-down (copy-marker limit))))
  1879. ;; Just one item: set singlep flag
  1880. ((org-at-item-p)
  1881. (setq singlep t)
  1882. (setq lim-up (point-at-bol)
  1883. lim-down (point-at-eol)))
  1884. (t (error "Not at an item or heading, and no active region"))))
  1885. ;; Determine the checkbox going to be applied to all items
  1886. ;; within bounds
  1887. (ref-checkbox
  1888. (progn
  1889. (goto-char lim-up)
  1890. (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
  1891. (cond
  1892. ((equal toggle-presence '(16)) "[-]")
  1893. ((equal toggle-presence '(4))
  1894. (unless cbox "[ ]"))
  1895. ((equal "[ ]" cbox) "[X]")
  1896. (t "[ ]"))))))
  1897. ;; When an item is found within bounds, grab the full list at
  1898. ;; point structure, then: 1. set checkbox of all its items
  1899. ;; within bounds to ref-checkbox; 2. fix checkboxes of the whole
  1900. ;; list; 3. move point after the list.
  1901. (goto-char lim-up)
  1902. (while (and (< (point) lim-down)
  1903. (org-list-search-forward (org-item-beginning-re)
  1904. lim-down 'move))
  1905. (let* ((struct (org-list-struct))
  1906. (struct-copy (copy-tree struct))
  1907. (parents (org-list-parents-alist struct))
  1908. (prevs (org-list-prevs-alist struct))
  1909. (bottom (copy-marker (org-list-get-bottom-point struct)))
  1910. (items-to-toggle (org-remove-if
  1911. (lambda (e) (or (< e lim-up) (> e lim-down)))
  1912. (mapcar 'car (cdr struct)))))
  1913. (mapc (lambda (e) (org-list-set-checkbox
  1914. e struct
  1915. ;; if there is no box at item, leave as-is
  1916. ;; unless function was called with C-u prefix
  1917. (let ((cur-box (org-list-get-checkbox e struct)))
  1918. (if (or cur-box (equal toggle-presence '(4)))
  1919. ref-checkbox
  1920. cur-box))))
  1921. items-to-toggle)
  1922. (setq block-item (org-list-struct-fix-box
  1923. struct parents prevs orderedp))
  1924. ;; Report some problems due to ORDERED status of subtree. If
  1925. ;; only one box was being checked, throw an error, else,
  1926. ;; only signal problems.
  1927. (cond
  1928. ((and singlep block-item (> lim-up block-item))
  1929. (error
  1930. "Checkbox blocked because of unchecked box at line %d"
  1931. (org-current-line block-item)))
  1932. (block-item
  1933. (message
  1934. "Checkboxes were removed due to unchecked box at line %d"
  1935. (org-current-line block-item))))
  1936. (goto-char bottom)
  1937. (org-list-struct-apply-struct struct struct-copy))))
  1938. (org-update-checkbox-count-maybe)))
  1939. (defun org-reset-checkbox-state-subtree ()
  1940. "Reset all checkboxes in an entry subtree."
  1941. (interactive "*")
  1942. (save-restriction
  1943. (save-excursion
  1944. (org-narrow-to-subtree)
  1945. (org-show-subtree)
  1946. (goto-char (point-min))
  1947. (let ((end (point-max)))
  1948. (while (< (point) end)
  1949. (when (org-at-item-checkbox-p)
  1950. (replace-match "[ ]" t t nil 1))
  1951. (beginning-of-line 2))))
  1952. (org-update-checkbox-count-maybe)))
  1953. (defun org-update-checkbox-count (&optional all)
  1954. "Update the checkbox statistics in the current section.
  1955. This will find all statistic cookies like [57%] and [6/12] and
  1956. update them with the current numbers.
  1957. With optional prefix argument ALL, do this for the whole buffer."
  1958. (interactive "P")
  1959. (save-excursion
  1960. (let ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  1961. (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
  1962. (recursivep
  1963. (or (not org-hierarchical-checkbox-statistics)
  1964. (string-match "\\<recursive\\>"
  1965. (or (ignore-errors
  1966. (org-entry-get nil "COOKIE_DATA"))
  1967. ""))))
  1968. (bounds (if all
  1969. (cons (point-min) (point-max))
  1970. (cons (or (ignore-errors (org-back-to-heading) (point))
  1971. (point-min))
  1972. (save-excursion (outline-next-heading) (point)))))
  1973. (count-boxes
  1974. (function
  1975. ;; Return number of checked boxes and boxes of all types
  1976. ;; in all structures in STRUCTS. If RECURSIVEP is non-nil,
  1977. ;; also count boxes in sub-lists. If ITEM is nil, count
  1978. ;; across the whole structure, else count only across
  1979. ;; subtree whose ancestor is ITEM.
  1980. (lambda (item structs recursivep)
  1981. (let ((c-on 0) (c-all 0))
  1982. (mapc
  1983. (lambda (s)
  1984. (let* ((pre (org-list-prevs-alist s))
  1985. (par (org-list-parents-alist s))
  1986. (items
  1987. (cond
  1988. ((and recursivep item) (org-list-get-subtree item s))
  1989. (recursivep (mapcar 'car s))
  1990. (item (org-list-get-children item s par))
  1991. (t (org-list-get-all-items
  1992. (org-list-get-top-point s) s pre))))
  1993. (cookies (delq nil (mapcar
  1994. (lambda (e)
  1995. (org-list-get-checkbox e s))
  1996. items))))
  1997. (setq c-all (+ (length cookies) c-all)
  1998. c-on (+ (org-count "[X]" cookies) c-on))))
  1999. structs)
  2000. (cons c-on c-all)))))
  2001. (backup-end 1)
  2002. cookies-list structs-bak box-num)
  2003. (goto-char (car bounds))
  2004. ;; 1. Build an alist for each cookie found within BOUNDS. The
  2005. ;; key will be position at beginning of cookie and values
  2006. ;; ending position, format of cookie, and a cell whose car is
  2007. ;; number of checked boxes to report, and cdr total number of
  2008. ;; boxes.
  2009. (while (re-search-forward cookie-re (cdr bounds) t)
  2010. (catch 'skip
  2011. (save-excursion
  2012. (push
  2013. (list
  2014. (match-beginning 1) ; cookie start
  2015. (match-end 1) ; cookie end
  2016. (match-string 2) ; percent?
  2017. (cond ; boxes count
  2018. ;; Cookie is at an heading, but specifically for todo,
  2019. ;; not for checkboxes: skip it.
  2020. ((and (org-on-heading-p)
  2021. (string-match "\\<todo\\>"
  2022. (downcase
  2023. (or (org-entry-get nil "COOKIE_DATA") ""))))
  2024. (throw 'skip nil))
  2025. ;; Cookie is at an heading, but all lists before next
  2026. ;; heading already have been read. Use data collected
  2027. ;; in STRUCTS-BAK. This should only happen when heading
  2028. ;; has more than one cookie on it.
  2029. ((and (org-on-heading-p)
  2030. (<= (save-excursion (outline-next-heading) (point))
  2031. backup-end))
  2032. (funcall count-boxes nil structs-bak recursivep))
  2033. ;; Cookie is at a fresh heading. Grab structure of
  2034. ;; every list containing a checkbox between point and
  2035. ;; next headline, and save them in STRUCTS-BAK.
  2036. ((org-on-heading-p)
  2037. (setq backup-end (save-excursion
  2038. (outline-next-heading) (point)))
  2039. (while (org-list-search-forward box-re backup-end 'move)
  2040. (let* ((struct (org-list-struct))
  2041. (bottom (org-list-get-bottom-point struct)))
  2042. (push struct structs-bak)
  2043. (goto-char bottom)))
  2044. (funcall count-boxes nil structs-bak recursivep))
  2045. ;; Cookie is at an item, and we already have list
  2046. ;; structure stored in STRUCTS-BAK.
  2047. ((and (org-at-item-p)
  2048. (< (point-at-bol) backup-end))
  2049. (funcall count-boxes (point-at-bol) structs-bak recursivep))
  2050. ;; Cookie is at an item, but we need to compute list
  2051. ;; structure.
  2052. ((org-at-item-p)
  2053. (let ((struct (org-list-struct)))
  2054. (setq backup-end (org-list-get-bottom-point struct)
  2055. structs-bak (list struct)))
  2056. (funcall count-boxes (point-at-bol) structs-bak recursivep))
  2057. ;; Else, cookie found is at a wrong place. Skip it.
  2058. (t (throw 'skip nil))))
  2059. cookies-list))))
  2060. ;; 2. Apply alist to buffer, in reverse order so positions stay
  2061. ;; unchanged after cookie modifications.
  2062. (mapc (lambda (cookie)
  2063. (let* ((beg (car cookie))
  2064. (end (nth 1 cookie))
  2065. (percentp (nth 2 cookie))
  2066. (checked (car (nth 3 cookie)))
  2067. (total (cdr (nth 3 cookie)))
  2068. (new (if percentp
  2069. (format "[%d%%]" (/ (* 100 checked)
  2070. (max 1 total)))
  2071. (format "[%d/%d]" checked total))))
  2072. (goto-char beg)
  2073. (insert new)
  2074. (delete-region (point) (+ (point) (- end beg)))))
  2075. cookies-list))))
  2076. (defun org-get-checkbox-statistics-face ()
  2077. "Select the face for checkbox statistics.
  2078. The face will be `org-done' when all relevant boxes are checked.
  2079. Otherwise it will be `org-todo'."
  2080. (if (match-end 1)
  2081. (if (equal (match-string 1) "100%")
  2082. 'org-checkbox-statistics-done
  2083. 'org-checkbox-statistics-todo)
  2084. (if (and (> (match-end 2) (match-beginning 2))
  2085. (equal (match-string 2) (match-string 3)))
  2086. 'org-checkbox-statistics-done
  2087. 'org-checkbox-statistics-todo)))
  2088. (defun org-update-checkbox-count-maybe ()
  2089. "Update checkbox statistics unless turned off by user."
  2090. (when (cdr (assq 'checkbox org-list-automatic-rules))
  2091. (org-update-checkbox-count))
  2092. (run-hooks 'org-checkbox-statistics-hook))
  2093. (defvar org-last-indent-begin-marker (make-marker))
  2094. (defvar org-last-indent-end-marker (make-marker))
  2095. (defun org-list-indent-item-generic (arg no-subtree struct)
  2096. "Indent a local list item including its children.
  2097. When number ARG is a negative, item will be outdented, otherwise
  2098. it will be indented.
  2099. If a region is active, all items inside will be moved.
  2100. If NO-SUBTREE is non-nil, only indent the item itself, not its
  2101. children.
  2102. STRUCT is the list structure. Return t if successful."
  2103. (save-excursion
  2104. (beginning-of-line)
  2105. (let* ((regionp (org-region-active-p))
  2106. (rbeg (and regionp (region-beginning)))
  2107. (rend (and regionp (region-end)))
  2108. (top (org-list-get-top-point struct))
  2109. (parents (org-list-parents-alist struct))
  2110. (prevs (org-list-prevs-alist struct))
  2111. ;; Are we going to move the whole list?
  2112. (specialp
  2113. (and (= top (point))
  2114. (cdr (assq 'indent org-list-automatic-rules))
  2115. (if no-subtree
  2116. (error
  2117. "First item of list cannot move without its subtree")
  2118. t))))
  2119. ;; Determine begin and end points of zone to indent. If moving
  2120. ;; more than one item, save them for subsequent moves.
  2121. (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
  2122. (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
  2123. (if regionp
  2124. (progn
  2125. (set-marker org-last-indent-begin-marker rbeg)
  2126. (set-marker org-last-indent-end-marker rend))
  2127. (set-marker org-last-indent-begin-marker (point))
  2128. (set-marker org-last-indent-end-marker
  2129. (cond
  2130. (specialp (org-list-get-bottom-point struct))
  2131. (no-subtree (1+ (point)))
  2132. (t (org-list-get-item-end (point) struct))))))
  2133. (let* ((beg (marker-position org-last-indent-begin-marker))
  2134. (end (marker-position org-last-indent-end-marker)))
  2135. (cond
  2136. ;; Special case: moving top-item with indent rule
  2137. (specialp
  2138. (let* ((level-skip (org-level-increment))
  2139. (offset (if (< arg 0) (- level-skip) level-skip))
  2140. (top-ind (org-list-get-ind beg struct))
  2141. (old-struct (copy-tree struct)))
  2142. (if (< (+ top-ind offset) 0)
  2143. (error "Cannot outdent beyond margin")
  2144. ;; Change bullet if necessary
  2145. (when (and (= (+ top-ind offset) 0)
  2146. (string-match "*"
  2147. (org-list-get-bullet beg struct)))
  2148. (org-list-set-bullet beg struct
  2149. (org-list-bullet-string "-")))
  2150. ;; Shift every item by OFFSET and fix bullets. Then
  2151. ;; apply changes to buffer.
  2152. (mapc (lambda (e)
  2153. (let ((ind (org-list-get-ind (car e) struct)))
  2154. (org-list-set-ind (car e) struct (+ ind offset))))
  2155. struct)
  2156. (org-list-struct-fix-bul struct prevs)
  2157. (org-list-struct-apply-struct struct old-struct))))
  2158. ;; Forbidden move:
  2159. ((and (< arg 0)
  2160. ;; If only one item is moved, it mustn't have a child
  2161. (or (and no-subtree
  2162. (not regionp)
  2163. (org-list-has-child-p beg struct))
  2164. ;; If a subtree or region is moved, the last item
  2165. ;; of the subtree mustn't have a child
  2166. (let ((last-item (caar
  2167. (reverse
  2168. (org-remove-if
  2169. (lambda (e) (>= (car e) end))
  2170. struct)))))
  2171. (org-list-has-child-p last-item struct))))
  2172. (error "Cannot outdent an item without its children"))
  2173. ;; Normal shifting
  2174. (t
  2175. (let* ((new-parents
  2176. (if (< arg 0)
  2177. (org-list-struct-outdent beg end struct parents)
  2178. (org-list-struct-indent beg end struct parents prevs))))
  2179. (org-list-write-struct struct new-parents))
  2180. (org-update-checkbox-count-maybe))))))
  2181. t)
  2182. (defun org-outdent-item ()
  2183. "Outdent a local list item, but not its children.
  2184. If a region is active, all items inside will be moved."
  2185. (interactive)
  2186. (if (org-at-item-p)
  2187. (let ((struct (org-list-struct)))
  2188. (org-list-indent-item-generic -1 t struct))
  2189. (error "Not at an item")))
  2190. (defun org-indent-item ()
  2191. "Indent a local list item, but not its children.
  2192. If a region is active, all items inside will be moved."
  2193. (interactive)
  2194. (if (org-at-item-p)
  2195. (let ((struct (org-list-struct)))
  2196. (org-list-indent-item-generic 1 t struct))
  2197. (error "Not at an item")))
  2198. (defun org-outdent-item-tree ()
  2199. "Outdent a local list item including its children.
  2200. If a region is active, all items inside will be moved."
  2201. (interactive)
  2202. (let ((regionp (org-region-active-p)))
  2203. (cond
  2204. ((or (org-at-item-p)
  2205. (and (org-region-active-p)
  2206. (goto-char (region-beginning))
  2207. (org-at-item-p)))
  2208. (let ((struct (org-list-struct)))
  2209. (org-list-indent-item-generic -1 nil struct)))
  2210. (regionp (error "Region not starting at an item"))
  2211. (t (error "Not at an item")))))
  2212. (defun org-indent-item-tree ()
  2213. "Indent a local list item including its children.
  2214. If a region is active, all items inside will be moved."
  2215. (interactive)
  2216. (let ((regionp (org-region-active-p)))
  2217. (cond
  2218. ((or (org-at-item-p)
  2219. (and (org-region-active-p)
  2220. (goto-char (region-beginning))
  2221. (org-at-item-p)))
  2222. (let ((struct (org-list-struct)))
  2223. (org-list-indent-item-generic 1 nil struct)))
  2224. (regionp (error "Region not starting at an item"))
  2225. (t (error "Not at an item")))))
  2226. (defvar org-tab-ind-state)
  2227. (defun org-cycle-item-indentation ()
  2228. "Cycle levels of indentation of an empty item.
  2229. The first run indents the item, if applicable. Subsequents runs
  2230. outdent it at meaningful levels in the list. When done, item is
  2231. put back at its original position with its original bullet.
  2232. Return t at each successful move."
  2233. (when (org-at-item-p)
  2234. (let* ((org-adapt-indentation nil)
  2235. (struct (org-list-struct))
  2236. (ind (org-list-get-ind (point-at-bol) struct))
  2237. (bullet (org-list-get-bullet (point-at-bol) struct)))
  2238. ;; Check that item is really empty
  2239. (when (and (save-excursion
  2240. (beginning-of-line)
  2241. (looking-at org-list-full-item-re))
  2242. (>= (match-end 0) (save-excursion
  2243. (goto-char (org-list-get-item-end
  2244. (point-at-bol) struct))
  2245. (skip-chars-backward " \r\t\n")
  2246. (point))))
  2247. (setq this-command 'org-cycle-item-indentation)
  2248. ;; When in the middle of the cycle, try to outdent first. If it
  2249. ;; fails, and point is still at initial position, indent. Else,
  2250. ;; go back to original position.
  2251. (if (eq last-command 'org-cycle-item-indentation)
  2252. (cond
  2253. ((ignore-errors (org-list-indent-item-generic -1 t struct)))
  2254. ((and (= ind (car org-tab-ind-state))
  2255. (ignore-errors (org-list-indent-item-generic 1 t struct))))
  2256. (t (back-to-indentation)
  2257. (org-indent-to-column (car org-tab-ind-state))
  2258. (looking-at "\\S-+")
  2259. (replace-match (cdr org-tab-ind-state))
  2260. (end-of-line)
  2261. ;; Break cycle
  2262. (setq this-command 'identity)))
  2263. ;; If a cycle is starting, remember indentation and bullet,
  2264. ;; then try to indent. If it fails, try to outdent.
  2265. (setq org-tab-ind-state (cons ind bullet))
  2266. (cond
  2267. ((ignore-errors (org-list-indent-item-generic 1 t struct)))
  2268. ((ignore-errors (org-list-indent-item-generic -1 t struct)))
  2269. (t (error "Cannot move item"))))
  2270. t))))
  2271. (defun org-sort-list (&optional with-case sorting-type getkey-func compare-func)
  2272. "Sort plain list items.
  2273. The cursor may be at any item of the list that should be sorted.
  2274. Sublists are not sorted. Checkboxes, if any, are ignored.
  2275. Sorting can be alphabetically, numerically, by date/time as given by
  2276. a time stamp, by a property or by priority.
  2277. Comparing entries ignores case by default. However, with an
  2278. optional argument WITH-CASE, the sorting considers case as well.
  2279. The command prompts for the sorting type unless it has been given
  2280. to the function through the SORTING-TYPE argument, which needs to
  2281. be a character, \(?n ?N ?a ?A ?t ?T ?f ?F). Here is the precise
  2282. meaning of each character:
  2283. n Numerically, by converting the beginning of the item to a number.
  2284. a Alphabetically. Only the first line of item is checked.
  2285. t By date/time, either the first active time stamp in the entry, if
  2286. any, or by the first inactive one. In a timer list, sort the timers.
  2287. Capital letters will reverse the sort order.
  2288. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a
  2289. function to be called with point at the beginning of the record.
  2290. It must return either a string or a number that should serve as
  2291. the sorting key for that record. It will then use COMPARE-FUNC to
  2292. compare entries."
  2293. (interactive "P")
  2294. (let* ((case-func (if with-case 'identity 'downcase))
  2295. (struct (org-list-struct))
  2296. (prevs (org-list-prevs-alist struct))
  2297. (start (org-list-get-list-begin (point-at-bol) struct prevs))
  2298. (end (org-list-get-list-end (point-at-bol) struct prevs))
  2299. (sorting-type
  2300. (progn
  2301. (message
  2302. "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:")
  2303. (read-char-exclusive)))
  2304. (getkey-func (and (= (downcase sorting-type) ?f)
  2305. (org-icompleting-read "Sort using function: "
  2306. obarray 'fboundp t nil nil)
  2307. (intern getkey-func))))
  2308. (message "Sorting items...")
  2309. (save-restriction
  2310. (narrow-to-region start end)
  2311. (goto-char (point-min))
  2312. (let* ((dcst (downcase sorting-type))
  2313. (case-fold-search nil)
  2314. (now (current-time))
  2315. (sort-func (cond
  2316. ((= dcst ?a) 'string<)
  2317. ((= dcst ?f) compare-func)
  2318. ((= dcst ?t) '<)
  2319. (t nil)))
  2320. (next-record (lambda ()
  2321. (skip-chars-forward " \r\t\n")
  2322. (beginning-of-line)))
  2323. (end-record (lambda ()
  2324. (goto-char (org-list-get-item-end-before-blank
  2325. (point) struct))))
  2326. (value-to-sort
  2327. (lambda ()
  2328. (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
  2329. (cond
  2330. ((= dcst ?n)
  2331. (string-to-number (buffer-substring (match-end 0)
  2332. (point-at-eol))))
  2333. ((= dcst ?a)
  2334. (buffer-substring (match-end 0) (point-at-eol)))
  2335. ((= dcst ?t)
  2336. (cond
  2337. ;; If it is a timer list, convert timer to seconds
  2338. ((org-at-item-timer-p)
  2339. (org-timer-hms-to-secs (match-string 1)))
  2340. ((or (re-search-forward org-ts-regexp (point-at-eol) t)
  2341. (re-search-forward org-ts-regexp-both
  2342. (point-at-eol) t))
  2343. (org-time-string-to-seconds (match-string 0)))
  2344. (t (org-float-time now))))
  2345. ((= dcst ?f)
  2346. (if getkey-func
  2347. (let ((value (funcall getkey-func)))
  2348. (if (stringp value)
  2349. (funcall case-func value)
  2350. value))
  2351. (error "Invalid key function `%s'" getkey-func)))
  2352. (t (error "Invalid sorting type `%c'" sorting-type)))))))
  2353. (sort-subr (/= dcst sorting-type)
  2354. next-record
  2355. end-record
  2356. value-to-sort
  2357. nil
  2358. sort-func)
  2359. ;; Read and fix list again, as `sort-subr' probably destroyed
  2360. ;; its structure.
  2361. (org-list-repair)
  2362. (run-hooks 'org-after-sorting-entries-or-items-hook)
  2363. (message "Sorting items...done")))))
  2364. ;;; Send and receive lists
  2365. (defun org-list-parse-list (&optional delete)
  2366. "Parse the list at point and maybe DELETE it.
  2367. Return a list whose car is a symbol of list type, among
  2368. `ordered', `unordered' and `descriptive'. Then, each item is a
  2369. list whose car is counter, and cdr are strings and other
  2370. sub-lists. Inside strings, checkboxes are replaced by \"[CBON]\"
  2371. and \"[CBOFF]\".
  2372. For example, the following list:
  2373. 1. first item
  2374. + sub-item one
  2375. + [X] sub-item two
  2376. more text in first item
  2377. 2. [@3] last item
  2378. will be parsed as:
  2379. \(ordered
  2380. \(nil \"first item\"
  2381. \(unordered
  2382. \(nil \"sub-item one\"\)
  2383. \(nil \"[CBON] sub-item two\"\)\)
  2384. \"more text in first item\"\)
  2385. \(3 \"last item\"\)\)
  2386. Point is left at list end."
  2387. (let* ((struct (org-list-struct))
  2388. (prevs (org-list-prevs-alist struct))
  2389. (parents (org-list-parents-alist struct))
  2390. (top (org-list-get-top-point struct))
  2391. (bottom (org-list-get-bottom-point struct))
  2392. out
  2393. parse-item ; for byte-compiler
  2394. (get-text
  2395. (function
  2396. ;; Return text between BEG and END, trimmed, with
  2397. ;; checkboxes replaced.
  2398. (lambda (beg end)
  2399. (let ((text (org-trim (buffer-substring beg end))))
  2400. (if (string-match "\\`\\[\\([X ]\\)\\]" text)
  2401. (replace-match
  2402. (if (equal (match-string 1 text) " ") "CBOFF" "CBON")
  2403. t nil text 1)
  2404. text)))))
  2405. (parse-sublist
  2406. (function
  2407. ;; Return a list whose car is list type and cdr a list of
  2408. ;; items' body.
  2409. (lambda (e)
  2410. (cons (org-list-get-list-type (car e) struct prevs)
  2411. (mapcar parse-item e)))))
  2412. (parse-item
  2413. (function
  2414. ;; Return a list containing conter of item, if any, text
  2415. ;; and any sublist inside it.
  2416. (lambda (e)
  2417. (let ((start (save-excursion
  2418. (goto-char e)
  2419. (or (org-at-item-counter-p) (org-at-item-p))
  2420. (match-end 0)))
  2421. ;; Get counter number. For alphabetic counter, get
  2422. ;; its position in the alphabet.
  2423. (counter (let ((c (org-list-get-counter e struct)))
  2424. (cond
  2425. ((not c) nil)
  2426. ((string-match "[A-Za-z]" c)
  2427. (- (string-to-char (upcase (match-string 0 c)))
  2428. 64))
  2429. ((string-match "[0-9]+" c)
  2430. (string-to-number (match-string 0 c))))))
  2431. (childp (org-list-has-child-p e struct))
  2432. (end (org-list-get-item-end e struct)))
  2433. ;; If item has a child, store text between bullet and
  2434. ;; next child, then recursively parse all sublists. At
  2435. ;; the end of each sublist, check for the presence of
  2436. ;; text belonging to the original item.
  2437. (if childp
  2438. (let* ((children (org-list-get-children e struct parents))
  2439. (body (list (funcall get-text start childp))))
  2440. (while children
  2441. (let* ((first (car children))
  2442. (sub (org-list-get-all-items first struct prevs))
  2443. (last-c (car (last sub)))
  2444. (last-end (org-list-get-item-end last-c struct)))
  2445. (push (funcall parse-sublist sub) body)
  2446. ;; Remove children from the list just parsed.
  2447. (setq children (cdr (member last-c children)))
  2448. ;; There is a chunk of text belonging to the
  2449. ;; item if last child doesn't end where next
  2450. ;; child starts or where item ends.
  2451. (unless (= (or (car children) end) last-end)
  2452. (push (funcall get-text
  2453. last-end (or (car children) end))
  2454. body))))
  2455. (cons counter (nreverse body)))
  2456. (list counter (funcall get-text start end))))))))
  2457. ;; Store output, take care of cursor position and deletion of
  2458. ;; list, then return output.
  2459. (setq out (funcall parse-sublist (org-list-get-all-items top struct prevs)))
  2460. (goto-char top)
  2461. (when delete
  2462. (delete-region top bottom)
  2463. (when (and (not (eq org-list-ending-method 'indent))
  2464. (looking-at org-list-end-re))
  2465. (replace-match "\n")))
  2466. out))
  2467. (defun org-list-make-subtree ()
  2468. "Convert the plain list at point into a subtree."
  2469. (interactive)
  2470. (if (not (ignore-errors (goto-char (org-in-item-p))))
  2471. (error "Not in a list")
  2472. (let ((list (save-excursion (org-list-parse-list t))))
  2473. (insert (org-list-to-subtree list)))))
  2474. (defun org-list-insert-radio-list ()
  2475. "Insert a radio list template appropriate for this major mode."
  2476. (interactive)
  2477. (let* ((e (assq major-mode org-list-radio-list-templates))
  2478. (txt (nth 1 e))
  2479. name pos)
  2480. (unless e (error "No radio list setup defined for %s" major-mode))
  2481. (setq name (read-string "List name: "))
  2482. (while (string-match "%n" txt)
  2483. (setq txt (replace-match name t t txt)))
  2484. (or (bolp) (insert "\n"))
  2485. (setq pos (point))
  2486. (insert txt)
  2487. (goto-char pos)))
  2488. (defun org-list-send-list (&optional maybe)
  2489. "Send a transformed version of this list to the receiver position.
  2490. With argument MAYBE, fail quietly if no transformation is defined for
  2491. this list."
  2492. (interactive)
  2493. (catch 'exit
  2494. (unless (org-at-item-p) (error "Not at a list item"))
  2495. (save-excursion
  2496. (re-search-backward "#\\+ORGLST" nil t)
  2497. (unless (looking-at "[ \t]*#\\+ORGLST[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
  2498. (if maybe
  2499. (throw 'exit nil)
  2500. (error "Don't know how to transform this list"))))
  2501. (let* ((name (match-string 1))
  2502. (transform (intern (match-string 2)))
  2503. (bottom-point
  2504. (save-excursion
  2505. (re-search-forward
  2506. "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t)
  2507. (match-beginning 0)))
  2508. (top-point
  2509. (progn
  2510. (re-search-backward "#\\+ORGLST" nil t)
  2511. (re-search-forward (org-item-beginning-re) bottom-point t)
  2512. (match-beginning 0)))
  2513. (list (save-restriction
  2514. (narrow-to-region top-point bottom-point)
  2515. (org-list-parse-list)))
  2516. beg txt)
  2517. (unless (fboundp transform)
  2518. (error "No such transformation function %s" transform))
  2519. (let ((txt (funcall transform list)))
  2520. ;; Find the insertion place
  2521. (save-excursion
  2522. (goto-char (point-min))
  2523. (unless (re-search-forward
  2524. (concat "BEGIN RECEIVE ORGLST +"
  2525. name
  2526. "\\([ \t]\\|$\\)") nil t)
  2527. (error "Don't know where to insert translated list"))
  2528. (goto-char (match-beginning 0))
  2529. (beginning-of-line 2)
  2530. (setq beg (point))
  2531. (unless (re-search-forward (concat "END RECEIVE ORGLST +" name) nil t)
  2532. (error "Cannot find end of insertion region"))
  2533. (delete-region beg (point-at-bol))
  2534. (goto-char beg)
  2535. (insert txt "\n")))
  2536. (message "List converted and installed at receiver location"))))
  2537. (defun org-list-to-generic (list params)
  2538. "Convert a LIST parsed through `org-list-parse-list' to other formats.
  2539. Valid parameters PARAMS are
  2540. :ustart String to start an unordered list
  2541. :uend String to end an unordered list
  2542. :ostart String to start an ordered list
  2543. :oend String to end an ordered list
  2544. :dstart String to start a descriptive list
  2545. :dend String to end a descriptive list
  2546. :dtstart String to start a descriptive term
  2547. :dtend String to end a descriptive term
  2548. :ddstart String to start a description
  2549. :ddend String to end a description
  2550. :splice When set to t, return only list body lines, don't wrap
  2551. them into :[u/o]start and :[u/o]end. Default is nil.
  2552. :istart String to start a list item.
  2553. :icount String to start an item with a counter.
  2554. :iend String to end a list item
  2555. :isep String to separate items
  2556. :lsep String to separate sublists
  2557. :csep String to separate text from a sub-list
  2558. :cboff String to insert for an unchecked checkbox
  2559. :cbon String to insert for a checked checkbox
  2560. Alternatively, each parameter can also be a form returning a
  2561. string. These sexp can use keywords `counter' and `depth',
  2562. reprensenting respectively counter associated to the current
  2563. item, and depth of the current sub-list, starting at 0.
  2564. Obviously, `counter' is only available for parameters applying to
  2565. items."
  2566. (interactive)
  2567. (let* ((p params)
  2568. (splicep (plist-get p :splice))
  2569. (ostart (plist-get p :ostart))
  2570. (oend (plist-get p :oend))
  2571. (ustart (plist-get p :ustart))
  2572. (uend (plist-get p :uend))
  2573. (dstart (plist-get p :dstart))
  2574. (dend (plist-get p :dend))
  2575. (dtstart (plist-get p :dtstart))
  2576. (dtend (plist-get p :dtend))
  2577. (ddstart (plist-get p :ddstart))
  2578. (ddend (plist-get p :ddend))
  2579. (istart (plist-get p :istart))
  2580. (icount (plist-get p :icount))
  2581. (iend (plist-get p :iend))
  2582. (isep (plist-get p :isep))
  2583. (lsep (plist-get p :lsep))
  2584. (csep (plist-get p :csep))
  2585. (cbon (plist-get p :cbon))
  2586. (cboff (plist-get p :cboff))
  2587. export-sublist ; for byte-compiler
  2588. (export-item
  2589. (function
  2590. ;; Export an item ITEM of type TYPE, at DEPTH. First string
  2591. ;; in item is treated in a special way as it can bring
  2592. ;; extra information that needs to be processed.
  2593. (lambda (item type depth)
  2594. (let* ((counter (pop item))
  2595. (fmt (concat (cond
  2596. ((eq type 'descriptive)
  2597. (concat (org-trim (eval istart)) "%s"
  2598. (eval ddend)))
  2599. ((and counter (eq type 'ordered))
  2600. (concat (eval icount) "%s"))
  2601. (t (concat (eval istart) "%s")))
  2602. (eval iend)))
  2603. (first (car item)))
  2604. ;; Replace checkbox if any is found.
  2605. (cond
  2606. ((string-match "\\[CBON\\]" first)
  2607. (setq first (replace-match cbon t t first)))
  2608. ((string-match "\\[CBOFF\\]" first)
  2609. (setq first (replace-match cboff t t first)))
  2610. ((string-match "\\[-\\]" first)
  2611. (setq first (replace-match "$\\boxminus$" t t first))))
  2612. ;; Insert descriptive term if TYPE is `descriptive'.
  2613. (when (and (eq type 'descriptive)
  2614. (string-match "^\\(.*\\)[ \t]+::" first))
  2615. (setq first (concat
  2616. (eval dtstart) (org-trim (match-string 1 first))
  2617. (eval dtend) (eval ddstart)
  2618. (org-trim (substring first (match-end 0))) "")))
  2619. (setcar item first)
  2620. (format fmt
  2621. (mapconcat (lambda (e)
  2622. (if (stringp e) e
  2623. (funcall export-sublist e (1+ depth))))
  2624. item (or (eval csep) "")))))))
  2625. (export-sublist
  2626. (function
  2627. ;; Export sublist SUB at DEPTH
  2628. (lambda (sub depth)
  2629. (let* ((type (car sub))
  2630. (items (cdr sub))
  2631. (fmt (concat (cond
  2632. (splicep "%s")
  2633. ((eq type 'ordered)
  2634. (concat (eval ostart) "\n%s" (eval oend)))
  2635. ((eq type 'descriptive)
  2636. (concat (eval dstart) "\n%s" (eval dend)))
  2637. (t (concat (eval ustart) "\n%s" (eval uend))))
  2638. (eval lsep))))
  2639. (format fmt (mapconcat (lambda (e)
  2640. (funcall export-item e type depth))
  2641. items (or (eval isep) ""))))))))
  2642. (concat (funcall export-sublist list 0) "\n")))
  2643. (defun org-list-to-latex (list &optional params)
  2644. "Convert LIST into a LaTeX list.
  2645. LIST is as returned by `org-list-parse-list'. PARAMS is a property list
  2646. with overruling parameters for `org-list-to-generic'."
  2647. (org-list-to-generic
  2648. list
  2649. (org-combine-plists
  2650. '(:splice nil :ostart "\\begin{enumerate}" :oend "\\end{enumerate}"
  2651. :ustart "\\begin{itemize}" :uend "\\end{itemize}"
  2652. :dstart "\\begin{description}" :dend "\\end{description}"
  2653. :dtstart "[" :dtend "] "
  2654. :istart "\\item " :iend "\n"
  2655. :icount (let ((enum (nth depth '("i" "ii" "iii" "iv"))))
  2656. (if enum
  2657. (format "\\setcounter{enum%s}{%s}\n\\item "
  2658. enum counter)
  2659. "\\item "))
  2660. :csep "\n"
  2661. :cbon "\\texttt{[X]}" :cboff "\\texttt{[ ]}")
  2662. params)))
  2663. (defun org-list-to-html (list &optional params)
  2664. "Convert LIST into a HTML list.
  2665. LIST is as returned by `org-list-parse-list'. PARAMS is a property list
  2666. with overruling parameters for `org-list-to-generic'."
  2667. (org-list-to-generic
  2668. list
  2669. (org-combine-plists
  2670. '(:splice nil :ostart "<ol>" :oend "\n</ol>"
  2671. :ustart "<ul>" :uend "\n</ul>"
  2672. :dstart "<dl>" :dend "</dl>"
  2673. :dtstart "<dt>" :dtend "</dt>\n"
  2674. :ddstart "<dd>" :ddend "</dd>"
  2675. :istart "<li>" :iend "</li>"
  2676. :icount (format "<li value=\"%s\">" counter)
  2677. :isep "\n" :lsep "\n" :csep "\n"
  2678. :cbon "<code>[X]</code>" :cboff "<code>[ ]</code>")
  2679. params)))
  2680. (defun org-list-to-texinfo (list &optional params)
  2681. "Convert LIST into a Texinfo list.
  2682. LIST is as returned by `org-list-parse-list'. PARAMS is a property list
  2683. with overruling parameters for `org-list-to-generic'."
  2684. (org-list-to-generic
  2685. list
  2686. (org-combine-plists
  2687. '(:splice nil :ostart "@itemize @minus" :oend "@end itemize"
  2688. :ustart "@enumerate" :uend "@end enumerate"
  2689. :dstart "@table @asis" :dend "@end table"
  2690. :dtstart " " :dtend "\n"
  2691. :istart "@item\n" :iend "\n"
  2692. :icount "@item\n"
  2693. :csep "\n"
  2694. :cbon "@code{[X]}" :cboff "@code{[ ]}")
  2695. params)))
  2696. (defun org-list-to-subtree (list &optional params)
  2697. "Convert LIST into an Org subtree.
  2698. LIST is as returned by `org-list-parse-list'. PARAMS is a property list
  2699. with overruling parameters for `org-list-to-generic'."
  2700. (let* ((rule (cdr (assq 'heading org-blank-before-new-entry)))
  2701. (level (or (org-current-level) 0))
  2702. (blankp (or (eq rule t)
  2703. (and (eq rule 'auto)
  2704. (save-excursion
  2705. (outline-previous-heading)
  2706. (org-previous-line-empty-p)))))
  2707. (get-stars
  2708. (function
  2709. ;; Return the string for the heading, depending on depth D
  2710. ;; of current sub-list.
  2711. (lambda (d)
  2712. (concat
  2713. (make-string (+ level
  2714. (if org-odd-levels-only (* 2 (1+ d)) (1+ d)))
  2715. ?*)
  2716. " ")))))
  2717. (org-list-to-generic
  2718. list
  2719. (org-combine-plists
  2720. '(:splice t
  2721. :dtstart " " :dtend " "
  2722. :istart (funcall get-stars depth)
  2723. :icount (funcall get-stars depth)
  2724. :isep (if blankp "\n\n" "\n")
  2725. :csep (if blankp "\n\n" "\n")
  2726. :cbon "DONE" :cboff "TODO")
  2727. params))))
  2728. (provide 'org-list)
  2729. ;; arch-tag: 73cf50c1-200f-4d1d-8a53-4e842a5b11c8
  2730. ;;; org-list.el ends here