org-list.el 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612
  1. ;;; org-list.el --- Plain lists for Org -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2004-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; URL: https://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  23. ;;
  24. ;;; Commentary:
  25. ;; This file contains the code dealing with plain lists in Org mode.
  26. ;; The core concept behind lists is their structure. A structure is
  27. ;; a snapshot of the list, in the shape of a data tree (see
  28. ;; `org-list-struct').
  29. ;; Once the list structure is stored, it is possible to make changes
  30. ;; on it that will be mirrored to the real list or to get information
  31. ;; about the list, using accessors and methods provided in the
  32. ;; library. Most of them require the use of one or two helper
  33. ;; functions, namely `org-list-parents-alist' and
  34. ;; `org-list-prevs-alist'.
  35. ;; Structure is eventually applied to the buffer with
  36. ;; `org-list-write-struct'. This function repairs (bullets,
  37. ;; indentation, checkboxes) the list in the process. It should be
  38. ;; called near the end of any function working on structures.
  39. ;; Thus, a function applying to lists should usually follow this
  40. ;; template:
  41. ;; 1. Verify point is in a list and grab item beginning (with the same
  42. ;; function `org-in-item-p'). If the function requires the cursor
  43. ;; to be at item's bullet, `org-at-item-p' is more selective. It
  44. ;; is also possible to move point to the closest item with
  45. ;; `org-list-search-backward', or `org-list-search-forward',
  46. ;; applied to the function `org-item-beginning-re'.
  47. ;; 2. Get list structure with `org-list-struct'.
  48. ;; 3. Compute one, or both, helper functions,
  49. ;; (`org-list-parents-alist', `org-list-prevs-alist') depending on
  50. ;; needed accessors.
  51. ;; 4. Proceed with the modifications, using methods and accessors.
  52. ;; 5. Verify and apply structure to buffer, using
  53. ;; `org-list-write-struct'.
  54. ;; 6. If changes made to the list might have modified check-boxes,
  55. ;; call `org-update-checkbox-count-maybe'.
  56. ;; Computing a structure can be a costly operation on huge lists (a
  57. ;; few thousand lines long). Thus, code should follow the rule:
  58. ;; "collect once, use many". As a corollary, it is usually a bad idea
  59. ;; to use directly an interactive function inside the code, as those,
  60. ;; being independent entities, read the whole list structure another
  61. ;; time.
  62. ;;; Code:
  63. (require 'org-macs)
  64. (org-assert-version)
  65. (require 'cl-lib)
  66. (require 'org-macs)
  67. (require 'org-compat)
  68. (require 'org-fold-core)
  69. (defvar org-M-RET-may-split-line)
  70. (defvar org-adapt-indentation)
  71. (defvar org-auto-align-tags)
  72. (defvar org-blank-before-new-entry)
  73. (defvar org-clock-string)
  74. (defvar org-closed-string)
  75. (defvar org-deadline-string)
  76. (defvar org-done-keywords)
  77. (defvar org-drawer-regexp)
  78. (defvar org-element-all-objects)
  79. (defvar org-inhibit-startup)
  80. (defvar org-loop-over-headlines-in-active-region)
  81. (defvar org-odd-levels-only)
  82. (defvar org-outline-regexp-bol)
  83. (defvar org-scheduled-string)
  84. (defvar org-todo-line-regexp)
  85. (defvar org-ts-regexp)
  86. (defvar org-ts-regexp-both)
  87. (declare-function org-at-heading-p "org" (&optional invisible-ok))
  88. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  89. (declare-function org-before-first-heading-p "org" ())
  90. (declare-function org-current-level "org" ())
  91. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  92. (declare-function org-element-context "org-element" (&optional element))
  93. (declare-function org-element-interpret-data "org-element" (data))
  94. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  95. (declare-function org-element-macro-interpreter "org-element" (macro ##))
  96. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  97. (declare-function org-element-normalize-string "org-element" (s))
  98. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  99. (declare-function org-element-property "org-element" (property element))
  100. (declare-function org-element-put-property "org-element" (element property value))
  101. (declare-function org-element-set-element "org-element" (old new))
  102. (declare-function org-element-type "org-element" (element))
  103. (declare-function org-element-update-syntax "org-element" ())
  104. (declare-function org-end-of-meta-data "org" (&optional full))
  105. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  106. (declare-function org-export-create-backend "ox" (&rest rest) t)
  107. (declare-function org-export-data-with-backend "ox" (data backend info))
  108. (declare-function org-export-get-backend "ox" (name))
  109. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  110. (declare-function org-export-get-next-element "ox" (blob info &optional n))
  111. (declare-function org-export-with-backend "ox" (backend data &optional contents info))
  112. (declare-function org-fix-tags-on-the-fly "org" ())
  113. (declare-function org-get-todo-state "org" ())
  114. (declare-function org-in-block-p "org" (names))
  115. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  116. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  117. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  118. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  119. (declare-function org-level-increment "org" ())
  120. (declare-function org-mode "org" ())
  121. (declare-function org-narrow-to-subtree "org" (&optional element))
  122. (declare-function org-outline-level "org" ())
  123. (declare-function org-previous-line-empty-p "org" ())
  124. (declare-function org-reduced-level "org" (L))
  125. (declare-function org-set-tags "org" (tags))
  126. (declare-function org-fold-show-subtree "org-fold" ())
  127. (declare-function org-fold-region "org-fold" (from to flag &optional spec))
  128. (declare-function org-sort-remove-invisible "org" (S))
  129. (declare-function org-time-string-to-seconds "org" (s))
  130. (declare-function org-timer-hms-to-secs "org-timer" (hms))
  131. (declare-function org-timer-item "org-timer" (&optional arg))
  132. (declare-function outline-next-heading "outline" ())
  133. (declare-function outline-previous-heading "outline" ())
  134. ;;; Configuration variables
  135. (defgroup org-plain-lists nil
  136. "Options concerning plain lists in Org mode."
  137. :tag "Org Plain lists"
  138. :group 'org-structure)
  139. (defcustom org-cycle-include-plain-lists t
  140. "When t, make TAB cycle visibility on plain list items.
  141. Cycling plain lists works only when the cursor is on a plain list
  142. item. When the cursor is on an outline heading, plain lists are
  143. treated as text. This is the most stable way of handling this,
  144. which is why it is the default.
  145. When this is the symbol `integrate', then integrate plain list
  146. items when cycling, as if they were children of outline headings.
  147. This setting can lead to strange effects when switching visibility
  148. to `children', because the first \"child\" in a subtree decides
  149. what children should be listed. If that first \"child\" is a
  150. plain list item with an implied large level number, all true
  151. children and grand children of the outline heading will be
  152. exposed in a children' view."
  153. :group 'org-plain-lists
  154. :group 'org-cycle
  155. :type '(choice
  156. (const :tag "Never" nil)
  157. (const :tag "With cursor in plain list (recommended)" t)
  158. (const :tag "As children of outline headings" integrate)))
  159. (defcustom org-list-demote-modify-bullet nil
  160. "Default bullet type installed when demoting an item.
  161. This is an association list, for each bullet type, this alist will point
  162. to the bullet that should be used when this item is demoted.
  163. For example,
  164. (setq org-list-demote-modify-bullet
  165. \\='((\"+\" . \"-\") (\"-\" . \"+\") (\"*\" . \"+\")))
  166. will make
  167. + Movies
  168. + Silence of the Lambs
  169. + My Cousin Vinny
  170. + Books
  171. + The Hunt for Red October
  172. + The Road to Omaha
  173. into
  174. + Movies
  175. - Silence of the Lambs
  176. - My Cousin Vinny
  177. + Books
  178. - The Hunt for Red October
  179. - The Road to Omaha"
  180. :group 'org-plain-lists
  181. :type '(repeat
  182. (cons
  183. (choice :tag "If the current bullet is "
  184. (const "-")
  185. (const "+")
  186. (const "*")
  187. (const "1.")
  188. (const "1)"))
  189. (choice :tag "demotion will change it to"
  190. (const "-")
  191. (const "+")
  192. (const "*")
  193. (const "1.")
  194. (const "1)")))))
  195. (defcustom org-plain-list-ordered-item-terminator t
  196. "The character that makes a line with leading number an ordered list item.
  197. Valid values are ?. and ?\\). To get both terminators, use t.
  198. This variable needs to be set before org.el is loaded. If you
  199. need to make a change while Emacs is running, use the customize
  200. interface or run the following code after updating it:
  201. `\\[org-element-update-syntax]'"
  202. :group 'org-plain-lists
  203. :type '(choice (const :tag "dot like in \"2.\"" ?.)
  204. (const :tag "paren like in \"2)\"" ?\))
  205. (const :tag "both" t))
  206. :set (lambda (var val) (set-default-toplevel-value var val)
  207. (when (featurep 'org-element) (org-element-update-syntax))))
  208. (defcustom org-list-allow-alphabetical nil
  209. "Non-nil means single character alphabetical bullets are allowed.
  210. Both uppercase and lowercase are handled. Lists with more than
  211. 26 items will fallback to standard numbering. Alphabetical
  212. counters like \"[@c]\" will be recognized.
  213. This variable needs to be set before org.el is loaded. If you
  214. need to make a change while Emacs is running, use the customize
  215. interface or run the following code after updating it:
  216. `\\[org-element-update-syntax]'"
  217. :group 'org-plain-lists
  218. :version "24.1"
  219. :type 'boolean
  220. :set (lambda (var val) (set-default-toplevel-value var val)
  221. (when (featurep 'org-element) (org-element-update-syntax))))
  222. (defcustom org-list-two-spaces-after-bullet-regexp nil
  223. "A regular expression matching bullets that should have 2 spaces after them.
  224. When nil, no bullet will have two spaces after them. When
  225. a string, it will be used as a regular expression. When the
  226. bullet type of a list is changed, the new bullet type will be
  227. matched against this regexp. If it matches, there will be two
  228. spaces instead of one after the bullet in each item of the list."
  229. :group 'org-plain-lists
  230. :type '(choice
  231. (const :tag "never" nil)
  232. (regexp)))
  233. (defcustom org-list-automatic-rules '((checkbox . t)
  234. (indent . t))
  235. "Non-nil means apply set of rules when acting on lists.
  236. \\<org-mode-map>
  237. By default, automatic actions are taken when using
  238. `\\[org-meta-return]',
  239. `\\[org-metaright]',
  240. `\\[org-metaleft]',
  241. `\\[org-shiftmetaright]',
  242. `\\[org-shiftmetaleft]',
  243. `\\[org-ctrl-c-minus]',
  244. `\\[org-toggle-checkbox]',
  245. `\\[org-insert-todo-heading]'.
  246. You can disable individually these rules by setting them to nil.
  247. Valid rules are:
  248. checkbox when non-nil, checkbox statistics is updated each time
  249. you either insert a new checkbox or toggle a checkbox.
  250. indent when non-nil, indenting or outdenting list top-item
  251. with its subtree will move the whole list and
  252. outdenting a list whose bullet is * to column 0 will
  253. change that bullet to \"-\"."
  254. :group 'org-plain-lists
  255. :version "24.1"
  256. :type '(alist :tag "Sets of rules"
  257. :key-type
  258. (choice
  259. (const :tag "Checkbox" checkbox)
  260. (const :tag "Indent" indent))
  261. :value-type
  262. (boolean :tag "Activate" :value t)))
  263. (defcustom org-list-use-circular-motion nil
  264. "Non-nil means commands implying motion in lists should be cyclic.
  265. \\<org-mode-map>
  266. In that case, the item following the last item is the first one,
  267. and the item preceding the first item is the last one.
  268. This affects the behavior of
  269. `\\[org-move-item-up]',
  270. `\\[org-move-item-down]',
  271. `\\[org-next-item]',
  272. `\\[org-previous-item]'."
  273. :group 'org-plain-lists
  274. :version "24.1"
  275. :type 'boolean)
  276. (defvar org-checkbox-statistics-hook nil
  277. "Hook that is run whenever Org thinks checkbox statistics should be updated.
  278. This hook runs even if checkbox rule in
  279. `org-list-automatic-rules' does not apply, so it can be used to
  280. implement alternative ways of collecting statistics
  281. information.")
  282. (defcustom org-checkbox-hierarchical-statistics t
  283. "Non-nil means checkbox statistics counts only the state of direct children.
  284. When nil, all boxes below the cookie are counted.
  285. This can be set to nil on a per-node basis using a COOKIE_DATA property
  286. with the word \"recursive\" in the value."
  287. :group 'org-plain-lists
  288. :type 'boolean)
  289. (defcustom org-list-indent-offset 0
  290. "Additional indentation for sub-items in a list.
  291. By setting this to a small number, usually 1 or 2, one can more
  292. clearly distinguish sub-items in a list."
  293. :group 'org-plain-lists
  294. :version "24.1"
  295. :type 'integer)
  296. (defvar org-list-forbidden-blocks '("example" "verse" "src" "export")
  297. "Names of blocks where lists are not allowed.
  298. Names must be in lower case.")
  299. ;;; Predicates and regexps
  300. (defconst org-list-end-re "^[ \t]*\n[ \t]*\n"
  301. "Regex matching the end of a plain list.")
  302. (defconst org-list-full-item-re
  303. (concat "^[ \t]*\\(\\(?:[-+*]\\|\\(?:[0-9]+\\|[A-Za-z]\\)[.)]\\)\\(?:[ \t]+\\|$\\)\\)"
  304. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  305. "\\(?:\\(\\[[ X-]\\]\\)\\(?:[ \t]+\\|$\\)\\)?"
  306. "\\(?:\\(.*\\)[ \t]+::\\(?:[ \t]+\\|$\\)\\)?")
  307. "Matches a list item and puts everything into groups:
  308. group 1: bullet
  309. group 2: counter
  310. group 3: checkbox
  311. group 4: description tag")
  312. (defun org-item-re ()
  313. "Return the correct regular expression for plain lists."
  314. (let ((term (cond
  315. ((eq org-plain-list-ordered-item-terminator t) "[.)]")
  316. ((= org-plain-list-ordered-item-terminator ?\)) ")")
  317. ((= org-plain-list-ordered-item-terminator ?.) "\\.")
  318. (t "[.)]")))
  319. (alpha (if org-list-allow-alphabetical "\\|[A-Za-z]" "")))
  320. (concat "\\([ \t]*\\([-+]\\|\\(\\([0-9]+" alpha "\\)" term
  321. "\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)")))
  322. (defsubst org-item-beginning-re ()
  323. "Regexp matching the beginning of a plain list item."
  324. (concat "^" (org-item-re)))
  325. (defun org-list-at-regexp-after-bullet-p (regexp)
  326. "Is point at a list item with REGEXP after bullet?"
  327. (and (org-at-item-p)
  328. (save-excursion
  329. (goto-char (match-end 0))
  330. (let ((counter-re (concat "\\(?:\\[@\\(?:start:\\)?"
  331. (if org-list-allow-alphabetical
  332. "\\([0-9]+\\|[A-Za-z]\\)"
  333. "[0-9]+")
  334. "\\][ \t]*\\)")))
  335. ;; Ignore counter if any
  336. (when (looking-at counter-re) (goto-char (match-end 0))))
  337. (looking-at regexp))))
  338. (defun org-list-in-valid-context-p ()
  339. "Is point in a context where lists are allowed?"
  340. (not (org-in-block-p org-list-forbidden-blocks)))
  341. (defun org-in-item-p ()
  342. "Return item beginning position when in a plain list, nil otherwise."
  343. (save-excursion
  344. (beginning-of-line)
  345. (let* ((case-fold-search t)
  346. (context (org-list-context))
  347. (lim-up (car context))
  348. (inlinetask-re (and (featurep 'org-inlinetask)
  349. (org-inlinetask-outline-regexp)))
  350. (item-re (org-item-re))
  351. ;; Indentation isn't meaningful when point starts at an empty
  352. ;; line or an inline task.
  353. (ind-ref (if (or (looking-at "^[ \t]*$")
  354. (and inlinetask-re (looking-at inlinetask-re)))
  355. 10000
  356. (org-current-text-indentation))))
  357. (cond
  358. ((eq (nth 2 context) 'invalid) nil)
  359. ((looking-at item-re) (point))
  360. (t
  361. ;; Detect if cursor in amidst `org-list-end-re'. First, count
  362. ;; number HL of hard lines it takes, then call `org-in-regexp'
  363. ;; to compute its boundaries END-BOUNDS. When point is
  364. ;; in-between, move cursor before regexp beginning.
  365. (let ((hl 0) (i -1) end-bounds)
  366. (when (and (progn
  367. (while (setq i (string-match
  368. "[\r\n]" org-list-end-re (1+ i)))
  369. (setq hl (1+ hl)))
  370. (setq end-bounds (org-in-regexp org-list-end-re hl)))
  371. (>= (point) (car end-bounds))
  372. (< (point) (cdr end-bounds)))
  373. (goto-char (car end-bounds))
  374. (forward-line -1)))
  375. ;; Look for an item, less indented that reference line.
  376. (catch 'exit
  377. (while t
  378. (let ((ind (org-current-text-indentation)))
  379. (cond
  380. ;; This is exactly what we want.
  381. ((and (looking-at item-re) (< ind ind-ref))
  382. (throw 'exit (point)))
  383. ;; At upper bound of search or looking at the end of a
  384. ;; previous list: search is over.
  385. ((<= (point) lim-up) (throw 'exit nil))
  386. ((looking-at org-list-end-re) (throw 'exit nil))
  387. ;; Skip blocks, drawers, inline-tasks, blank lines
  388. ((and (looking-at "^[ \t]*#\\+end_")
  389. (re-search-backward "^[ \t]*#\\+begin_" lim-up t)))
  390. ((and (looking-at "^[ \t]*:END:")
  391. (re-search-backward org-drawer-regexp lim-up t))
  392. (beginning-of-line))
  393. ((and inlinetask-re (looking-at inlinetask-re))
  394. (org-inlinetask-goto-beginning)
  395. (forward-line -1))
  396. ((looking-at "^[ \t]*$") (forward-line -1))
  397. ;; Text at column 0 cannot belong to a list: stop.
  398. ((zerop ind) (throw 'exit nil))
  399. ;; Normal text less indented than reference line, take
  400. ;; it as new reference.
  401. ((< ind ind-ref)
  402. (setq ind-ref ind)
  403. (forward-line -1))
  404. (t (forward-line -1)))))))))))
  405. (defun org-at-item-p ()
  406. "Is point in a line starting a hand-formatted item?"
  407. (save-excursion
  408. (beginning-of-line)
  409. (and (looking-at (org-item-re)) (org-list-in-valid-context-p))))
  410. (defun org-at-item-bullet-p ()
  411. "Is point at the bullet of a plain list item?"
  412. (and (org-at-item-p)
  413. (not (member (char-after) '(?\ ?\t)))
  414. (< (point) (match-end 0))))
  415. (defun org-at-item-timer-p ()
  416. "Is point at a line starting a plain list item with a timer?"
  417. (org-list-at-regexp-after-bullet-p
  418. "\\([0-9]+:[0-9]+:[0-9]+\\)[ \t]+::[ \t]+"))
  419. (defun org-at-item-description-p ()
  420. "Is point at a description list item?"
  421. (org-list-at-regexp-after-bullet-p "\\(\\S-.+\\)[ \t]+::\\([ \t]+\\|$\\)"))
  422. (defun org-at-item-checkbox-p ()
  423. "Is point at a line starting a plain-list item with a checklet?"
  424. (org-list-at-regexp-after-bullet-p "\\(\\[[- X]\\]\\)[ \t]+"))
  425. (defun org-at-item-counter-p ()
  426. "Is point at a line starting a plain-list item with a counter?"
  427. (and (org-at-item-p)
  428. (looking-at org-list-full-item-re)
  429. (match-string 2)))
  430. ;;; Structures and helper functions
  431. (defun org-list-context ()
  432. "Determine context, and its boundaries, around point.
  433. Context will be a cell like (MIN MAX CONTEXT) where MIN and MAX
  434. are boundaries and CONTEXT is a symbol among `drawer', `block',
  435. `invalid', `inlinetask' and nil.
  436. Contexts `block' and `invalid' refer to `org-list-forbidden-blocks'."
  437. (save-match-data
  438. (save-excursion
  439. (org-with-limited-levels
  440. (beginning-of-line)
  441. (let ((case-fold-search t) (pos (point)) beg end context-type
  442. ;; Get positions of surrounding headings. This is the
  443. ;; default context.
  444. (lim-up (or (save-excursion (and (ignore-errors (org-back-to-heading t))
  445. (point)))
  446. (point-min)))
  447. (lim-down (or (save-excursion (outline-next-heading)) (point-max))))
  448. ;; Is point inside a drawer?
  449. (let ((end-re "^[ \t]*:END:")
  450. (beg-re org-drawer-regexp))
  451. (when (save-excursion
  452. (and (not (looking-at beg-re))
  453. (not (looking-at end-re))
  454. (setq beg (and (re-search-backward beg-re lim-up t)
  455. (1+ (line-end-position))))
  456. (setq end (or (and (re-search-forward end-re lim-down t)
  457. (1- (match-beginning 0)))
  458. lim-down))
  459. (>= end pos)))
  460. (setq lim-up beg lim-down end context-type 'drawer)))
  461. ;; Is point strictly in a block, and of which type?
  462. (let ((block-re "^[ \t]*#\\+\\(begin\\|end\\)_") type)
  463. (when (save-excursion
  464. (and (not (looking-at block-re))
  465. (setq beg (and (re-search-backward block-re lim-up t)
  466. (1+ (line-end-position))))
  467. (looking-at "^[ \t]*#\\+begin_\\(\\S-+\\)")
  468. (setq type (downcase (match-string 1)))
  469. (goto-char beg)
  470. (setq end (or (and (re-search-forward block-re lim-down t)
  471. (1- (line-beginning-position)))
  472. lim-down))
  473. (>= end pos)
  474. (equal (downcase (match-string 1)) "end")))
  475. (setq lim-up beg lim-down end
  476. context-type (if (member type org-list-forbidden-blocks)
  477. 'invalid 'block))))
  478. ;; Is point in an inlinetask?
  479. (when (and (featurep 'org-inlinetask)
  480. (save-excursion
  481. (let* ((beg-re (org-inlinetask-outline-regexp))
  482. (end-re (concat beg-re "END[ \t]*$")))
  483. (and (not (looking-at "^\\*+"))
  484. (setq beg (and (re-search-backward beg-re lim-up t)
  485. (1+ (line-end-position))))
  486. (not (looking-at end-re))
  487. (setq end (and (re-search-forward end-re lim-down t)
  488. (1- (match-beginning 0))))
  489. (> (point) pos)))))
  490. (setq lim-up beg lim-down end context-type 'inlinetask))
  491. ;; Return context boundaries and type.
  492. (list lim-up lim-down context-type))))))
  493. (defun org-list-struct ()
  494. "Return structure of list at point.
  495. A list structure is an alist where key is point at item, and
  496. values are:
  497. 1. indentation,
  498. 2. bullet with trailing whitespace,
  499. 3. bullet counter, if any,
  500. 4. checkbox, if any,
  501. 5. description tag, if any,
  502. 6. position at item end.
  503. Thus the following list, where numbers in parens are
  504. line-beginning-position:
  505. - [X] first item (1)
  506. 1. sub-item 1 (18)
  507. 5. [@5] sub-item 2 (34)
  508. some other text belonging to first item (55)
  509. - last item (97)
  510. + tag :: description (109)
  511. (131)
  512. will get the following structure:
  513. ((1 0 \"- \" nil \"[X]\" nil 97)
  514. (18 2 \"1. \" nil nil nil 34)
  515. (34 2 \"5. \" \"5\" nil nil 55)
  516. (97 0 \"- \" nil nil nil 131)
  517. (109 2 \"+ \" nil nil \"tag\" 131))
  518. Assume point is at an item."
  519. (save-excursion
  520. (beginning-of-line)
  521. (let* ((case-fold-search t)
  522. (context (org-list-context))
  523. (lim-up (car context))
  524. (lim-down (nth 1 context))
  525. (text-min-ind 10000)
  526. (item-re (org-item-re))
  527. (inlinetask-re (and (featurep 'org-inlinetask)
  528. (org-inlinetask-outline-regexp)))
  529. (beg-cell (cons (point) (org-current-text-indentation)))
  530. itm-lst itm-lst-2 end-lst end-lst-2 struct
  531. (assoc-at-point
  532. ;; Return association at point.
  533. (lambda (ind)
  534. (looking-at org-list-full-item-re)
  535. (let ((bullet (match-string-no-properties 1)))
  536. (list (point)
  537. ind
  538. bullet
  539. (match-string-no-properties 2) ; counter
  540. (match-string-no-properties 3) ; checkbox
  541. ;; Description tag.
  542. (and (string-match-p "[-+*]" bullet)
  543. (match-string-no-properties 4))))))
  544. (end-before-blank
  545. ;; Ensure list ends at the first blank line.
  546. (lambda ()
  547. (skip-chars-backward " \r\t\n")
  548. (min (1+ (line-end-position)) lim-down))))
  549. ;; 1. Read list from starting item to its beginning, and save
  550. ;; top item position and indentation in BEG-CELL. Also store
  551. ;; ending position of items in END-LST.
  552. (save-excursion
  553. (catch 'exit
  554. (while t
  555. (let ((ind (org-current-text-indentation)))
  556. (cond
  557. ((<= (point) lim-up)
  558. ;; At upward limit: if we ended at an item, store it,
  559. ;; else dismiss useless data recorded above BEG-CELL.
  560. ;; Jump to part 2.
  561. (throw 'exit
  562. (setq itm-lst
  563. (if (not (looking-at item-re))
  564. (memq (assq (car beg-cell) itm-lst) itm-lst)
  565. (setq beg-cell (cons (point) ind))
  566. (cons (funcall assoc-at-point ind) itm-lst)))))
  567. ;; Looking at a list ending regexp. Dismiss useless
  568. ;; data recorded above BEG-CELL. Jump to part 2.
  569. ((looking-at org-list-end-re)
  570. (throw 'exit
  571. (setq itm-lst
  572. (memq (assq (car beg-cell) itm-lst) itm-lst))))
  573. ;; Point is at an item. Add data to ITM-LST. It may
  574. ;; also end a previous item: save it in END-LST. If
  575. ;; ind is less or equal than BEG-CELL and there is no
  576. ;; end at this ind or lesser, this item becomes the new
  577. ;; BEG-CELL.
  578. ((looking-at item-re)
  579. (push (funcall assoc-at-point ind) itm-lst)
  580. (push (cons ind (point)) end-lst)
  581. (when (< ind text-min-ind) (setq beg-cell (cons (point) ind)))
  582. (forward-line -1))
  583. ;; Skip blocks, drawers, inline tasks, blank lines.
  584. ((and (looking-at "^[ \t]*#\\+end_")
  585. (re-search-backward "^[ \t]*#\\+begin_" lim-up t)))
  586. ((and (looking-at "^[ \t]*:END:")
  587. (re-search-backward org-drawer-regexp lim-up t))
  588. (beginning-of-line))
  589. ((and inlinetask-re (looking-at inlinetask-re))
  590. (org-inlinetask-goto-beginning)
  591. (forward-line -1))
  592. ((looking-at "^[ \t]*$")
  593. (forward-line -1))
  594. ;; From there, point is not at an item. Interpret
  595. ;; line's indentation:
  596. ;; - text at column 0 is necessarily out of any list.
  597. ;; Dismiss data recorded above BEG-CELL. Jump to
  598. ;; part 2.
  599. ;; - any other case may be an ending position for an
  600. ;; hypothetical item above. Store it and proceed.
  601. ((zerop ind)
  602. (throw 'exit
  603. (setq itm-lst
  604. (memq (assq (car beg-cell) itm-lst) itm-lst))))
  605. (t
  606. (when (< ind text-min-ind) (setq text-min-ind ind))
  607. (push (cons ind (point)) end-lst)
  608. (forward-line -1)))))))
  609. ;; 2. Read list from starting point to its end, that is until we
  610. ;; get out of context, or that a non-item line is less or
  611. ;; equally indented than BEG-CELL's cdr. Also, store ending
  612. ;; position of items in END-LST-2.
  613. (catch 'exit
  614. (while t
  615. (let ((ind (org-current-text-indentation)))
  616. (cond
  617. ((>= (point) lim-down)
  618. ;; At downward limit: this is de facto the end of the
  619. ;; list. Save point as an ending position, and jump to
  620. ;; part 3.
  621. (throw 'exit
  622. (push (cons 0 (funcall end-before-blank)) end-lst-2)))
  623. ;; Looking at a list ending regexp. Save point as an
  624. ;; ending position and jump to part 3.
  625. ((looking-at org-list-end-re)
  626. (throw 'exit (push (cons 0 (point)) end-lst-2)))
  627. ((looking-at item-re)
  628. ;; Point is at an item. Add data to ITM-LST-2. It may
  629. ;; also end a previous item, so save it in END-LST-2.
  630. (push (funcall assoc-at-point ind) itm-lst-2)
  631. (push (cons ind (point)) end-lst-2)
  632. (forward-line 1))
  633. ;; Skip inline tasks and blank lines along the way
  634. ((and inlinetask-re (looking-at inlinetask-re))
  635. (org-inlinetask-goto-end))
  636. ((looking-at "^[ \t]*$")
  637. (forward-line 1))
  638. ;; Ind is lesser or equal than BEG-CELL's. The list is
  639. ;; over: store point as an ending position and jump to
  640. ;; part 3.
  641. ((<= ind (cdr beg-cell))
  642. (throw 'exit
  643. (push (cons 0 (funcall end-before-blank)) end-lst-2)))
  644. ;; Else, if ind is lesser or equal than previous item's,
  645. ;; this is an ending position: store it. In any case,
  646. ;; skip block or drawer at point, and move to next line.
  647. (t
  648. (when (<= ind (nth 1 (car itm-lst-2)))
  649. (push (cons ind (point)) end-lst-2))
  650. (cond
  651. ((and (looking-at "^[ \t]*#\\+begin_")
  652. (re-search-forward "^[ \t]*#\\+end_" lim-down t)))
  653. ((and (looking-at org-drawer-regexp)
  654. (re-search-forward "^[ \t]*:END:" lim-down t))))
  655. (forward-line 1))))))
  656. (setq struct (append itm-lst (cdr (nreverse itm-lst-2)))
  657. end-lst (append end-lst (cdr (nreverse end-lst-2))))
  658. ;; 3. Associate each item to its end position.
  659. (org-list-struct-assoc-end struct end-lst)
  660. ;; 4. Return STRUCT
  661. struct)))
  662. (defun org-list-struct-assoc-end (struct end-list)
  663. "Associate proper ending point to items in STRUCT.
  664. END-LIST is a pseudo-alist where car is indentation and cdr is
  665. ending position.
  666. This function modifies STRUCT."
  667. (let ((endings end-list))
  668. (mapc
  669. (lambda (elt)
  670. (let ((pos (car elt))
  671. (ind (nth 1 elt)))
  672. ;; Remove end candidates behind current item.
  673. (while (or (<= (cdar endings) pos))
  674. (pop endings))
  675. ;; Add end position to item assoc.
  676. (let ((old-end (nthcdr 6 elt))
  677. (new-end (assoc-default ind endings '<=)))
  678. (if old-end
  679. (setcar old-end new-end)
  680. (setcdr elt (append (cdr elt) (list new-end)))))))
  681. struct)))
  682. (defun org-list-prevs-alist (struct)
  683. "Return alist between item and previous item in STRUCT."
  684. (let ((item-end-alist (mapcar (lambda (e) (cons (car e) (nth 6 e)))
  685. struct)))
  686. (mapcar (lambda (e)
  687. (let ((prev (car (rassq (car e) item-end-alist))))
  688. (cons (car e) prev)))
  689. struct)))
  690. (defun org-list-parents-alist (struct)
  691. "Return alist between item and parent in STRUCT."
  692. (let* ((ind-to-ori (list (list (nth 1 (car struct)))))
  693. (top-item (org-list-get-top-point struct))
  694. (prev-pos (list top-item)))
  695. (cons prev-pos
  696. (mapcar (lambda (item)
  697. (let ((pos (car item))
  698. (ind (nth 1 item))
  699. (prev-ind (caar ind-to-ori)))
  700. (push pos prev-pos)
  701. (cond
  702. ((> prev-ind ind)
  703. ;; A sub-list is over. Find the associated
  704. ;; origin in IND-TO-ORI. If it cannot be
  705. ;; found (ill-formed list), set its parent as
  706. ;; the first item less indented. If there is
  707. ;; none, make it a top-level item.
  708. (setq ind-to-ori
  709. (or (member (assq ind ind-to-ori) ind-to-ori)
  710. (catch 'exit
  711. (mapc
  712. (lambda (e)
  713. (when (< (car e) ind)
  714. (throw 'exit (member e ind-to-ori))))
  715. ind-to-ori)
  716. (list (list ind)))))
  717. (cons pos (cdar ind-to-ori)))
  718. ;; A sub-list starts. Every item at IND will
  719. ;; have previous item as its parent.
  720. ((< prev-ind ind)
  721. (let ((origin (nth 1 prev-pos)))
  722. (push (cons ind origin) ind-to-ori)
  723. (cons pos origin)))
  724. ;; Another item in the same sub-list: it shares
  725. ;; the same parent as the previous item.
  726. (t (cons pos (cdar ind-to-ori))))))
  727. (cdr struct)))))
  728. (defun org-list--delete-metadata ()
  729. "Delete metadata from the heading at point.
  730. Metadata are tags, planning information and properties drawers."
  731. (save-match-data
  732. (org-with-wide-buffer
  733. (org-set-tags nil)
  734. (delete-region (line-beginning-position 2)
  735. (save-excursion
  736. (org-end-of-meta-data)
  737. (org-skip-whitespace)
  738. (if (eobp) (point) (line-beginning-position)))))))
  739. ;;; Accessors
  740. (defsubst org-list-get-nth (n key struct)
  741. "Return the Nth value of KEY in STRUCT."
  742. (nth n (assq key struct)))
  743. (defun org-list-set-nth (n key struct new)
  744. "Set the Nth value of KEY in STRUCT to NEW.
  745. \nThis function modifies STRUCT."
  746. (setcar (nthcdr n (assq key struct)) new))
  747. (defsubst org-list-get-ind (item struct)
  748. "Return indentation of ITEM in STRUCT."
  749. (org-list-get-nth 1 item struct))
  750. (defun org-list-set-ind (item struct ind)
  751. "Set indentation of ITEM in STRUCT to IND.
  752. \nThis function modifies STRUCT."
  753. (org-list-set-nth 1 item struct ind))
  754. (defsubst org-list-get-bullet (item struct)
  755. "Return bullet of ITEM in STRUCT."
  756. (org-list-get-nth 2 item struct))
  757. (defun org-list-set-bullet (item struct bullet)
  758. "Set bullet of ITEM in STRUCT to BULLET.
  759. \nThis function modifies STRUCT."
  760. (org-list-set-nth 2 item struct bullet))
  761. (defsubst org-list-get-counter (item struct)
  762. "Return counter of ITEM in STRUCT."
  763. (org-list-get-nth 3 item struct))
  764. (defsubst org-list-get-checkbox (item struct)
  765. "Return checkbox of ITEM in STRUCT or nil."
  766. (org-list-get-nth 4 item struct))
  767. (defun org-list-set-checkbox (item struct checkbox)
  768. "Set checkbox of ITEM in STRUCT to CHECKBOX.
  769. \nThis function modifies STRUCT."
  770. (org-list-set-nth 4 item struct checkbox))
  771. (defsubst org-list-get-tag (item struct)
  772. "Return end position of ITEM in STRUCT."
  773. (org-list-get-nth 5 item struct))
  774. (defun org-list-get-item-end (item struct)
  775. "Return end position of ITEM in STRUCT."
  776. (org-list-get-nth 6 item struct))
  777. (defun org-list-get-item-end-before-blank (item struct)
  778. "Return point at end of ITEM in STRUCT, before any blank line.
  779. Point returned is at end of line."
  780. (save-excursion
  781. (goto-char (org-list-get-item-end item struct))
  782. (skip-chars-backward " \r\t\n")
  783. (line-end-position)))
  784. (defun org-list-get-parent (item struct parents)
  785. "Return parent of ITEM or nil.
  786. STRUCT is the list structure. PARENTS is the alist of parents,
  787. as returned by `org-list-parents-alist'."
  788. (let ((parents (or parents (org-list-parents-alist struct))))
  789. (cdr (assq item parents))))
  790. (defun org-list-has-child-p (item struct)
  791. "Non-nil if ITEM has a child.
  792. STRUCT is the list structure.
  793. Value returned is the position of the first child of ITEM."
  794. (let ((ind (org-list-get-ind item struct))
  795. (child-maybe (car (nth 1 (member (assq item struct) struct)))))
  796. (when (and child-maybe
  797. (< ind (org-list-get-ind child-maybe struct)))
  798. child-maybe)))
  799. (defun org-list-get-next-item (item _struct prevs)
  800. "Return next item in same sub-list as ITEM, or nil.
  801. STRUCT is the list structure. PREVS is the alist of previous
  802. items, as returned by `org-list-prevs-alist'."
  803. (car (rassq item prevs)))
  804. (defun org-list-get-prev-item (item _struct prevs)
  805. "Return previous item in same sub-list as ITEM, or nil.
  806. STRUCT is the list structure. PREVS is the alist of previous
  807. items, as returned by `org-list-prevs-alist'."
  808. (cdr (assq item prevs)))
  809. (defun org-list-get-subtree (item struct)
  810. "List all items having ITEM as a common ancestor, or nil.
  811. STRUCT is the list structure."
  812. (let* ((item-end (org-list-get-item-end item struct))
  813. (sub-struct (cdr (member (assq item struct) struct)))
  814. items)
  815. (catch :exit
  816. (pcase-dolist (`(,pos . ,_) sub-struct)
  817. (if (< pos item-end)
  818. (push pos items)
  819. (throw :exit nil))))
  820. (nreverse items)))
  821. (defun org-list-get-all-items (item struct prevs)
  822. "List all items in the same sub-list as ITEM.
  823. STRUCT is the list structure. PREVS is the alist of previous
  824. items, as returned by `org-list-prevs-alist'."
  825. (let ((prev-item item)
  826. (next-item item)
  827. before-item after-item)
  828. (while (setq prev-item (org-list-get-prev-item prev-item struct prevs))
  829. (push prev-item before-item))
  830. (while (setq next-item (org-list-get-next-item next-item struct prevs))
  831. (push next-item after-item))
  832. (append before-item (list item) (nreverse after-item))))
  833. (defun org-list-get-children (item _struct parents)
  834. "List all children of ITEM, or nil.
  835. STRUCT is the list structure. PARENTS is the alist of parents,
  836. as returned by `org-list-parents-alist'."
  837. (let (all child)
  838. (while (setq child (car (rassq item parents)))
  839. (setq parents (cdr (member (assq child parents) parents)))
  840. (push child all))
  841. (nreverse all)))
  842. (defun org-list-get-top-point (struct)
  843. "Return point at beginning of list.
  844. STRUCT is the list structure."
  845. (caar struct))
  846. (defun org-list-get-bottom-point (struct)
  847. "Return point at bottom of list.
  848. STRUCT is the list structure."
  849. (apply #'max
  850. (mapcar (lambda (e) (org-list-get-item-end (car e) struct)) struct)))
  851. (defun org-list-get-list-begin (item struct prevs)
  852. "Return point at beginning of sub-list ITEM belongs.
  853. STRUCT is the list structure. PREVS is the alist of previous
  854. items, as returned by `org-list-prevs-alist'."
  855. (let ((first-item item) prev-item)
  856. (while (setq prev-item (org-list-get-prev-item first-item struct prevs))
  857. (setq first-item prev-item))
  858. first-item))
  859. (defalias 'org-list-get-first-item 'org-list-get-list-begin)
  860. (defun org-list-get-last-item (item struct prevs)
  861. "Return point at last item of sub-list ITEM belongs.
  862. STRUCT is the list structure. PREVS is the alist of previous
  863. items, as returned by `org-list-prevs-alist'."
  864. (let ((last-item item) next-item)
  865. (while (setq next-item (org-list-get-next-item last-item struct prevs))
  866. (setq last-item next-item))
  867. last-item))
  868. (defun org-list-get-list-end (item struct prevs)
  869. "Return point at end of sub-list ITEM belongs.
  870. STRUCT is the list structure. PREVS is the alist of previous
  871. items, as returned by `org-list-prevs-alist'."
  872. (org-list-get-item-end (org-list-get-last-item item struct prevs) struct))
  873. (defun org-list-get-list-type (item struct prevs)
  874. "Return the type of the list containing ITEM, as a symbol.
  875. STRUCT is the list structure. PREVS is the alist of previous
  876. items, as returned by `org-list-prevs-alist'.
  877. Possible types are `descriptive', `ordered' and `unordered'. The
  878. type is determined by the first item of the list."
  879. (let ((first (org-list-get-list-begin item struct prevs)))
  880. (cond
  881. ((string-match-p "[[:alnum:]]" (org-list-get-bullet first struct)) 'ordered)
  882. ((org-list-get-tag first struct) 'descriptive)
  883. (t 'unordered))))
  884. (defun org-list-get-item-number (item struct prevs parents)
  885. "Return ITEM's sequence number.
  886. STRUCT is the list structure. PREVS is the alist of previous
  887. items, as returned by `org-list-prevs-alist'. PARENTS is the
  888. alist of ancestors, as returned by `org-list-parents-alist'.
  889. Return value is a list of integers. Counters have an impact on
  890. that value."
  891. (let ((get-relative-number
  892. (lambda (item struct prevs)
  893. ;; Return relative sequence number of ITEM in the sub-list
  894. ;; it belongs. STRUCT is the list structure. PREVS is
  895. ;; the alist of previous items.
  896. (let ((seq 0) (pos item) counter)
  897. (while (and (not (setq counter (org-list-get-counter pos struct)))
  898. (setq pos (org-list-get-prev-item pos struct prevs)))
  899. (cl-incf seq))
  900. (if (not counter) (1+ seq)
  901. (cond
  902. ((string-match "[A-Za-z]" counter)
  903. (+ (- (string-to-char (upcase (match-string 0 counter))) 64)
  904. seq))
  905. ((string-match "[0-9]+" counter)
  906. (+ (string-to-number (match-string 0 counter)) seq))
  907. (t (1+ seq))))))))
  908. ;; Cons each parent relative number into return value (OUT).
  909. (let ((out (list (funcall get-relative-number item struct prevs)))
  910. (parent item))
  911. (while (setq parent (org-list-get-parent parent struct parents))
  912. (push (funcall get-relative-number parent struct prevs) out))
  913. ;; Return value.
  914. out)))
  915. ;;; Searching
  916. (defun org-list-search-generic (search re bound noerr)
  917. "Search a string in valid contexts for lists.
  918. Arguments SEARCH, RE, BOUND and NOERR are similar to those used
  919. in `re-search-forward'."
  920. (catch 'exit
  921. (let ((origin (point)))
  922. (while t
  923. ;; 1. No match: return to origin or bound, depending on NOERR.
  924. (unless (funcall search re bound noerr)
  925. (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound))
  926. nil)))
  927. ;; 2. Match in valid context: return point. Else, continue
  928. ;; searching.
  929. (when (org-list-in-valid-context-p) (throw 'exit (point)))))))
  930. (defun org-list-search-backward (regexp &optional bound noerror)
  931. "Like `re-search-backward' but stop only where lists are recognized.
  932. Arguments REGEXP, BOUND and NOERROR are similar to those used in
  933. `re-search-backward'."
  934. (org-list-search-generic #'re-search-backward
  935. regexp (or bound (point-min)) noerror))
  936. (defun org-list-search-forward (regexp &optional bound noerror)
  937. "Like `re-search-forward' but stop only where lists are recognized.
  938. Arguments REGEXP, BOUND and NOERROR are similar to those used in
  939. `re-search-forward'."
  940. (org-list-search-generic #'re-search-forward
  941. regexp (or bound (point-max)) noerror))
  942. ;;; Methods on structures
  943. (defsubst org-list-bullet-string (bullet)
  944. "Return BULLET with the correct number of whitespaces.
  945. It determines the number of whitespaces to append by looking at
  946. `org-list-two-spaces-after-bullet-regexp'."
  947. (save-match-data
  948. (let ((spaces (if (and org-list-two-spaces-after-bullet-regexp
  949. (string-match
  950. org-list-two-spaces-after-bullet-regexp bullet))
  951. " "
  952. " ")))
  953. (if (string-match "\\S-+\\([ \t]*\\)" bullet)
  954. (replace-match spaces nil nil bullet 1)
  955. bullet))))
  956. (defun org-list-swap-items (beg-A beg-B struct)
  957. "Swap item starting at BEG-A with item starting at BEG-B in STRUCT.
  958. Blank lines at the end of items are left in place. Item
  959. visibility is preserved. Return the new structure after the
  960. changes.
  961. Assume BEG-A is lesser than BEG-B and that BEG-A and BEG-B belong
  962. to the same sub-list.
  963. This function modifies STRUCT."
  964. (save-excursion
  965. (org-fold-core-ignore-modifications
  966. (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct))
  967. (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct))
  968. (end-A (org-list-get-item-end beg-A struct))
  969. (end-B (org-list-get-item-end beg-B struct))
  970. (size-A (- end-A-no-blank beg-A))
  971. (size-B (- end-B-no-blank beg-B))
  972. (body-A (buffer-substring beg-A end-A-no-blank))
  973. (body-B (buffer-substring beg-B end-B-no-blank))
  974. (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B))
  975. (sub-A (cons beg-A (org-list-get-subtree beg-A struct)))
  976. (sub-B (cons beg-B (org-list-get-subtree beg-B struct)))
  977. ;; Store inner folds responsible for visibility status.
  978. (folds
  979. (cons
  980. (org-fold-core-get-regions :from beg-A :to end-A :relative t)
  981. (org-fold-core-get-regions :from beg-B :to end-B :relative t))))
  982. ;; Clear up the folds.
  983. (org-fold-region beg-A end-B-no-blank nil)
  984. ;; 1. Move effectively items in buffer.
  985. (goto-char beg-A)
  986. (delete-region beg-A end-B-no-blank)
  987. (insert (concat body-B between-A-no-blank-and-B body-A))
  988. ;; Restore visibility status.
  989. (org-fold-core-regions (cdr folds) :relative beg-A)
  990. (org-fold-core-regions
  991. (car folds)
  992. :relative (+ beg-B (- size-B size-A (length between-A-no-blank-and-B))))
  993. ;; 2. Now modify struct. No need to re-read the list, the
  994. ;; transformation is just a shift of positions. Some special
  995. ;; attention is required for items ending at END-A and END-B
  996. ;; as empty spaces are not moved there. In others words,
  997. ;; item BEG-A will end with whitespaces that were at the end
  998. ;; of BEG-B and the same applies to BEG-B.
  999. (dolist (e struct)
  1000. (let ((pos (car e)))
  1001. (cond
  1002. ((< pos beg-A))
  1003. ((memq pos sub-A)
  1004. (let ((end-e (nth 6 e)))
  1005. (setcar e (+ pos (- end-B-no-blank end-A-no-blank)))
  1006. (setcar (nthcdr 6 e)
  1007. (+ end-e (- end-B-no-blank end-A-no-blank)))
  1008. (when (= end-e end-A) (setcar (nthcdr 6 e) end-B))))
  1009. ((memq pos sub-B)
  1010. (let ((end-e (nth 6 e)))
  1011. (setcar e (- (+ pos beg-A) beg-B))
  1012. (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B)))
  1013. (when (= end-e end-B)
  1014. (setcar (nthcdr 6 e)
  1015. (+ beg-A size-B (- end-A end-A-no-blank))))))
  1016. ((< pos beg-B)
  1017. (let ((end-e (nth 6 e)))
  1018. (setcar e (+ pos (- size-B size-A)))
  1019. (setcar (nthcdr 6 e) (+ end-e (- size-B size-A))))))))
  1020. (setq struct (sort struct #'car-less-than-car))
  1021. ;; Return structure.
  1022. struct))))
  1023. (defun org-list-separating-blank-lines-number (pos struct prevs)
  1024. "Return number of blank lines that should separate items in list.
  1025. POS is the position of point where `org-list-insert-item' was called.
  1026. STRUCT is the list structure. PREVS is the alist of previous
  1027. items, as returned by `org-list-prevs-alist'.
  1028. Assume point is at item's beginning. If the item is alone, apply
  1029. some heuristics to guess the result."
  1030. (save-excursion
  1031. (let ((item (point))
  1032. (insert-blank-p
  1033. (cdr (assq 'plain-list-item org-blank-before-new-entry)))
  1034. usr-blank
  1035. (count-blanks
  1036. (lambda ()
  1037. ;; Count blank lines above beginning of line.
  1038. (save-excursion
  1039. (count-lines (goto-char (line-beginning-position))
  1040. (progn (skip-chars-backward " \r\t\n")
  1041. (forward-line)
  1042. (point)))))))
  1043. (cond
  1044. ;; Trivial cases where there should be none.
  1045. ((not insert-blank-p) 0)
  1046. ;; When `org-blank-before-new-entry' says so, it is 1.
  1047. ((eq insert-blank-p t) 1)
  1048. ;; `plain-list-item' is 'auto. Count blank lines separating
  1049. ;; neighbors' items in list.
  1050. (t (let ((next-p (org-list-get-next-item item struct prevs)))
  1051. (cond
  1052. ;; Is there a next item?
  1053. (next-p (goto-char next-p)
  1054. (funcall count-blanks))
  1055. ;; Is there a previous item?
  1056. ((org-list-get-prev-item item struct prevs)
  1057. (funcall count-blanks))
  1058. ;; User inserted blank lines, trust him.
  1059. ((and (> pos (org-list-get-item-end-before-blank item struct))
  1060. (> (save-excursion (goto-char pos)
  1061. (setq usr-blank (funcall count-blanks)))
  1062. 0))
  1063. usr-blank)
  1064. ;; Are there blank lines inside the list so far?
  1065. ((save-excursion
  1066. (goto-char (org-list-get-top-point struct))
  1067. ;; Do not use `org-list-search-forward' so blank lines
  1068. ;; in blocks can be counted in.
  1069. (re-search-forward
  1070. "^[ \t]*$" (org-list-get-item-end-before-blank item struct) t))
  1071. 1)
  1072. ;; Default choice: no blank line.
  1073. (t 0))))))))
  1074. (defun org-list-insert-item (pos struct prevs &optional checkbox after-bullet)
  1075. "Insert a new list item at POS and return the new structure.
  1076. If POS is before first character after bullet of the item, the
  1077. new item will be created before the current one.
  1078. STRUCT is the list structure. PREVS is the alist of previous
  1079. items, as returned by `org-list-prevs-alist'.
  1080. Insert a checkbox if CHECKBOX is non-nil, and string AFTER-BULLET
  1081. after the bullet. Cursor will be after this text once the
  1082. function ends.
  1083. This function modifies STRUCT."
  1084. (let* ((case-fold-search t)
  1085. ;; Get information about list: ITEM containing POS, position
  1086. ;; of point with regards to item start (BEFOREP), blank lines
  1087. ;; number separating items (BLANK-NB), if we're allowed to
  1088. ;; (SPLIT-LINE-P).
  1089. (item
  1090. (catch :exit
  1091. (let ((i nil))
  1092. (pcase-dolist (`(,start ,_ ,_ ,_ ,_ ,_ ,end) struct)
  1093. (cond
  1094. ((> start pos) (throw :exit i))
  1095. ((< end pos) nil) ;skip sub-lists before point
  1096. (t (setq i start))))
  1097. ;; If no suitable item is found, insert a sibling of the
  1098. ;; last item in buffer.
  1099. (or i (caar (reverse struct))))))
  1100. (item-end (org-list-get-item-end item struct))
  1101. (item-end-no-blank (org-list-get-item-end-before-blank item struct))
  1102. (beforep
  1103. (progn
  1104. (goto-char item)
  1105. (looking-at org-list-full-item-re)
  1106. (<= pos
  1107. (cond
  1108. ((not (match-beginning 4)) (match-end 0))
  1109. ;; Ignore tag in a non-descriptive list.
  1110. ((save-match-data (string-match "[.)]" (match-string 1)))
  1111. (match-beginning 4))
  1112. (t (save-excursion
  1113. (goto-char (match-end 4))
  1114. (skip-chars-forward " \t")
  1115. (point)))))))
  1116. (split-line-p (org-get-alist-option org-M-RET-may-split-line 'item))
  1117. (blank-nb (org-list-separating-blank-lines-number pos struct prevs))
  1118. ;; Build the new item to be created. Concatenate same bullet
  1119. ;; as item, checkbox, text AFTER-BULLET if provided, and text
  1120. ;; cut from point to end of item (TEXT-CUT) to form item's
  1121. ;; BODY. TEXT-CUT depends on BEFOREP and SPLIT-LINE-P. The
  1122. ;; difference of size between what was cut and what was
  1123. ;; inserted in buffer is stored in SIZE-OFFSET.
  1124. (ind (org-list-get-ind item struct))
  1125. (ind-size (if indent-tabs-mode
  1126. (+ (/ ind tab-width) (mod ind tab-width))
  1127. ind))
  1128. (bullet (org-list-bullet-string (org-list-get-bullet item struct)))
  1129. (box (and checkbox "[ ]"))
  1130. (text-cut
  1131. (and (not beforep)
  1132. split-line-p
  1133. (progn
  1134. (goto-char pos)
  1135. ;; If POS is greater than ITEM-END, then point is in
  1136. ;; some white lines after the end of the list. Those
  1137. ;; must be removed, or they will be left, stacking up
  1138. ;; after the list.
  1139. (when (< item-end pos)
  1140. (delete-region (1- item-end) (line-end-position)))
  1141. (skip-chars-backward " \r\t\n")
  1142. ;; Cut position is after any blank on the line.
  1143. (save-excursion
  1144. (skip-chars-forward " \t")
  1145. (setq pos (point)))
  1146. (delete-and-extract-region (point) item-end-no-blank))))
  1147. (body
  1148. (concat bullet
  1149. (and box (concat box " "))
  1150. after-bullet
  1151. (and text-cut
  1152. (if (string-match "\\`[ \t]+" text-cut)
  1153. (replace-match "" t t text-cut)
  1154. text-cut))))
  1155. (item-sep (make-string (1+ blank-nb) ?\n))
  1156. (item-size (+ ind-size (length body) (length item-sep)))
  1157. (size-offset (- item-size (length text-cut))))
  1158. ;; Insert effectively item into buffer.
  1159. (goto-char item)
  1160. (indent-to-column ind)
  1161. (insert body item-sep)
  1162. ;; Add new item to STRUCT.
  1163. (dolist (e struct)
  1164. (let ((p (car e)) (end (nth 6 e)))
  1165. (cond
  1166. ;; Before inserted item, positions don't change but an item
  1167. ;; ending after insertion has its end shifted by SIZE-OFFSET.
  1168. ((< p item)
  1169. (when (> end item)
  1170. (setcar (nthcdr 6 e) (+ end size-offset))))
  1171. ;; Item where insertion happens may be split in two parts.
  1172. ;; In this case, move start by ITEM-SIZE and end by
  1173. ;; SIZE-OFFSET.
  1174. ((and (= p item) (not beforep) split-line-p)
  1175. (setcar e (+ p item-size))
  1176. (setcar (nthcdr 6 e) (+ end size-offset)))
  1177. ;; Items starting after modified item fall into two
  1178. ;; categories.
  1179. ;;
  1180. ;; If modified item was split, and current sub-item was
  1181. ;; located after split point, it was moved to the new item:
  1182. ;; the part between body start and split point (POS) was
  1183. ;; removed. So we compute the length of that part and shift
  1184. ;; item's positions accordingly.
  1185. ;;
  1186. ;; Otherwise, the item was simply shifted by SIZE-OFFSET.
  1187. ((and split-line-p (not beforep) (>= p pos) (<= p item-end-no-blank))
  1188. (let ((offset (- pos item ind (length bullet) (length after-bullet))))
  1189. (setcar e (- p offset))
  1190. (setcar (nthcdr 6 e) (- end offset))))
  1191. (t
  1192. (setcar e (+ p size-offset))
  1193. (setcar (nthcdr 6 e) (+ end size-offset))))))
  1194. (push (list item ind bullet nil box nil (+ item item-size)) struct)
  1195. (setq struct (sort struct #'car-less-than-car))
  1196. ;; If not BEFOREP, new item must appear after ITEM, so exchange
  1197. ;; ITEM with the next item in list. Position cursor after bullet,
  1198. ;; counter, checkbox, and label.
  1199. (if beforep
  1200. (goto-char item)
  1201. (setq struct (org-list-swap-items item (+ item item-size) struct))
  1202. (goto-char (org-list-get-next-item
  1203. item struct (org-list-prevs-alist struct))))
  1204. struct))
  1205. (defun org-list-delete-item (item struct)
  1206. "Remove ITEM from the list and return the new structure.
  1207. STRUCT is the list structure."
  1208. (let* ((end (org-list-get-item-end item struct))
  1209. (beg (if (= (org-list-get-bottom-point struct) end)
  1210. ;; If ITEM ends with the list, delete blank lines
  1211. ;; before it.
  1212. (save-excursion
  1213. (goto-char item)
  1214. (skip-chars-backward " \r\t\n")
  1215. (min (1+ (line-end-position)) (point-max)))
  1216. item)))
  1217. ;; Remove item from buffer.
  1218. (delete-region beg end)
  1219. ;; Remove item from structure and shift others items accordingly.
  1220. ;; Don't forget to shift also ending position when appropriate.
  1221. (let ((size (- end beg)))
  1222. (delq nil (mapcar (lambda (e)
  1223. (let ((pos (car e)))
  1224. (cond
  1225. ((< pos item)
  1226. (let ((end-e (nth 6 e)))
  1227. (cond
  1228. ((< end-e item) e)
  1229. ((= end-e item)
  1230. (append (butlast e) (list beg)))
  1231. (t
  1232. (append (butlast e) (list (- end-e size)))))))
  1233. ((< pos end) nil)
  1234. (t
  1235. (cons (- pos size)
  1236. (append (butlast (cdr e))
  1237. (list (- (nth 6 e) size))))))))
  1238. struct)))))
  1239. (defun org-list-send-item (item dest struct)
  1240. "Send ITEM to destination DEST.
  1241. STRUCT is the list structure.
  1242. DEST can have various values.
  1243. If DEST is a buffer position, the function will assume it points
  1244. to another item in the same list as ITEM, and will move the
  1245. latter just before the former.
  1246. If DEST is `begin' (respectively `end'), ITEM will be moved at
  1247. the beginning (respectively end) of the list it belongs to.
  1248. If DEST is a string like \"N\", where N is an integer, ITEM will
  1249. be moved at the Nth position in the list.
  1250. If DEST is `kill', ITEM will be deleted and its body will be
  1251. added to the kill-ring.
  1252. If DEST is `delete', ITEM will be deleted.
  1253. Visibility of item is preserved.
  1254. This function returns, destructively, the new list structure."
  1255. (let* ((prevs (org-list-prevs-alist struct))
  1256. (item-end (org-list-get-item-end item struct))
  1257. ;; Grab full item body minus its bullet.
  1258. (body (org-trim
  1259. (buffer-substring
  1260. (save-excursion
  1261. (goto-char item)
  1262. (looking-at
  1263. (concat "[ \t]*"
  1264. (regexp-quote (org-list-get-bullet item struct))))
  1265. (match-end 0))
  1266. item-end)))
  1267. ;; Change DEST into a buffer position. A trick is needed
  1268. ;; when ITEM is meant to be sent at the end of the list.
  1269. ;; Indeed, by setting locally `org-M-RET-may-split-line' to
  1270. ;; nil and insertion point (INS-POINT) to the first line's
  1271. ;; end of the last item, we ensure the new item will be
  1272. ;; inserted after the last item, and not after any of its
  1273. ;; hypothetical sub-items.
  1274. (ins-point (cond
  1275. ((or (eq dest 'kill) (eq dest 'delete)))
  1276. ((eq dest 'begin)
  1277. (setq dest (org-list-get-list-begin item struct prevs)))
  1278. ((eq dest 'end)
  1279. (setq dest (org-list-get-list-end item struct prevs))
  1280. (save-excursion
  1281. (goto-char (org-list-get-last-item item struct prevs))
  1282. (line-end-position)))
  1283. ((and (stringp dest) (string-match-p "\\`[0-9]+\\'" dest))
  1284. (let* ((all (org-list-get-all-items item struct prevs))
  1285. (len (length all))
  1286. (index (mod (string-to-number dest) len)))
  1287. (if (not (zerop index))
  1288. (setq dest (nth (1- index) all))
  1289. ;; Send ITEM at the end of the list.
  1290. (setq dest (org-list-get-list-end item struct prevs))
  1291. (save-excursion
  1292. (goto-char
  1293. (org-list-get-last-item item struct prevs))
  1294. (line-end-position)))))
  1295. (t dest)))
  1296. (org-M-RET-may-split-line nil)
  1297. ;; Store inner overlays (to preserve visibility).
  1298. (overlays (cl-remove-if (lambda (o) (or (< (overlay-start o) item)
  1299. (> (overlay-end o) item)))
  1300. (overlays-in item item-end))))
  1301. (cond
  1302. ((eq dest 'delete) (org-list-delete-item item struct))
  1303. ((eq dest 'kill)
  1304. (kill-new body)
  1305. (org-list-delete-item item struct))
  1306. ((and (integerp dest) (/= item ins-point))
  1307. (setq item (copy-marker item))
  1308. (setq struct (org-list-insert-item ins-point struct prevs nil body))
  1309. ;; 1. Structure returned by `org-list-insert-item' may not be
  1310. ;; accurate, as it cannot see sub-items included in BODY.
  1311. ;; Thus, first compute the real structure so far.
  1312. (let ((moved-items
  1313. (cons (marker-position item)
  1314. (org-list-get-subtree (marker-position item) struct)))
  1315. (new-end (org-list-get-item-end (point) struct))
  1316. (old-end (org-list-get-item-end (marker-position item) struct))
  1317. (new-item (point))
  1318. (shift (- (point) item)))
  1319. ;; 1.1. Remove the item just created in structure.
  1320. (setq struct (delete (assq new-item struct) struct))
  1321. ;; 1.2. Copy ITEM and any of its sub-items at NEW-ITEM.
  1322. (setq struct (sort
  1323. (append
  1324. struct
  1325. (mapcar (lambda (e)
  1326. (let* ((cell (assq e struct))
  1327. (pos (car cell))
  1328. (end (nth 6 cell)))
  1329. (cons (+ pos shift)
  1330. (append (butlast (cdr cell))
  1331. (list (if (= end old-end)
  1332. new-end
  1333. (+ end shift)))))))
  1334. moved-items))
  1335. #'car-less-than-car)))
  1336. ;; 2. Restore inner overlays.
  1337. (dolist (o overlays)
  1338. (move-overlay o
  1339. (+ (overlay-start o) (- (point) item))
  1340. (+ (overlay-end o) (- (point) item))))
  1341. ;; 3. Eventually delete extra copy of the item and clean marker.
  1342. (prog1 (org-list-delete-item (marker-position item) struct)
  1343. (move-marker item nil)))
  1344. (t struct))))
  1345. (defun org-list-struct-outdent (start end struct parents)
  1346. "Outdent items between positions START and END.
  1347. STRUCT is the list structure. PARENTS is the alist of items'
  1348. parents, as returned by `org-list-parents-alist'.
  1349. START is included, END excluded."
  1350. (let* (acc
  1351. (out (lambda (cell)
  1352. (let* ((item (car cell))
  1353. (parent (cdr cell)))
  1354. (cond
  1355. ;; Item not yet in zone: keep association.
  1356. ((< item start) cell)
  1357. ;; Item out of zone: follow associations in ACC.
  1358. ((>= item end)
  1359. (let ((convert (and parent (assq parent acc))))
  1360. (if convert (cons item (cdr convert)) cell)))
  1361. ;; Item has no parent: error
  1362. ((not parent)
  1363. (error "Cannot outdent top-level items"))
  1364. ;; Parent is outdented: keep association.
  1365. ((>= parent start)
  1366. (push (cons parent item) acc) cell)
  1367. (t
  1368. ;; Parent isn't outdented: reparent to grand-parent.
  1369. (let ((grand-parent (org-list-get-parent
  1370. parent struct parents)))
  1371. (push (cons parent item) acc)
  1372. (cons item grand-parent))))))))
  1373. (mapcar out parents)))
  1374. (defun org-list-struct-indent (start end struct parents prevs)
  1375. "Indent items between positions START and END.
  1376. STRUCT is the list structure. PARENTS is the alist of parents
  1377. and PREVS is the alist of previous items, returned by,
  1378. respectively, `org-list-parents-alist' and
  1379. `org-list-prevs-alist'.
  1380. START is included and END excluded.
  1381. STRUCT may be modified if `org-list-demote-modify-bullet' matches
  1382. bullets between START and END."
  1383. (let* (acc
  1384. (set-assoc (lambda (cell) (push cell acc) cell))
  1385. (ind
  1386. (lambda (cell)
  1387. (let* ((item (car cell))
  1388. (parent (cdr cell)))
  1389. (cond
  1390. ;; Item not yet in zone: keep association.
  1391. ((< item start) cell)
  1392. ((>= item end)
  1393. ;; Item out of zone: follow associations in ACC.
  1394. (let ((convert (assq parent acc)))
  1395. (if convert (cons item (cdr convert)) cell)))
  1396. (t
  1397. ;; Item is in zone...
  1398. (let ((prev (org-list-get-prev-item item struct prevs)))
  1399. ;; Check if bullet needs to be changed.
  1400. (pcase (assoc (let ((b (org-list-get-bullet item struct))
  1401. (case-fold-search nil))
  1402. (cond ((string-match "[A-Z]\\." b) "A.")
  1403. ((string-match "[A-Z])" b) "A)")
  1404. ((string-match "[a-z]\\." b) "a.")
  1405. ((string-match "[a-z])" b) "a)")
  1406. ((string-match "[0-9]\\." b) "1.")
  1407. ((string-match "[0-9])" b) "1)")
  1408. (t (org-trim b))))
  1409. org-list-demote-modify-bullet)
  1410. (`(,_ . ,bullet)
  1411. (org-list-set-bullet
  1412. item struct (org-list-bullet-string bullet)))
  1413. (_ nil))
  1414. (cond
  1415. ;; First item indented but not parent: error
  1416. ((and (not prev) (or (not parent) (< parent start)))
  1417. (user-error "Cannot indent the first item of a list"))
  1418. ;; First item and parent indented: keep same
  1419. ;; parent.
  1420. ((not prev) (funcall set-assoc cell))
  1421. ;; Previous item not indented: reparent to it.
  1422. ((< prev start) (funcall set-assoc (cons item prev)))
  1423. ;; Previous item indented: reparent like it.
  1424. (t
  1425. (funcall set-assoc
  1426. (cons item (cdr (assq prev acc)))))))))))))
  1427. (mapcar ind parents)))
  1428. ;;; Repairing structures
  1429. (defun org-list-use-alpha-bul-p (first struct prevs)
  1430. "Non-nil if list starting at FIRST can have alphabetical bullets.
  1431. STRUCT is list structure. PREVS is the alist of previous items,
  1432. as returned by `org-list-prevs-alist'."
  1433. (and org-list-allow-alphabetical
  1434. (catch 'exit
  1435. (let ((item first) (ascii 64) (case-fold-search nil))
  1436. ;; Pretend that bullets are uppercase and check if alphabet
  1437. ;; is sufficient, taking counters into account.
  1438. (while item
  1439. (let ((count (org-list-get-counter item struct)))
  1440. ;; Virtually determine current bullet
  1441. (if (and count (string-match-p "[a-zA-Z]" count))
  1442. ;; Counters are not case-sensitive.
  1443. (setq ascii (string-to-char (upcase count)))
  1444. (setq ascii (1+ ascii)))
  1445. ;; Test if bullet would be over z or Z.
  1446. (if (> ascii 90)
  1447. (throw 'exit nil)
  1448. (setq item (org-list-get-next-item item struct prevs)))))
  1449. ;; All items checked. All good.
  1450. t))))
  1451. (defun org-list-inc-bullet-maybe (bullet)
  1452. "Increment BULLET if applicable."
  1453. (let ((case-fold-search nil))
  1454. (cond
  1455. ;; Num bullet: increment it.
  1456. ((string-match "[0-9]+" bullet)
  1457. (replace-match
  1458. (number-to-string (1+ (string-to-number (match-string 0 bullet))))
  1459. nil nil bullet))
  1460. ;; Alpha bullet: increment it.
  1461. ((string-match "[A-Za-z]" bullet)
  1462. (replace-match
  1463. (char-to-string (1+ (string-to-char (match-string 0 bullet))))
  1464. nil nil bullet))
  1465. ;; Unordered bullet: leave it.
  1466. (t bullet))))
  1467. (defun org-list-struct-fix-bul (struct prevs)
  1468. "Verify and correct bullets in STRUCT.
  1469. PREVS is the alist of previous items, as returned by
  1470. `org-list-prevs-alist'.
  1471. This function modifies STRUCT."
  1472. (let ((case-fold-search nil)
  1473. (fix-bul
  1474. ;; Set bullet of ITEM in STRUCT, depending on the type of
  1475. ;; first item of the list, the previous bullet and counter
  1476. ;; if any.
  1477. (lambda (item)
  1478. (let* ((prev (org-list-get-prev-item item struct prevs))
  1479. (prev-bul (and prev (org-list-get-bullet prev struct)))
  1480. (counter (org-list-get-counter item struct))
  1481. (bullet (org-list-get-bullet item struct))
  1482. (alphap (and (not prev)
  1483. (org-list-use-alpha-bul-p item struct prevs))))
  1484. (org-list-set-bullet
  1485. item struct
  1486. (org-list-bullet-string
  1487. (cond
  1488. ;; Alpha counter in alpha list: use counter.
  1489. ((and prev counter
  1490. (string-match "[a-zA-Z]" counter)
  1491. (string-match "[a-zA-Z]" prev-bul))
  1492. ;; Use cond to be sure `string-match' is used in
  1493. ;; both cases.
  1494. (let ((real-count
  1495. (cond
  1496. ((string-match "[a-z]" prev-bul) (downcase counter))
  1497. ((string-match "[A-Z]" prev-bul) (upcase counter)))))
  1498. (replace-match real-count nil nil prev-bul)))
  1499. ;; Num counter in a num list: use counter.
  1500. ((and prev counter
  1501. (string-match "[0-9]+" counter)
  1502. (string-match "[0-9]+" prev-bul))
  1503. (replace-match counter nil nil prev-bul))
  1504. ;; No counter: increase, if needed, previous bullet.
  1505. (prev
  1506. (org-list-inc-bullet-maybe (org-list-get-bullet prev struct)))
  1507. ;; Alpha counter at first item: use counter.
  1508. ((and counter (org-list-use-alpha-bul-p item struct prevs)
  1509. (string-match "[A-Za-z]" counter)
  1510. (string-match "[A-Za-z]" bullet))
  1511. (let ((real-count
  1512. (cond
  1513. ((string-match "[a-z]" bullet) (downcase counter))
  1514. ((string-match "[A-Z]" bullet) (upcase counter)))))
  1515. (replace-match real-count nil nil bullet)))
  1516. ;; Num counter at first item: use counter.
  1517. ((and counter
  1518. (string-match "[0-9]+" counter)
  1519. (string-match "[0-9]+" bullet))
  1520. (replace-match counter nil nil bullet))
  1521. ;; First bullet is alpha uppercase: use "A".
  1522. ((and alphap (string-match "[A-Z]" bullet))
  1523. (replace-match "A" nil nil bullet))
  1524. ;; First bullet is alpha lowercase: use "a".
  1525. ((and alphap (string-match "[a-z]" bullet))
  1526. (replace-match "a" nil nil bullet))
  1527. ;; First bullet is num: use "1".
  1528. ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet)
  1529. (replace-match "1" nil nil bullet))
  1530. ;; Not an ordered list: keep bullet.
  1531. (t bullet))))))))
  1532. (mapc fix-bul (mapcar #'car struct))))
  1533. (defun org-list-struct-fix-ind (struct parents &optional bullet-size)
  1534. "Verify and correct indentation in STRUCT.
  1535. PARENTS is the alist of parents, as returned by
  1536. `org-list-parents-alist'.
  1537. If numeric optional argument BULLET-SIZE is set, assume all
  1538. bullets in list have this length to determine new indentation.
  1539. This function modifies STRUCT."
  1540. (let* ((ancestor (org-list-get-top-point struct))
  1541. (top-ind (org-list-get-ind ancestor struct))
  1542. (new-ind
  1543. (lambda (item)
  1544. (let ((parent (org-list-get-parent item struct parents)))
  1545. (if parent
  1546. ;; Indent like parent + length of parent's bullet +
  1547. ;; sub-list offset.
  1548. (org-list-set-ind
  1549. item struct (+ (or bullet-size
  1550. (length
  1551. (org-list-get-bullet parent struct)))
  1552. (org-list-get-ind parent struct)
  1553. org-list-indent-offset))
  1554. ;; If no parent, indent like top-point.
  1555. (org-list-set-ind item struct top-ind))))))
  1556. (mapc new-ind (mapcar #'car (cdr struct)))))
  1557. (defun org-list-struct-fix-box (struct parents prevs &optional ordered)
  1558. "Verify and correct checkboxes in STRUCT.
  1559. PARENTS is the alist of parents and PREVS is the alist of
  1560. previous items, as returned by, respectively,
  1561. `org-list-parents-alist' and `org-list-prevs-alist'.
  1562. If ORDERED is non-nil, a checkbox can only be checked when every
  1563. checkbox before it is checked too. If there was an attempt to
  1564. break this rule, the function will return the blocking item. In
  1565. all others cases, the return value will be nil.
  1566. This function modifies STRUCT."
  1567. (let ((all-items (mapcar #'car struct))
  1568. (set-parent-box
  1569. (lambda (item)
  1570. (let* ((box-list
  1571. (mapcar (lambda (child)
  1572. (org-list-get-checkbox child struct))
  1573. (org-list-get-children item struct parents))))
  1574. (org-list-set-checkbox
  1575. item struct
  1576. (cond
  1577. ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]")
  1578. ((member "[-]" box-list) "[-]")
  1579. ((member "[X]" box-list) "[X]")
  1580. ((member "[ ]" box-list) "[ ]")
  1581. ;; Parent has no boxed child: leave box as-is.
  1582. (t (org-list-get-checkbox item struct)))))))
  1583. parent-list)
  1584. ;; 1. List all parents with a checkbox.
  1585. (mapc
  1586. (lambda (e)
  1587. (let* ((parent (org-list-get-parent e struct parents))
  1588. (parent-box-p (org-list-get-checkbox parent struct)))
  1589. (when (and parent-box-p (not (memq parent parent-list)))
  1590. (push parent parent-list))))
  1591. all-items)
  1592. ;; 2. Sort those parents by decreasing indentation.
  1593. (setq parent-list (sort parent-list
  1594. (lambda (e1 e2)
  1595. (> (org-list-get-ind e1 struct)
  1596. (org-list-get-ind e2 struct)))))
  1597. ;; 3. For each parent, get all children's checkboxes to determine
  1598. ;; and set its checkbox accordingly.
  1599. (mapc set-parent-box parent-list)
  1600. ;; 4. If ORDERED is set, see if we need to uncheck some boxes.
  1601. (when ordered
  1602. (let* ((box-list
  1603. (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items))
  1604. (after-unchecked (member "[ ]" box-list)))
  1605. ;; There are boxes checked after an unchecked one: fix that.
  1606. (when (member "[X]" after-unchecked)
  1607. (let ((index (- (length struct) (length after-unchecked))))
  1608. (dolist (e (nthcdr index all-items))
  1609. (when (org-list-get-checkbox e struct)
  1610. (org-list-set-checkbox e struct "[ ]")))
  1611. ;; Verify once again the structure, without ORDERED.
  1612. (org-list-struct-fix-box struct parents prevs nil)
  1613. ;; Return blocking item.
  1614. (nth index all-items)))))))
  1615. (defun org-list-struct-fix-item-end (struct)
  1616. "Verify and correct each item end position in STRUCT.
  1617. This function modifies STRUCT."
  1618. (let (end-list acc-end)
  1619. (pcase-dolist (`(,pos . ,_) struct)
  1620. (let ((ind-pos (org-list-get-ind pos struct))
  1621. (end-pos (org-list-get-item-end pos struct)))
  1622. (unless (assq end-pos struct)
  1623. ;; To determine real ind of an ending position that is not
  1624. ;; at an item, we have to find the item it belongs to: it is
  1625. ;; the last item (ITEM-UP), whose ending is further than the
  1626. ;; position we're interested in.
  1627. (let ((item-up (assoc-default end-pos acc-end #'>)))
  1628. (push (cons
  1629. ;; Else part is for the bottom point.
  1630. (if item-up (+ (org-list-get-ind item-up struct) 2) 0)
  1631. end-pos)
  1632. end-list)))
  1633. (push (cons ind-pos pos) end-list)
  1634. (push (cons end-pos pos) acc-end)))
  1635. (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2)))))
  1636. (org-list-struct-assoc-end struct end-list)))
  1637. (defun org-list-struct-apply-struct (struct old-struct)
  1638. "Apply set difference between STRUCT and OLD-STRUCT to the buffer.
  1639. OLD-STRUCT is the structure before any modifications, and STRUCT
  1640. the structure to be applied. The function will only modify parts
  1641. of the list which have changed.
  1642. Initial position of cursor is restored after the changes."
  1643. (let* ((origin (point-marker))
  1644. (inlinetask-re (and (featurep 'org-inlinetask)
  1645. (org-inlinetask-outline-regexp)))
  1646. (item-re (org-item-re))
  1647. (shift-body-ind
  1648. ;; Shift the indentation between END and BEG by DELTA.
  1649. ;; Start from the line before END.
  1650. (lambda (end beg delta)
  1651. (goto-char end)
  1652. (skip-chars-backward " \r\t\n")
  1653. (beginning-of-line)
  1654. (while (or (> (point) beg)
  1655. (and (= (point) beg)
  1656. (not (looking-at item-re))))
  1657. (cond
  1658. ;; Skip inline tasks.
  1659. ((and inlinetask-re (looking-at inlinetask-re))
  1660. (org-inlinetask-goto-beginning))
  1661. ;; Shift only non-empty lines.
  1662. ((looking-at-p "^[ \t]*\\S-")
  1663. (indent-line-to (+ (org-current-text-indentation) delta))))
  1664. (forward-line -1))))
  1665. (modify-item
  1666. ;; Replace ITEM first line elements with new elements from
  1667. ;; STRUCT, if appropriate.
  1668. (lambda (item)
  1669. (goto-char item)
  1670. (let* ((new-ind (org-list-get-ind item struct))
  1671. (old-ind (org-current-text-indentation))
  1672. (new-bul (org-list-bullet-string
  1673. (org-list-get-bullet item struct)))
  1674. (old-bul (org-list-get-bullet item old-struct))
  1675. (new-box (org-list-get-checkbox item struct)))
  1676. (looking-at org-list-full-item-re)
  1677. ;; a. Replace bullet
  1678. (unless (equal old-bul new-bul)
  1679. (let ((keep-space ""))
  1680. (save-excursion
  1681. ;; If origin is inside the bullet, preserve the
  1682. ;; spaces after origin.
  1683. (when (<= (match-beginning 1) origin (match-end 1))
  1684. (org-with-point-at origin
  1685. (save-match-data
  1686. (when (looking-at "[ \t]+")
  1687. (setq keep-space (match-string 0))))))
  1688. (replace-match "" nil nil nil 1)
  1689. (goto-char (match-end 1))
  1690. (insert-before-markers new-bul)
  1691. (insert keep-space))))
  1692. ;; Refresh potentially shifted match markers.
  1693. (goto-char item)
  1694. (looking-at org-list-full-item-re)
  1695. ;; b. Replace checkbox.
  1696. (cond
  1697. ((equal (match-string 3) new-box))
  1698. ((and (match-string 3) new-box)
  1699. (replace-match new-box nil nil nil 3))
  1700. ((match-string 3)
  1701. (looking-at ".*?\\([ \t]*\\[[ X-]\\]\\)")
  1702. (replace-match "" nil nil nil 1))
  1703. (t (let ((counterp (match-end 2)))
  1704. (goto-char (if counterp (1+ counterp) (match-end 1)))
  1705. (insert (concat new-box (unless counterp " "))))))
  1706. ;; c. Indent item to appropriate column.
  1707. (unless (= new-ind old-ind)
  1708. (delete-region (goto-char (line-beginning-position))
  1709. (progn (skip-chars-forward " \t") (point)))
  1710. (indent-to new-ind))))))
  1711. ;; 1. First get list of items and position endings. We maintain
  1712. ;; two alists: ITM-SHIFT, determining indentation shift needed
  1713. ;; at item, and END-LIST, a pseudo-alist where key is ending
  1714. ;; position and value point.
  1715. (let (end-list acc-end itm-shift all-ends sliced-struct)
  1716. (dolist (e old-struct)
  1717. (let* ((pos (car e))
  1718. (ind-pos (org-list-get-ind pos struct))
  1719. (ind-old (org-list-get-ind pos old-struct))
  1720. (bul-pos (org-list-get-bullet pos struct))
  1721. (bul-old (org-list-get-bullet pos old-struct))
  1722. (ind-shift (- (+ ind-pos (length bul-pos))
  1723. (+ ind-old (length bul-old))))
  1724. (end-pos (org-list-get-item-end pos old-struct)))
  1725. (push (cons pos ind-shift) itm-shift)
  1726. (unless (assq end-pos old-struct)
  1727. ;; To determine real ind of an ending position that
  1728. ;; is not at an item, we have to find the item it
  1729. ;; belongs to: it is the last item (ITEM-UP), whose
  1730. ;; ending is further than the position we're
  1731. ;; interested in.
  1732. (let ((item-up (assoc-default end-pos acc-end #'>)))
  1733. (push (cons end-pos item-up) end-list)))
  1734. (push (cons end-pos pos) acc-end)))
  1735. ;; 2. Slice the items into parts that should be shifted by the
  1736. ;; same amount of indentation. Each slice follow the pattern
  1737. ;; (END BEG DELTA). Slices are returned in reverse order.
  1738. (setq all-ends (sort (append (mapcar #'car itm-shift)
  1739. (org-uniquify (mapcar #'car end-list)))
  1740. #'<)
  1741. acc-end (nreverse acc-end))
  1742. (while (cdr all-ends)
  1743. (let* ((up (pop all-ends))
  1744. (down (car all-ends))
  1745. (itemp (assq up struct))
  1746. (delta
  1747. (if itemp (cdr (assq up itm-shift))
  1748. ;; If we're not at an item, there's a child of the
  1749. ;; item point belongs to above. Make sure the less
  1750. ;; indented line in this slice has the same column
  1751. ;; as that child.
  1752. (let* ((child (cdr (assq up acc-end)))
  1753. (ind (org-list-get-ind child struct))
  1754. (min-ind most-positive-fixnum))
  1755. (save-excursion
  1756. (goto-char up)
  1757. (while (< (point) down)
  1758. ;; Ignore empty lines. Also ignore blocks and
  1759. ;; drawers contents.
  1760. (unless (looking-at-p "[ \t]*$")
  1761. (setq min-ind (min (org-current-text-indentation) min-ind))
  1762. (cond
  1763. ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)")
  1764. (re-search-forward
  1765. (format "^[ \t]*#\\+END%s[ \t]*$"
  1766. (match-string 1))
  1767. down t)))
  1768. ((and (looking-at org-drawer-regexp)
  1769. (re-search-forward "^[ \t]*:END:[ \t]*$"
  1770. down t)))))
  1771. (forward-line)))
  1772. (- ind min-ind)))))
  1773. (push (list down up delta) sliced-struct)))
  1774. ;; 3. Shift each slice in buffer, provided delta isn't 0, from
  1775. ;; end to beginning. Take a special action when beginning is
  1776. ;; at item bullet.
  1777. (dolist (e sliced-struct)
  1778. (unless (zerop (nth 2 e)) (apply shift-body-ind e))
  1779. (let* ((beg (nth 1 e))
  1780. (cell (assq beg struct)))
  1781. (unless (or (not cell) (equal cell (assq beg old-struct)))
  1782. (funcall modify-item beg)))))
  1783. ;; 4. Go back to initial position and clean marker.
  1784. (goto-char origin)
  1785. (move-marker origin nil)))
  1786. (defun org-list-write-struct (struct parents &optional old-struct)
  1787. "Correct bullets, checkboxes and indentation in list at point.
  1788. STRUCT is the list structure. PARENTS is the alist of parents,
  1789. as returned by `org-list-parents-alist'.
  1790. When non-nil, optional argument OLD-STRUCT is the reference
  1791. structure of the list. It should be provided whenever STRUCT
  1792. doesn't correspond anymore to the real list in buffer."
  1793. ;; Order of functions matters here: checkboxes and endings need
  1794. ;; correct indentation to be set, and indentation needs correct
  1795. ;; bullets.
  1796. ;;
  1797. ;; 0. Save a copy of structure before modifications
  1798. (let ((old-struct (or old-struct (copy-tree struct))))
  1799. ;; 1. Set a temporary, but coherent with PARENTS, indentation in
  1800. ;; order to get items endings and bullets properly
  1801. (org-list-struct-fix-ind struct parents 2)
  1802. ;; 2. Fix each item end to get correct prevs alist.
  1803. (org-list-struct-fix-item-end struct)
  1804. ;; 3. Get bullets right.
  1805. (let ((prevs (org-list-prevs-alist struct)))
  1806. (org-list-struct-fix-bul struct prevs)
  1807. ;; 4. Now get real indentation.
  1808. (org-list-struct-fix-ind struct parents)
  1809. ;; 5. Eventually fix checkboxes.
  1810. (org-list-struct-fix-box struct parents prevs))
  1811. ;; 6. Apply structure modifications to buffer.
  1812. (org-list-struct-apply-struct struct old-struct))
  1813. ;; 7. Return the updated structure
  1814. struct)
  1815. ;;; Misc Tools
  1816. (defun org-apply-on-list (function init-value &rest args)
  1817. "Call FUNCTION on each item of the list at point.
  1818. FUNCTION must be called with at least one argument: INIT-VALUE,
  1819. that will contain the value returned by the function at the
  1820. previous item, plus ARGS extra arguments.
  1821. FUNCTION is applied on items in reverse order.
  1822. As an example, \(org-apply-on-list \(lambda \(result) \(1+ result)) 0)
  1823. will return the number of items in the current list.
  1824. Sublists of the list are skipped. Cursor is always at the
  1825. beginning of the item."
  1826. (let* ((struct (org-list-struct))
  1827. (prevs (org-list-prevs-alist struct))
  1828. (item (copy-marker (line-beginning-position)))
  1829. (all (org-list-get-all-items (marker-position item) struct prevs))
  1830. (value init-value))
  1831. (dolist (e (nreverse all))
  1832. (goto-char e)
  1833. (setq value (apply function value args)))
  1834. (goto-char item)
  1835. (move-marker item nil)
  1836. value))
  1837. (defun org-list-set-item-visibility (item struct view)
  1838. "Set visibility of ITEM in STRUCT to VIEW.
  1839. Possible values are: `folded', `children' or `subtree'. See
  1840. `org-cycle' for more information."
  1841. (cond
  1842. ((eq view 'folded)
  1843. (let ((item-end (org-list-get-item-end-before-blank item struct)))
  1844. ;; Hide from eol
  1845. (org-fold-region (save-excursion (goto-char item) (line-end-position))
  1846. item-end t 'outline)))
  1847. ((eq view 'children)
  1848. ;; First show everything.
  1849. (org-list-set-item-visibility item struct 'subtree)
  1850. ;; Then fold every child.
  1851. (let* ((parents (org-list-parents-alist struct))
  1852. (children (org-list-get-children item struct parents)))
  1853. (dolist (child children)
  1854. (org-list-set-item-visibility child struct 'folded))))
  1855. ((eq view 'subtree)
  1856. ;; Show everything
  1857. (let ((item-end (org-list-get-item-end item struct)))
  1858. (org-fold-region item item-end nil 'outline)))))
  1859. (defun org-list-item-body-column (item)
  1860. "Return column at which body of ITEM should start."
  1861. (save-excursion
  1862. (goto-char item)
  1863. (looking-at "[ \t]*\\(\\S-+\\)")
  1864. (+ (progn (goto-char (match-end 1)) (current-column))
  1865. (if (and org-list-two-spaces-after-bullet-regexp
  1866. (string-match-p org-list-two-spaces-after-bullet-regexp
  1867. (match-string 1)))
  1868. 2
  1869. 1))))
  1870. ;;; Interactive functions
  1871. (defalias 'org-list-get-item-begin 'org-in-item-p)
  1872. (defun org-beginning-of-item ()
  1873. "Go to the beginning of the current item.
  1874. Throw an error when not in a list."
  1875. (interactive)
  1876. (let ((begin (org-in-item-p)))
  1877. (if begin (goto-char begin) (error "Not in an item"))))
  1878. (defun org-beginning-of-item-list ()
  1879. "Go to the beginning item of the current list or sublist.
  1880. Throw an error when not in a list."
  1881. (interactive)
  1882. (let ((begin (org-in-item-p)))
  1883. (if (not begin)
  1884. (error "Not in an item")
  1885. (goto-char begin)
  1886. (let* ((struct (org-list-struct))
  1887. (prevs (org-list-prevs-alist struct)))
  1888. (goto-char (org-list-get-list-begin begin struct prevs))))))
  1889. (defun org-end-of-item-list ()
  1890. "Go to the end of the current list or sublist.
  1891. Throw an error when not in a list."
  1892. (interactive)
  1893. (let ((begin (org-in-item-p)))
  1894. (if (not begin)
  1895. (error "Not in an item")
  1896. (goto-char begin)
  1897. (let* ((struct (org-list-struct))
  1898. (prevs (org-list-prevs-alist struct)))
  1899. (goto-char (org-list-get-list-end begin struct prevs))))))
  1900. (defun org-end-of-item ()
  1901. "Go to the end of the current item.
  1902. Throw an error when not in a list."
  1903. (interactive)
  1904. (let ((begin (org-in-item-p)))
  1905. (if (not begin)
  1906. (error "Not in an item")
  1907. (goto-char begin)
  1908. (let ((struct (org-list-struct)))
  1909. (goto-char (org-list-get-item-end begin struct))))))
  1910. (defun org-previous-item ()
  1911. "Move to the beginning of the previous item.
  1912. Throw an error when not in a list. Also throw an error when at
  1913. first item, unless `org-list-use-circular-motion' is non-nil."
  1914. (interactive)
  1915. (let ((item (org-in-item-p)))
  1916. (if (not item)
  1917. (error "Not in an item")
  1918. (goto-char item)
  1919. (let* ((struct (org-list-struct))
  1920. (prevs (org-list-prevs-alist struct))
  1921. (prevp (org-list-get-prev-item item struct prevs)))
  1922. (cond
  1923. (prevp (goto-char prevp))
  1924. (org-list-use-circular-motion
  1925. (goto-char (org-list-get-last-item item struct prevs)))
  1926. (t (error "On first item")))))))
  1927. (defun org-next-item ()
  1928. "Move to the beginning of the next item.
  1929. Throw an error when not in a list. Also throw an error when at
  1930. last item, unless `org-list-use-circular-motion' is non-nil."
  1931. (interactive)
  1932. (let ((item (org-in-item-p)))
  1933. (if (not item)
  1934. (error "Not in an item")
  1935. (goto-char item)
  1936. (let* ((struct (org-list-struct))
  1937. (prevs (org-list-prevs-alist struct))
  1938. (prevp (org-list-get-next-item item struct prevs)))
  1939. (cond
  1940. (prevp (goto-char prevp))
  1941. (org-list-use-circular-motion
  1942. (goto-char (org-list-get-first-item item struct prevs)))
  1943. (t (error "On last item")))))))
  1944. (defun org-move-item-down ()
  1945. "Move the item at point down, i.e. swap with following item.
  1946. Sub-items (items with larger indentation) are considered part of
  1947. the item, so this really moves item trees."
  1948. (interactive)
  1949. (unless (org-at-item-p) (error "Not at an item"))
  1950. (let* ((col (current-column))
  1951. (item (line-beginning-position))
  1952. (struct (org-list-struct))
  1953. (prevs (org-list-prevs-alist struct))
  1954. (next-item (org-list-get-next-item (line-beginning-position) struct prevs)))
  1955. (unless (or next-item org-list-use-circular-motion)
  1956. (user-error "Cannot move this item further down"))
  1957. (if (not next-item)
  1958. (setq struct (org-list-send-item item 'begin struct))
  1959. (setq struct (org-list-swap-items item next-item struct))
  1960. (goto-char
  1961. (org-list-get-next-item item struct (org-list-prevs-alist struct))))
  1962. (org-list-write-struct struct (org-list-parents-alist struct))
  1963. (org-move-to-column col)))
  1964. (defun org-move-item-up ()
  1965. "Move the item at point up, i.e. swap with previous item.
  1966. Sub-items (items with larger indentation) are considered part of
  1967. the item, so this really moves item trees."
  1968. (interactive)
  1969. (unless (org-at-item-p) (error "Not at an item"))
  1970. (let* ((col (current-column))
  1971. (item (line-beginning-position))
  1972. (struct (org-list-struct))
  1973. (prevs (org-list-prevs-alist struct))
  1974. (prev-item (org-list-get-prev-item (line-beginning-position) struct prevs)))
  1975. (unless (or prev-item org-list-use-circular-motion)
  1976. (user-error "Cannot move this item further up"))
  1977. (if (not prev-item)
  1978. (setq struct (org-list-send-item item 'end struct))
  1979. (setq struct (org-list-swap-items prev-item item struct)))
  1980. (org-list-write-struct struct (org-list-parents-alist struct))
  1981. (org-move-to-column col)))
  1982. (defun org-insert-item (&optional checkbox)
  1983. "Insert a new item at the current level.
  1984. If cursor is before first character after bullet of the item, the
  1985. new item will be created before the current one.
  1986. If CHECKBOX is non-nil, add a checkbox next to the bullet.
  1987. Return t when things worked, nil when we are not in an item, or
  1988. item is invisible."
  1989. (interactive "P")
  1990. (let ((itemp (org-in-item-p))
  1991. (pos (point)))
  1992. ;; If cursor isn't is a list or if list is invisible, return nil.
  1993. (unless (or (not itemp)
  1994. (save-excursion
  1995. (goto-char itemp)
  1996. (org-invisible-p)))
  1997. (if (save-excursion
  1998. (goto-char itemp)
  1999. (org-at-item-timer-p))
  2000. ;; Timer list: delegate to `org-timer-item'.
  2001. (progn (org-timer-item) t)
  2002. (let* ((struct (save-excursion (goto-char itemp)
  2003. (org-list-struct)))
  2004. (prevs (org-list-prevs-alist struct))
  2005. ;; If we're in a description list, ask for the new term.
  2006. (desc (when (eq (org-list-get-list-type itemp struct prevs)
  2007. 'descriptive)
  2008. " :: ")))
  2009. (setq struct (org-list-insert-item pos struct prevs checkbox desc))
  2010. (org-list-write-struct struct (org-list-parents-alist struct))
  2011. (when checkbox (org-update-checkbox-count-maybe))
  2012. (beginning-of-line)
  2013. (looking-at org-list-full-item-re)
  2014. (goto-char (if (and (match-beginning 4)
  2015. (save-match-data
  2016. (string-match "[.)]" (match-string 1))))
  2017. (match-beginning 4)
  2018. (match-end 0)))
  2019. (when desc (backward-char 1))
  2020. t)))))
  2021. (defun org-list-repair ()
  2022. "Fix indentation, bullets and checkboxes in the list at point."
  2023. (interactive)
  2024. (unless (org-at-item-p) (error "This is not a list"))
  2025. (let* ((struct (org-list-struct))
  2026. (parents (org-list-parents-alist struct)))
  2027. (org-list-write-struct struct parents)))
  2028. (defun org-cycle-list-bullet (&optional which)
  2029. "Cycle through the different itemize/enumerate bullets.
  2030. This cycle the entire list level through the sequence:
  2031. `-' -> `+' -> `*' -> `1.' -> `1)'
  2032. If WHICH is a valid string, use that as the new bullet. If WHICH
  2033. is an integer, 0 means `-', 1 means `+' etc. If WHICH is
  2034. `previous', cycle backwards."
  2035. (interactive "P")
  2036. (unless (org-at-item-p) (error "Not at an item"))
  2037. (let ((origin (point-marker)))
  2038. (beginning-of-line)
  2039. (let* ((struct (org-list-struct))
  2040. (parents (org-list-parents-alist struct))
  2041. (prevs (org-list-prevs-alist struct))
  2042. (list-beg (org-list-get-first-item (point) struct prevs))
  2043. ;; Record relative point position to bullet beginning.
  2044. (origin-offset (- origin
  2045. (+ (point) (org-list-get-ind (point) struct))))
  2046. ;; Record relative point position to bullet end.
  2047. (origin-offset2 (- origin
  2048. (+ (point) (org-list-get-ind (point) struct)
  2049. (length (org-list-get-bullet (point) struct)))))
  2050. (bullet (org-list-get-bullet list-beg struct))
  2051. (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs))
  2052. (case-fold-search nil)
  2053. (current (cond
  2054. ((string-match "[a-z]\\." bullet) "a.")
  2055. ((string-match "[a-z])" bullet) "a)")
  2056. ((string-match "[A-Z]\\." bullet) "A.")
  2057. ((string-match "[A-Z])" bullet) "A)")
  2058. ((string-match "\\." bullet) "1.")
  2059. ((string-match ")" bullet) "1)")
  2060. (t (org-trim bullet))))
  2061. ;; Compute list of possible bullets, depending on context.
  2062. (bullet-list
  2063. (append '("-" "+" )
  2064. ;; *-bullets are not allowed at column 0.
  2065. (unless (looking-at "\\S-") '("*"))
  2066. ;; Description items cannot be numbered.
  2067. (unless (or (eq org-plain-list-ordered-item-terminator ?\))
  2068. (org-at-item-description-p))
  2069. '("1."))
  2070. (unless (or (eq org-plain-list-ordered-item-terminator ?.)
  2071. (org-at-item-description-p))
  2072. '("1)"))
  2073. (unless (or (not alpha-p)
  2074. (eq org-plain-list-ordered-item-terminator ?\))
  2075. (org-at-item-description-p))
  2076. '("a." "A."))
  2077. (unless (or (not alpha-p)
  2078. (eq org-plain-list-ordered-item-terminator ?.)
  2079. (org-at-item-description-p))
  2080. '("a)" "A)"))))
  2081. (len (length bullet-list))
  2082. (item-index (- len (length (member current bullet-list))))
  2083. (get-value (lambda (index) (nth (mod index len) bullet-list)))
  2084. (new (cond
  2085. ((member which bullet-list) which)
  2086. ((numberp which) (funcall get-value which))
  2087. ((eq 'previous which) (funcall get-value (1- item-index)))
  2088. (t (funcall get-value (1+ item-index))))))
  2089. ;; Use a short variation of `org-list-write-struct' as there's
  2090. ;; no need to go through all the steps.
  2091. (let ((old-struct (copy-tree struct)))
  2092. (org-list-set-bullet list-beg struct (org-list-bullet-string new))
  2093. (org-list-struct-fix-bul struct prevs)
  2094. (org-list-struct-fix-ind struct parents)
  2095. (org-list-struct-apply-struct struct old-struct))
  2096. (goto-char origin)
  2097. (setq struct (org-list-struct))
  2098. (cond
  2099. ((>= origin-offset2 0)
  2100. (beginning-of-line)
  2101. (move-marker origin (+ (point)
  2102. (org-list-get-ind (point) struct)
  2103. (length (org-list-get-bullet (point) struct))
  2104. origin-offset2))
  2105. (goto-char origin))
  2106. ((>= origin-offset 0)
  2107. (beginning-of-line)
  2108. (move-marker origin (+ (point)
  2109. (org-list-get-ind (point) struct)
  2110. origin-offset))
  2111. (goto-char origin)))
  2112. (move-marker origin nil))))
  2113. ;;;###autoload
  2114. (define-minor-mode org-list-checkbox-radio-mode
  2115. "When turned on, use list checkboxes as radio buttons."
  2116. :lighter " CheckBoxRadio"
  2117. (unless (eq major-mode 'org-mode)
  2118. (user-error "Cannot turn this mode outside org-mode buffers")))
  2119. (defun org-toggle-radio-button (&optional arg)
  2120. "Toggle off all checkboxes and toggle on the one at point."
  2121. (interactive "P")
  2122. (if (not (org-at-item-p))
  2123. (user-error "Cannot toggle checkbox outside of a list")
  2124. (let* ((cpos (org-in-item-p))
  2125. (struct (org-list-struct))
  2126. (orderedp (org-entry-get nil "ORDERED"))
  2127. (parents (org-list-parents-alist struct))
  2128. (old-struct (copy-tree struct))
  2129. (cbox (org-list-get-checkbox cpos struct))
  2130. (prevs (org-list-prevs-alist struct))
  2131. (start (org-list-get-list-begin (line-beginning-position) struct prevs))
  2132. (new (unless (and cbox (equal arg '(4)) (equal start cpos))
  2133. "[ ]")))
  2134. (dolist (pos (org-list-get-all-items
  2135. start struct (org-list-prevs-alist struct)))
  2136. (org-list-set-checkbox pos struct new))
  2137. (when new
  2138. (org-list-set-checkbox
  2139. cpos struct
  2140. (cond ((equal arg '(4)) (unless cbox "[ ]"))
  2141. ((equal arg '(16)) (unless cbox "[-]"))
  2142. (t (if (equal cbox "[X]") "[ ]" "[X]")))))
  2143. (org-list-struct-fix-box struct parents prevs orderedp)
  2144. (org-list-struct-apply-struct struct old-struct)
  2145. (org-update-checkbox-count-maybe))))
  2146. (defun org-at-radio-list-p ()
  2147. "Is point at a list item with radio buttons?"
  2148. (when (org-match-line (org-item-re)) ;short-circuit
  2149. (let* ((e (save-excursion (beginning-of-line) (org-element-at-point))))
  2150. ;; Check we're really on a line with a bullet.
  2151. (when (memq (org-element-type e) '(item plain-list))
  2152. ;; Look for ATTR_ORG attribute in the current plain list.
  2153. (let ((plain-list (org-element-lineage e '(plain-list) t)))
  2154. (org-with-point-at (org-element-property :post-affiliated plain-list)
  2155. (let ((case-fold-search t)
  2156. (regexp "^[ \t]*#\\+attr_org:.* :radio \\(\\S-+\\)")
  2157. (begin (org-element-property :begin plain-list)))
  2158. (and (re-search-backward regexp begin t)
  2159. (not (string-equal "nil" (match-string 1)))))))))))
  2160. (defun org-toggle-checkbox (&optional toggle-presence)
  2161. "Toggle the checkbox in the current line.
  2162. With prefix argument TOGGLE-PRESENCE, add or remove checkboxes.
  2163. With a double prefix argument, set the checkbox to \"[-]\".
  2164. When there is an active region, toggle status or presence of the
  2165. first checkbox there, and make every item inside have the same
  2166. status or presence, respectively.
  2167. If point is on a headline, apply this to all checkbox items in
  2168. the text below the heading, taking as reference the first item in
  2169. subtree, ignoring planning line and any drawer following it."
  2170. (interactive "P")
  2171. (if (org-at-radio-list-p)
  2172. (org-toggle-radio-button toggle-presence)
  2173. (save-excursion
  2174. (let* (singlep
  2175. block-item
  2176. lim-up
  2177. lim-down
  2178. (orderedp (org-entry-get nil "ORDERED"))
  2179. (_bounds
  2180. ;; In a region, start at first item in region.
  2181. (cond
  2182. ((org-region-active-p)
  2183. (let ((limit (region-end)))
  2184. (goto-char (region-beginning))
  2185. (if (org-list-search-forward (org-item-beginning-re) limit t)
  2186. (setq lim-up (line-beginning-position))
  2187. (error "No item in region"))
  2188. (setq lim-down (copy-marker limit))))
  2189. ((org-at-heading-p)
  2190. ;; On a heading, start at first item after drawers and
  2191. ;; time-stamps (scheduled, etc.).
  2192. (let ((limit (save-excursion (outline-next-heading) (point))))
  2193. (org-end-of-meta-data t)
  2194. (if (org-list-search-forward (org-item-beginning-re) limit t)
  2195. (setq lim-up (line-beginning-position))
  2196. (error "No item in subtree"))
  2197. (setq lim-down (copy-marker limit))))
  2198. ;; Just one item: set SINGLEP flag.
  2199. ((org-at-item-p)
  2200. (setq singlep t)
  2201. (setq lim-up (line-beginning-position)
  2202. lim-down (copy-marker (line-end-position))))
  2203. (t (error "Not at an item or heading, and no active region"))))
  2204. ;; Determine the checkbox going to be applied to all items
  2205. ;; within bounds.
  2206. (ref-checkbox
  2207. (progn
  2208. (goto-char lim-up)
  2209. (let ((cbox (and (org-at-item-checkbox-p) (match-string 1))))
  2210. (cond
  2211. ((equal toggle-presence '(16)) "[-]")
  2212. ((equal toggle-presence '(4))
  2213. (unless cbox "[ ]"))
  2214. ((equal "[X]" cbox) "[ ]")
  2215. (t "[X]"))))))
  2216. ;; When an item is found within bounds, grab the full list at
  2217. ;; point structure, then: (1) set check-box of all its items
  2218. ;; within bounds to REF-CHECKBOX, (2) fix check-boxes of the
  2219. ;; whole list, (3) move point after the list.
  2220. (goto-char lim-up)
  2221. (while (and (< (point) lim-down)
  2222. (org-list-search-forward (org-item-beginning-re)
  2223. lim-down 'move))
  2224. (let* ((struct (org-list-struct))
  2225. (struct-copy (copy-tree struct))
  2226. (parents (org-list-parents-alist struct))
  2227. (prevs (org-list-prevs-alist struct))
  2228. (bottom (copy-marker (org-list-get-bottom-point struct)))
  2229. (items-to-toggle (cl-remove-if
  2230. (lambda (e) (or (< e lim-up) (> e lim-down)))
  2231. (mapcar #'car struct))))
  2232. (dolist (e items-to-toggle)
  2233. (org-list-set-checkbox
  2234. e struct
  2235. ;; If there is no box at item, leave as-is unless
  2236. ;; function was called with C-u prefix.
  2237. (let ((cur-box (org-list-get-checkbox e struct)))
  2238. (if (or cur-box (equal toggle-presence '(4)))
  2239. ref-checkbox
  2240. cur-box))))
  2241. (setq block-item (org-list-struct-fix-box
  2242. struct parents prevs orderedp))
  2243. ;; Report some problems due to ORDERED status of subtree.
  2244. ;; If only one box was being checked, throw an error, else,
  2245. ;; only signal problems.
  2246. (cond
  2247. ((and singlep block-item (> lim-up block-item))
  2248. (error
  2249. "Checkbox blocked because of unchecked box at line %d"
  2250. (org-current-line block-item)))
  2251. (block-item
  2252. (message
  2253. "Checkboxes were removed due to unchecked box at line %d"
  2254. (org-current-line block-item))))
  2255. (goto-char bottom)
  2256. (move-marker bottom nil)
  2257. (org-list-struct-apply-struct struct struct-copy)))
  2258. (move-marker lim-down nil))))
  2259. (org-update-checkbox-count-maybe))
  2260. (defun org-reset-checkbox-state-subtree ()
  2261. "Reset all checkboxes in an entry subtree."
  2262. (interactive "*")
  2263. (if (org-before-first-heading-p)
  2264. (error "Not inside a tree")
  2265. (save-restriction
  2266. (save-excursion
  2267. (org-narrow-to-subtree)
  2268. (org-fold-show-subtree)
  2269. (goto-char (point-min))
  2270. (let ((end (point-max)))
  2271. (while (< (point) end)
  2272. (when (org-at-item-checkbox-p)
  2273. (replace-match "[ ]" t t nil 1))
  2274. (beginning-of-line 2)))
  2275. (org-update-checkbox-count-maybe 'all)))))
  2276. (defun org-update-checkbox-count (&optional all)
  2277. "Update the checkbox statistics in the current section.
  2278. This will find all statistic cookies like [57%] and [6/12] and
  2279. update them with the current numbers.
  2280. With optional prefix argument ALL, do this for the whole buffer."
  2281. (interactive "P")
  2282. (org-with-wide-buffer
  2283. (let* ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  2284. (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\
  2285. \\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)")
  2286. (cookie-data (or (org-entry-get nil "COOKIE_DATA") ""))
  2287. (recursivep
  2288. (or (not org-checkbox-hierarchical-statistics)
  2289. (string-match-p "\\<recursive\\>" cookie-data)))
  2290. (within-inlinetask (and (not all)
  2291. (featurep 'org-inlinetask)
  2292. (org-inlinetask-in-task-p)))
  2293. (end (cond (all (point-max))
  2294. (within-inlinetask
  2295. (save-excursion (outline-next-heading) (point)))
  2296. (t (save-excursion
  2297. (org-with-limited-levels (outline-next-heading))
  2298. (point)))))
  2299. (count-boxes
  2300. (lambda (item structs recursivep)
  2301. ;; Return number of checked boxes and boxes of all types
  2302. ;; in all structures in STRUCTS. If RECURSIVEP is
  2303. ;; non-nil, also count boxes in sub-lists. If ITEM is
  2304. ;; nil, count across the whole structure, else count only
  2305. ;; across subtree whose ancestor is ITEM.
  2306. (let ((c-on 0) (c-all 0))
  2307. (dolist (s structs (list c-on c-all))
  2308. (let* ((pre (org-list-prevs-alist s))
  2309. (par (org-list-parents-alist s))
  2310. (items
  2311. (cond
  2312. ((and recursivep item) (org-list-get-subtree item s))
  2313. (recursivep (mapcar #'car s))
  2314. (item (org-list-get-children item s par))
  2315. (t (org-list-get-all-items
  2316. (org-list-get-top-point s) s pre))))
  2317. (cookies (delq nil (mapcar
  2318. (lambda (e)
  2319. (org-list-get-checkbox e s))
  2320. items))))
  2321. (cl-incf c-all (length cookies))
  2322. (cl-incf c-on (cl-count "[X]" cookies :test #'equal)))))))
  2323. cookies-list cache)
  2324. ;; Move to start.
  2325. (cond (all (goto-char (point-min)))
  2326. (within-inlinetask (org-back-to-heading t))
  2327. (t (org-with-limited-levels (outline-previous-heading))))
  2328. ;; Build an alist for each cookie found. The key is the position
  2329. ;; at beginning of cookie and values ending position, format of
  2330. ;; cookie, number of checked boxes to report and total number of
  2331. ;; boxes.
  2332. (while (re-search-forward cookie-re end t)
  2333. (let ((context (save-excursion (backward-char)
  2334. (save-match-data (org-element-context)))))
  2335. (when (and (eq (org-element-type context) 'statistics-cookie)
  2336. (not (string-match-p "\\<todo\\>" cookie-data)))
  2337. (push
  2338. (append
  2339. (list (match-beginning 1) (match-end 1) (match-end 2))
  2340. (let* ((container
  2341. (org-element-lineage
  2342. context
  2343. '(drawer center-block dynamic-block inlinetask item
  2344. quote-block special-block verse-block)))
  2345. (beg (if container
  2346. (org-element-property :contents-begin container)
  2347. (save-excursion
  2348. (org-with-limited-levels
  2349. (outline-previous-heading))
  2350. (point)))))
  2351. (or (cdr (assq beg cache))
  2352. (save-excursion
  2353. (goto-char beg)
  2354. (let ((end
  2355. (if container
  2356. (org-element-property :contents-end container)
  2357. (save-excursion
  2358. (org-with-limited-levels (outline-next-heading))
  2359. (point))))
  2360. structs)
  2361. (while (re-search-forward box-re end t)
  2362. (let ((element (org-element-at-point)))
  2363. (when (eq (org-element-type element) 'item)
  2364. (push (org-element-property :structure element)
  2365. structs)
  2366. ;; Skip whole list since we have its
  2367. ;; structure anyway.
  2368. (while (setq element (org-element-lineage
  2369. element '(plain-list)))
  2370. (goto-char
  2371. (min (org-element-property :end element)
  2372. end))))))
  2373. ;; Cache count for cookies applying to the same
  2374. ;; area. Then return it.
  2375. (let ((count
  2376. (funcall count-boxes
  2377. (and (eq (org-element-type container)
  2378. 'item)
  2379. (org-element-property
  2380. :begin container))
  2381. structs
  2382. recursivep)))
  2383. (push (cons beg count) cache)
  2384. count))))))
  2385. cookies-list))))
  2386. ;; Apply alist to buffer.
  2387. (dolist (cookie cookies-list)
  2388. (let* ((beg (car cookie))
  2389. (end (nth 1 cookie))
  2390. (percent (nth 2 cookie))
  2391. (checked (nth 3 cookie))
  2392. (total (nth 4 cookie)))
  2393. (goto-char beg)
  2394. (insert
  2395. (if percent (format "[%d%%]" (floor (* 100.0 checked)
  2396. (max 1 total)))
  2397. (format "[%d/%d]" checked total)))
  2398. (delete-region (point) (+ (point) (- end beg)))
  2399. (when org-auto-align-tags (org-fix-tags-on-the-fly)))))))
  2400. (defun org-get-checkbox-statistics-face ()
  2401. "Select the face for checkbox statistics.
  2402. The face will be `org-done' when all relevant boxes are checked.
  2403. Otherwise it will be `org-todo'."
  2404. (if (match-end 1)
  2405. (if (equal (match-string 1) "100%")
  2406. 'org-checkbox-statistics-done
  2407. 'org-checkbox-statistics-todo)
  2408. (if (and (> (match-end 2) (match-beginning 2))
  2409. (equal (match-string 2) (match-string 3)))
  2410. 'org-checkbox-statistics-done
  2411. 'org-checkbox-statistics-todo)))
  2412. (defun org-update-checkbox-count-maybe (&optional all)
  2413. "Update checkbox statistics unless turned off by user.
  2414. With an optional argument ALL, update them in the whole buffer."
  2415. (when (cdr (assq 'checkbox org-list-automatic-rules))
  2416. (org-update-checkbox-count all))
  2417. (run-hooks 'org-checkbox-statistics-hook))
  2418. (defvar org-last-indent-begin-marker (make-marker))
  2419. (defvar org-last-indent-end-marker (make-marker))
  2420. (defun org-list-indent-item-generic (arg no-subtree struct)
  2421. "Indent a local list item including its children.
  2422. When number ARG is a negative, item will be outdented, otherwise
  2423. it will be indented.
  2424. If a region is active, all items inside will be moved.
  2425. If NO-SUBTREE is non-nil, only indent the item itself, not its
  2426. children.
  2427. STRUCT is the list structure.
  2428. Return t if successful."
  2429. (save-excursion
  2430. (let* ((regionp (org-region-active-p))
  2431. (rbeg (and regionp (region-beginning)))
  2432. (rend (and regionp (region-end)))
  2433. (top (org-list-get-top-point struct))
  2434. (parents (org-list-parents-alist struct))
  2435. (prevs (org-list-prevs-alist struct))
  2436. ;; Are we going to move the whole list?
  2437. (specialp
  2438. (and (not regionp)
  2439. (= top (line-beginning-position))
  2440. (cdr (assq 'indent org-list-automatic-rules))
  2441. (if no-subtree
  2442. (user-error
  2443. "At first item: use S-M-<left/right> to move the whole list")
  2444. t))))
  2445. ;; Determine begin and end points of zone to indent. If moving
  2446. ;; more than one item, save them for subsequent moves.
  2447. (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft))
  2448. (memq this-command '(org-shiftmetaright org-shiftmetaleft)))
  2449. (if regionp
  2450. (progn
  2451. (set-marker org-last-indent-begin-marker rbeg)
  2452. (set-marker org-last-indent-end-marker rend))
  2453. (set-marker org-last-indent-begin-marker (line-beginning-position))
  2454. (set-marker org-last-indent-end-marker
  2455. (cond
  2456. (specialp (org-list-get-bottom-point struct))
  2457. (no-subtree (1+ (line-beginning-position)))
  2458. (t (org-list-get-item-end (line-beginning-position) struct))))))
  2459. (let* ((beg (marker-position org-last-indent-begin-marker))
  2460. (end (marker-position org-last-indent-end-marker)))
  2461. (cond
  2462. ;; Special case: moving top-item with indent rule.
  2463. (specialp
  2464. (let* ((level-skip (org-level-increment))
  2465. (offset (if (< arg 0) (- level-skip) level-skip))
  2466. (top-ind (org-list-get-ind beg struct))
  2467. (old-struct (copy-tree struct)))
  2468. (if (< (+ top-ind offset) 0)
  2469. (error "Cannot outdent beyond margin")
  2470. ;; Change bullet if necessary.
  2471. (when (and (= (+ top-ind offset) 0)
  2472. (string-match "\\*"
  2473. (org-list-get-bullet beg struct)))
  2474. (org-list-set-bullet beg struct
  2475. (org-list-bullet-string "-")))
  2476. ;; Shift every item by OFFSET and fix bullets. Then
  2477. ;; apply changes to buffer.
  2478. (pcase-dolist (`(,pos . ,_) struct)
  2479. (let ((ind (org-list-get-ind pos struct)))
  2480. (org-list-set-ind pos struct (+ ind offset))))
  2481. (org-list-struct-fix-bul struct prevs)
  2482. (org-list-struct-apply-struct struct old-struct))))
  2483. ;; Forbidden move:
  2484. ((and (< arg 0)
  2485. ;; If only one item is moved, it mustn't have a child.
  2486. (or (and no-subtree
  2487. (not regionp)
  2488. (org-list-has-child-p beg struct))
  2489. ;; If a subtree or region is moved, the last item
  2490. ;; of the subtree mustn't have a child.
  2491. (let ((last-item (caar
  2492. (reverse
  2493. (cl-remove-if
  2494. (lambda (e) (>= (car e) end))
  2495. struct)))))
  2496. (org-list-has-child-p last-item struct))))
  2497. (error "Cannot outdent an item without its children"))
  2498. ;; Normal shifting
  2499. (t
  2500. (let* ((old-struct (copy-tree struct))
  2501. (new-parents
  2502. (if (< arg 0)
  2503. (org-list-struct-outdent beg end struct parents)
  2504. (org-list-struct-indent beg end struct parents prevs))))
  2505. (org-list-write-struct struct new-parents old-struct))
  2506. (org-update-checkbox-count-maybe))))))
  2507. t)
  2508. (defun org-outdent-item ()
  2509. "Outdent a local list item, but not its children.
  2510. If a region is active, all items inside will be moved."
  2511. (interactive)
  2512. (let ((regionp (org-region-active-p)))
  2513. (cond
  2514. ((or (org-at-item-p)
  2515. (and regionp
  2516. (save-excursion (goto-char (region-beginning))
  2517. (org-at-item-p))))
  2518. (let ((struct (if (not regionp) (org-list-struct)
  2519. (save-excursion (goto-char (region-beginning))
  2520. (org-list-struct)))))
  2521. (org-list-indent-item-generic -1 t struct)))
  2522. (regionp (error "Region not starting at an item"))
  2523. (t (error "Not at an item")))))
  2524. (defun org-indent-item ()
  2525. "Indent a local list item, but not its children.
  2526. If a region is active, all items inside will be moved."
  2527. (interactive)
  2528. (let ((regionp (org-region-active-p)))
  2529. (cond
  2530. ((or (org-at-item-p)
  2531. (and regionp
  2532. (save-excursion (goto-char (region-beginning))
  2533. (org-at-item-p))))
  2534. (let ((struct (if (not regionp) (org-list-struct)
  2535. (save-excursion (goto-char (region-beginning))
  2536. (org-list-struct)))))
  2537. (org-list-indent-item-generic 1 t struct)))
  2538. (regionp (error "Region not starting at an item"))
  2539. (t (error "Not at an item")))))
  2540. (defun org-outdent-item-tree ()
  2541. "Outdent a local list item including its children.
  2542. If a region is active, all items inside will be moved."
  2543. (interactive)
  2544. (let ((regionp (org-region-active-p)))
  2545. (cond
  2546. ((or (org-at-item-p)
  2547. (and regionp
  2548. (save-excursion (goto-char (region-beginning))
  2549. (org-at-item-p))))
  2550. (let ((struct (if (not regionp) (org-list-struct)
  2551. (save-excursion (goto-char (region-beginning))
  2552. (org-list-struct)))))
  2553. (org-list-indent-item-generic -1 nil struct)))
  2554. (regionp (error "Region not starting at an item"))
  2555. (t (error "Not at an item")))))
  2556. (defun org-indent-item-tree ()
  2557. "Indent a local list item including its children.
  2558. If a region is active, all items inside will be moved."
  2559. (interactive)
  2560. (let ((regionp (org-region-active-p)))
  2561. (cond
  2562. ((or (org-at-item-p)
  2563. (and regionp
  2564. (save-excursion (goto-char (region-beginning))
  2565. (org-at-item-p))))
  2566. (let ((struct (if (not regionp) (org-list-struct)
  2567. (save-excursion (goto-char (region-beginning))
  2568. (org-list-struct)))))
  2569. (org-list-indent-item-generic 1 nil struct)))
  2570. (regionp (error "Region not starting at an item"))
  2571. (t (error "Not at an item")))))
  2572. (defvar org-tab-ind-state)
  2573. (defun org-cycle-item-indentation ()
  2574. "Cycle levels of indentation of an empty item.
  2575. The first run indents the item, if applicable. Subsequent runs
  2576. outdent it at meaningful levels in the list. When done, item is
  2577. put back at its original position with its original bullet.
  2578. Return t at each successful move."
  2579. (when (org-at-item-p)
  2580. (let* ((struct (org-list-struct))
  2581. (item (line-beginning-position))
  2582. (ind (org-list-get-ind item struct)))
  2583. ;; Accept empty items or if cycle has already started.
  2584. (when (or (eq last-command 'org-cycle-item-indentation)
  2585. (and (org-match-line org-list-full-item-re)
  2586. (>= (match-end 0)
  2587. (save-excursion
  2588. (goto-char (org-list-get-item-end item struct))
  2589. (skip-chars-backward " \t\n")
  2590. (point)))))
  2591. (setq this-command 'org-cycle-item-indentation)
  2592. (let ((prevs (org-list-prevs-alist struct))
  2593. (parents (org-list-parents-alist struct)))
  2594. (if (eq last-command 'org-cycle-item-indentation)
  2595. ;; When in the middle of the cycle, try to outdent. If
  2596. ;; it fails, move point back to its initial position and
  2597. ;; reset cycle.
  2598. (pcase-let ((`(,old-ind . ,old-bul) org-tab-ind-state)
  2599. (allow-outdent
  2600. (lambda (struct prevs parents)
  2601. ;; Non-nil if current item can be
  2602. ;; outdented.
  2603. (and (not (org-list-get-next-item item nil prevs))
  2604. (not (org-list-has-child-p item struct))
  2605. (org-list-get-parent item struct parents)))))
  2606. (cond
  2607. ((and (> ind old-ind)
  2608. (org-list-get-prev-item item nil prevs))
  2609. (org-list-indent-item-generic 1 t struct))
  2610. ((and (< ind old-ind)
  2611. (funcall allow-outdent struct prevs parents))
  2612. (org-list-indent-item-generic -1 t struct))
  2613. (t
  2614. (delete-region (line-beginning-position) (line-end-position))
  2615. (indent-to-column old-ind)
  2616. (insert old-bul " ")
  2617. (let* ((struct (org-list-struct))
  2618. (parents (org-list-parents-alist struct)))
  2619. (if (and (> ind old-ind)
  2620. ;; We were previously indenting item. It
  2621. ;; is no longer possible. Try to outdent
  2622. ;; from initial position.
  2623. (funcall allow-outdent
  2624. struct
  2625. (org-list-prevs-alist struct)
  2626. parents))
  2627. (org-list-indent-item-generic -1 t struct)
  2628. (org-list-write-struct struct parents)
  2629. ;; Start cycle over.
  2630. (setq this-command 'identity)
  2631. t)))))
  2632. ;; If a cycle is starting, remember initial indentation
  2633. ;; and bullet, then try to indent. If it fails, try to
  2634. ;; outdent.
  2635. (setq org-tab-ind-state
  2636. (cons ind (org-trim (org-current-line-string))))
  2637. (cond
  2638. ((org-list-get-prev-item item nil prevs)
  2639. (org-list-indent-item-generic 1 t struct))
  2640. ((and (not (org-list-get-next-item item nil prevs))
  2641. (org-list-get-parent item struct parents))
  2642. (org-list-indent-item-generic -1 t struct))
  2643. (t
  2644. ;; This command failed. So will the following one.
  2645. ;; There's no point in starting the cycle.
  2646. (setq this-command 'identity)
  2647. (user-error "Cannot move item")))))))))
  2648. (defun org-sort-list
  2649. (&optional with-case sorting-type getkey-func compare-func interactive?)
  2650. "Sort list items.
  2651. The cursor may be at any item of the list that should be sorted.
  2652. Sublists are not sorted. Checkboxes, if any, are ignored.
  2653. Sorting can be alphabetically, numerically, by date/time as given
  2654. by a time stamp, by a property or by priority.
  2655. Comparing entries ignores case by default. However, with an
  2656. optional argument WITH-CASE, the sorting considers case as well,
  2657. if the current locale allows for it.
  2658. The command prompts for the sorting type unless it has been given
  2659. to the function through the SORTING-TYPE argument, which needs to
  2660. be a character, among ?n ?N ?a ?A ?t ?T ?f ?F ?x or ?X. Here is
  2661. the detailed meaning of each character:
  2662. n Numerically, by converting the beginning of the item to a number.
  2663. a Alphabetically. Only the first line of item is checked.
  2664. t By date/time, either the first active time stamp in the entry, if
  2665. any, or by the first inactive one. In a timer list, sort the timers.
  2666. x By \"checked\" status of a check list.
  2667. Capital letters will reverse the sort order.
  2668. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
  2669. a function to be called with point at the beginning of the
  2670. record. It must return a value that is compatible with COMPARE-FUNC,
  2671. the function used to compare entries.
  2672. Sorting is done against the visible part of the headlines, it
  2673. ignores hidden links.
  2674. A non-nil value for INTERACTIVE? is used to signal that this
  2675. function is being called interactively."
  2676. (interactive (list current-prefix-arg nil nil nil t))
  2677. (let* ((case-func (if with-case 'identity 'downcase))
  2678. (struct (org-list-struct))
  2679. (prevs (org-list-prevs-alist struct))
  2680. (start (org-list-get-list-begin (line-beginning-position) struct prevs))
  2681. (end (org-list-get-list-end (line-beginning-position) struct prevs))
  2682. (sorting-type
  2683. (or sorting-type
  2684. (progn
  2685. (message
  2686. "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc [x]checked A/N/T/F/X means reversed:")
  2687. (read-char-exclusive))))
  2688. (dcst (downcase sorting-type))
  2689. (getkey-func
  2690. (and (= dcst ?f)
  2691. (or getkey-func
  2692. (and interactive?
  2693. (org-read-function "Function for extracting keys: "))
  2694. (error "Missing key extractor"))))
  2695. (sort-func
  2696. (cond
  2697. ((= dcst ?a) #'string-collate-lessp)
  2698. ((= dcst ?f)
  2699. (or compare-func
  2700. (and interactive?
  2701. (org-read-function
  2702. (concat "Function for comparing keys "
  2703. "(empty for default `sort-subr' predicate): ")
  2704. 'allow-empty))))
  2705. ((= dcst ?t) #'<)
  2706. ((= dcst ?x) #'string<))))
  2707. (message "Sorting items...")
  2708. (save-restriction
  2709. (narrow-to-region start end)
  2710. (goto-char (point-min))
  2711. (let* ((case-fold-search nil)
  2712. (now (current-time))
  2713. (next-record (lambda ()
  2714. (skip-chars-forward " \r\t\n")
  2715. (or (eobp) (beginning-of-line))))
  2716. (end-record (lambda ()
  2717. (goto-char (org-list-get-item-end-before-blank
  2718. (point) struct))))
  2719. (value-to-sort
  2720. (lambda ()
  2721. (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
  2722. (cond
  2723. ((= dcst ?n)
  2724. (string-to-number
  2725. (org-sort-remove-invisible
  2726. (buffer-substring (match-end 0) (line-end-position)))))
  2727. ((= dcst ?a)
  2728. (funcall case-func
  2729. (org-sort-remove-invisible
  2730. (buffer-substring
  2731. (match-end 0) (line-end-position)))))
  2732. ((= dcst ?t)
  2733. (cond
  2734. ;; If it is a timer list, convert timer to seconds
  2735. ((org-at-item-timer-p)
  2736. (org-timer-hms-to-secs (match-string 1)))
  2737. ((or (save-excursion
  2738. (re-search-forward org-ts-regexp (line-end-position) t))
  2739. (save-excursion (re-search-forward org-ts-regexp-both
  2740. (line-end-position) t)))
  2741. (org-time-string-to-seconds (match-string 0)))
  2742. (t (float-time now))))
  2743. ((= dcst ?x) (or (and (stringp (match-string 1))
  2744. (match-string 1))
  2745. ""))
  2746. ((= dcst ?f)
  2747. (if getkey-func
  2748. (let ((value (funcall getkey-func)))
  2749. (if (stringp value)
  2750. (funcall case-func value)
  2751. value))
  2752. (error "Invalid key function `%s'" getkey-func)))
  2753. (t (error "Invalid sorting type `%c'" sorting-type)))))))
  2754. (sort-subr (/= dcst sorting-type)
  2755. next-record
  2756. end-record
  2757. value-to-sort
  2758. nil
  2759. sort-func)
  2760. ;; Read and fix list again, as `sort-subr' probably destroyed
  2761. ;; its structure.
  2762. (org-list-repair)
  2763. (run-hooks 'org-after-sorting-entries-or-items-hook)
  2764. (message "Sorting items...done")))))
  2765. (defun org-toggle-item (arg)
  2766. "Convert headings or normal lines to items, items to normal lines.
  2767. If there is no active region, only the current line is considered.
  2768. If the first non blank line in the region is a headline, convert
  2769. all headlines to items, shifting text accordingly.
  2770. If it is an item, convert all items to normal lines.
  2771. If it is normal text, change region into a list of items.
  2772. With a prefix argument ARG, change the region in a single item."
  2773. (interactive "P")
  2774. (let ((shift-text
  2775. (lambda (ind end)
  2776. ;; Shift text in current section to IND, from point to END.
  2777. ;; The function leaves point to END line.
  2778. (let ((min-i 1000) (end (copy-marker end)))
  2779. ;; First determine the minimum indentation (MIN-I) of
  2780. ;; the text.
  2781. (save-excursion
  2782. (catch 'exit
  2783. (while (< (point) end)
  2784. (let ((i (org-current-text-indentation)))
  2785. (cond
  2786. ;; Skip blank lines and inline tasks.
  2787. ((looking-at "^[ \t]*$"))
  2788. ((looking-at org-outline-regexp-bol))
  2789. ;; We can't find less than 0 indentation.
  2790. ((zerop i) (throw 'exit (setq min-i 0)))
  2791. ((< i min-i) (setq min-i i))))
  2792. (forward-line))))
  2793. ;; Then indent each line so that a line indented to
  2794. ;; MIN-I becomes indented to IND. Ignore blank lines
  2795. ;; and inline tasks in the process.
  2796. (let ((delta (- ind min-i)))
  2797. (while (< (point) end)
  2798. (unless (or (looking-at "^[ \t]*$")
  2799. (looking-at org-outline-regexp-bol))
  2800. (indent-line-to (+ (org-current-text-indentation) delta)))
  2801. (forward-line))))))
  2802. (skip-blanks
  2803. (lambda (pos)
  2804. ;; Return beginning of first non-blank line, starting from
  2805. ;; line at POS.
  2806. (save-excursion
  2807. (goto-char pos)
  2808. (skip-chars-forward " \r\t\n")
  2809. (line-beginning-position))))
  2810. beg end)
  2811. ;; Determine boundaries of changes.
  2812. (if (org-region-active-p)
  2813. (setq beg (funcall skip-blanks (region-beginning))
  2814. end (copy-marker (region-end)))
  2815. (setq beg (line-beginning-position)
  2816. end (copy-marker (line-end-position))))
  2817. ;; Depending on the starting line, choose an action on the text
  2818. ;; between BEG and END.
  2819. (org-with-limited-levels
  2820. (save-excursion
  2821. (goto-char beg)
  2822. (cond
  2823. ;; Case 1. Start at an item: de-itemize. Note that it only
  2824. ;; happens when a region is active: `org-ctrl-c-minus'
  2825. ;; would call `org-cycle-list-bullet' otherwise.
  2826. ((org-at-item-p)
  2827. (while (< (point) end)
  2828. (when (org-at-item-p)
  2829. (skip-chars-forward " \t")
  2830. (delete-region (point) (match-end 0)))
  2831. (forward-line)))
  2832. ;; Case 2. Start at an heading: convert to items.
  2833. ((org-at-heading-p)
  2834. ;; Remove metadata
  2835. (let (org-loop-over-headlines-in-active-region)
  2836. (org-list--delete-metadata))
  2837. (let* ((bul (org-list-bullet-string "-"))
  2838. (bul-len (length bul))
  2839. ;; Indentation of the first heading. It should be
  2840. ;; relative to the indentation of its parent, if any.
  2841. (start-ind (save-excursion
  2842. (cond
  2843. ((not org-adapt-indentation) 0)
  2844. ((not (outline-previous-heading)) 0)
  2845. (t (length (match-string 0))))))
  2846. ;; Level of first heading. Further headings will be
  2847. ;; compared to it to determine hierarchy in the list.
  2848. (ref-level (org-reduced-level (org-outline-level))))
  2849. (while (< (point) end)
  2850. (let* ((level (org-reduced-level (org-outline-level)))
  2851. (delta (max 0 (- level ref-level)))
  2852. (todo-state (org-get-todo-state)))
  2853. ;; If current headline is less indented than the first
  2854. ;; one, set it as reference, in order to preserve
  2855. ;; subtrees.
  2856. (when (< level ref-level) (setq ref-level level))
  2857. ;; Remove metadata
  2858. (let (org-loop-over-headlines-in-active-region)
  2859. (org-list--delete-metadata))
  2860. ;; Remove stars and TODO keyword.
  2861. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  2862. (delete-region (point) (or (match-beginning 3)
  2863. (line-end-position)))
  2864. (insert bul)
  2865. (indent-line-to (+ start-ind (* delta bul-len)))
  2866. ;; Turn TODO keyword into a check box.
  2867. (when todo-state
  2868. (let* ((struct (org-list-struct))
  2869. (old (copy-tree struct)))
  2870. (org-list-set-checkbox
  2871. (line-beginning-position)
  2872. struct
  2873. (if (member todo-state org-done-keywords)
  2874. "[X]"
  2875. "[ ]"))
  2876. (org-list-write-struct struct
  2877. (org-list-parents-alist struct)
  2878. old)))
  2879. ;; Ensure all text down to END (or SECTION-END) belongs
  2880. ;; to the newly created item.
  2881. (let ((section-end (save-excursion
  2882. (or (outline-next-heading) (point)))))
  2883. (forward-line)
  2884. (funcall shift-text
  2885. (+ start-ind (* (1+ delta) bul-len))
  2886. (min end section-end)))))))
  2887. ;; Case 3. Normal line with ARG: make the first line of region
  2888. ;; an item, and shift indentation of others lines to
  2889. ;; set them as item's body.
  2890. (arg (let* ((bul (org-list-bullet-string "-"))
  2891. (bul-len (length bul))
  2892. (ref-ind (org-current-text-indentation)))
  2893. (skip-chars-forward " \t")
  2894. (insert bul)
  2895. (forward-line)
  2896. (while (< (point) end)
  2897. ;; Ensure that lines less indented than first one
  2898. ;; still get included in item body.
  2899. (funcall shift-text
  2900. (+ ref-ind bul-len)
  2901. (min end (save-excursion (or (outline-next-heading)
  2902. (point)))))
  2903. (forward-line))))
  2904. ;; Case 4. Normal line without ARG: turn each non-item line
  2905. ;; into an item.
  2906. (t
  2907. (while (< (point) end)
  2908. (unless (or (org-at-heading-p) (org-at-item-p))
  2909. (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
  2910. (replace-match
  2911. (concat "\\1" (org-list-bullet-string "-") "\\2"))))
  2912. (forward-line))))))))
  2913. ;;; Send and receive lists
  2914. (defun org-list-to-lisp (&optional delete)
  2915. "Parse the list at point and maybe DELETE it.
  2916. Return a list whose car is a symbol of list type, among
  2917. `ordered', `unordered' and `descriptive'. Then, each item is
  2918. a list of strings and other sub-lists.
  2919. For example, the following list:
  2920. 1. first item
  2921. + sub-item one
  2922. + [X] sub-item two
  2923. more text in first item
  2924. 2. [@3] last item
  2925. is parsed as
  2926. (ordered
  2927. (\"first item\"
  2928. (unordered
  2929. (\"sub-item one\")
  2930. (\"[X] sub-item two\"))
  2931. \"more text in first item\")
  2932. (\"[@3] last item\"))
  2933. Point is left at list's end."
  2934. (letrec ((struct (org-list-struct))
  2935. (prevs (org-list-prevs-alist struct))
  2936. (parents (org-list-parents-alist struct))
  2937. (top (org-list-get-top-point struct))
  2938. (bottom (org-list-get-bottom-point struct))
  2939. (trim
  2940. (lambda (text)
  2941. ;; Remove indentation and final newline from TEXT.
  2942. (org-remove-indentation
  2943. (if (string-match-p "\n\\'" text)
  2944. (substring text 0 -1)
  2945. text))))
  2946. (parse-sublist
  2947. (lambda (e)
  2948. ;; Return a list whose car is list type and cdr a list
  2949. ;; of items' body.
  2950. (cons (org-list-get-list-type (car e) struct prevs)
  2951. (mapcar parse-item e))))
  2952. (parse-item
  2953. (lambda (e)
  2954. ;; Return a list containing counter of item, if any,
  2955. ;; text and any sublist inside it.
  2956. (let* ((end (org-list-get-item-end e struct))
  2957. (children (org-list-get-children e struct parents))
  2958. (body
  2959. (save-excursion
  2960. (goto-char e)
  2961. (looking-at "[ \t]*\\S-+[ \t]*")
  2962. (list
  2963. (funcall
  2964. trim
  2965. (concat
  2966. (make-string (string-width (match-string 0)) ?\s)
  2967. (buffer-substring-no-properties
  2968. (match-end 0) (or (car children) end))))))))
  2969. (while children
  2970. (let* ((child (car children))
  2971. (sub (org-list-get-all-items child struct prevs))
  2972. (last-in-sub (car (last sub))))
  2973. (push (funcall parse-sublist sub) body)
  2974. ;; Remove whole sub-list from children.
  2975. (setq children (cdr (memq last-in-sub children)))
  2976. ;; There is a chunk of text belonging to the item
  2977. ;; if last child doesn't end where next child
  2978. ;; starts or where item ends.
  2979. (let ((sub-end (org-list-get-item-end last-in-sub struct))
  2980. (next (or (car children) end)))
  2981. (when (/= sub-end next)
  2982. (push (funcall
  2983. trim
  2984. (buffer-substring-no-properties sub-end next))
  2985. body)))))
  2986. (nreverse body)))))
  2987. ;; Store output, take care of cursor position and deletion of
  2988. ;; list, then return output.
  2989. (prog1 (funcall parse-sublist (org-list-get-all-items top struct prevs))
  2990. (goto-char top)
  2991. (when delete
  2992. (delete-region top bottom)
  2993. (when (and (not (looking-at "[ \t]*$")) (looking-at org-list-end-re))
  2994. (replace-match ""))))))
  2995. (defun org-list-make-subtree ()
  2996. "Convert the plain list at point into a subtree."
  2997. (interactive)
  2998. (let ((item (org-in-item-p)))
  2999. (unless item (error "Not in a list"))
  3000. (goto-char item)
  3001. (let ((level (pcase (org-current-level)
  3002. (`nil 1)
  3003. (l (1+ (org-reduced-level l)))))
  3004. (list (save-excursion (org-list-to-lisp t))))
  3005. (insert (org-list-to-subtree list level) "\n"))))
  3006. (defun org-list-to-generic (list params)
  3007. "Convert a LIST parsed through `org-list-to-lisp' to a custom format.
  3008. LIST is a list as returned by `org-list-to-lisp', which see.
  3009. PARAMS is a property list of parameters used to tweak the output
  3010. format.
  3011. Valid parameters are:
  3012. :backend, :raw
  3013. Export back-end used as a basis to transcode elements of the
  3014. list, when no specific parameter applies to it. It is also
  3015. used to translate its contents. You can prevent this by
  3016. setting :raw property to a non-nil value.
  3017. :splice
  3018. When non-nil, only export the contents of the top most plain
  3019. list, effectively ignoring its opening and closing lines.
  3020. :ustart, :uend
  3021. Strings to start and end an unordered list. They can also be
  3022. set to a function returning a string or nil, which will be
  3023. called with the depth of the list, counting from 1.
  3024. :ostart, :oend
  3025. Strings to start and end an ordered list. They can also be set
  3026. to a function returning a string or nil, which will be called
  3027. with the depth of the list, counting from 1.
  3028. :dstart, :dend
  3029. Strings to start and end a descriptive list. They can also be
  3030. set to a function returning a string or nil, which will be
  3031. called with the depth of the list, counting from 1.
  3032. :dtstart, :dtend, :ddstart, :ddend
  3033. Strings to start and end a descriptive term.
  3034. :istart, :iend
  3035. Strings to start or end a list item, and to start a list item
  3036. with a counter. They can also be set to a function returning
  3037. a string or nil, which will be called with two arguments: the
  3038. type of list and the depth of the item, counting from 1.
  3039. :icount
  3040. Strings to start a list item with a counter. It can also be
  3041. set to a function returning a string or nil, which will be
  3042. called with three arguments: the type of list, the depth of the
  3043. item, counting from 1, and the counter. Its value, when
  3044. non-nil, has precedence over `:istart'.
  3045. :isep
  3046. String used to separate items. It can also be set to
  3047. a function returning a string or nil, which will be called with
  3048. two arguments: the type of list and the depth of the item,
  3049. counting from 1. It always start on a new line.
  3050. :ifmt
  3051. Function to be applied to the contents of every item. It is
  3052. called with two arguments: the type of list and the contents.
  3053. :cbon, :cboff, :cbtrans
  3054. String to insert, respectively, an un-checked check-box,
  3055. a checked check-box and a check-box in transitional state."
  3056. (require 'ox)
  3057. (let* ((backend (plist-get params :backend))
  3058. (custom-backend
  3059. (org-export-create-backend
  3060. :parent (or backend 'org)
  3061. :transcoders
  3062. `((plain-list . ,(org-list--to-generic-plain-list params))
  3063. (item . ,(org-list--to-generic-item params))
  3064. (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
  3065. data info)
  3066. ;; Write LIST back into Org syntax and parse it.
  3067. (with-temp-buffer
  3068. (let ((org-inhibit-startup t)) (org-mode))
  3069. (letrec ((insert-list
  3070. (lambda (l)
  3071. (dolist (i (cdr l))
  3072. (funcall insert-item i (car l)))))
  3073. (insert-item
  3074. (lambda (i type)
  3075. (let ((start (point)))
  3076. (insert (if (eq type 'ordered) "1. " "- "))
  3077. (dolist (e i)
  3078. (if (consp e) (funcall insert-list e)
  3079. (insert e)
  3080. (insert "\n")))
  3081. (beginning-of-line)
  3082. (save-excursion
  3083. (let ((ind (if (eq type 'ordered) 3 2)))
  3084. (while (> (point) start)
  3085. (unless (looking-at-p "[ \t]*$")
  3086. (indent-to ind))
  3087. (forward-line -1))))))))
  3088. (funcall insert-list list))
  3089. (setf data
  3090. (org-element-map (org-element-parse-buffer) 'plain-list
  3091. #'identity nil t))
  3092. (setf info (org-export-get-environment backend nil params)))
  3093. (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
  3094. (user-error "Unknown :backend value"))
  3095. (unless backend (require 'ox-org))
  3096. ;; When ':raw' property has a non-nil value, turn all objects back
  3097. ;; into Org syntax.
  3098. (when (and backend (plist-get params :raw))
  3099. (org-element-map data org-element-all-objects
  3100. (lambda (object)
  3101. (org-element-set-element
  3102. object (org-element-interpret-data object)))))
  3103. ;; We use a low-level mechanism to export DATA so as to skip all
  3104. ;; usual pre-processing and post-processing, i.e., hooks, filters,
  3105. ;; Babel code evaluation, include keywords and macro expansion,
  3106. ;; and filters.
  3107. (let ((output (org-export-data-with-backend data custom-backend info)))
  3108. ;; Remove final newline.
  3109. (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
  3110. (defun org-list--depth (element)
  3111. "Return the level of ELEMENT within current plain list.
  3112. ELEMENT is either an item or a plain list."
  3113. (cl-count-if (lambda (ancestor) (eq (org-element-type ancestor) 'plain-list))
  3114. (org-element-lineage element nil t)))
  3115. (defun org-list--trailing-newlines (string)
  3116. "Return the number of trailing newlines in STRING."
  3117. (with-temp-buffer
  3118. (insert string)
  3119. (skip-chars-backward " \t\n")
  3120. (count-lines (line-beginning-position 2) (point-max))))
  3121. (defun org-list--generic-eval (value &rest args)
  3122. "Evaluate VALUE according to its type.
  3123. VALUE is either nil, a string or a function. In the latter case,
  3124. it is called with arguments ARGS."
  3125. (cond ((null value) nil)
  3126. ((stringp value) value)
  3127. ((functionp value) (apply value args))
  3128. (t (error "Wrong value: %s" value))))
  3129. (defun org-list--to-generic-plain-list (params)
  3130. "Return a transcoder for `plain-list' elements.
  3131. PARAMS is a plist used to tweak the behavior of the transcoder."
  3132. (let ((ustart (plist-get params :ustart))
  3133. (uend (plist-get params :uend))
  3134. (ostart (plist-get params :ostart))
  3135. (oend (plist-get params :oend))
  3136. (dstart (plist-get params :dstart))
  3137. (dend (plist-get params :dend))
  3138. (splice (plist-get params :splice))
  3139. (backend (plist-get params :backend)))
  3140. (lambda (plain-list contents info)
  3141. (let* ((type (org-element-property :type plain-list))
  3142. (depth (org-list--depth plain-list))
  3143. (start (and (not splice)
  3144. (org-list--generic-eval
  3145. (pcase type
  3146. (`ordered ostart)
  3147. (`unordered ustart)
  3148. (_ dstart))
  3149. depth)))
  3150. (end (and (not splice)
  3151. (org-list--generic-eval
  3152. (pcase type
  3153. (`ordered oend)
  3154. (`unordered uend)
  3155. (_ dend))
  3156. depth))))
  3157. ;; Make sure trailing newlines in END appear in the output by
  3158. ;; setting `:post-blank' property to their number.
  3159. (when end
  3160. (org-element-put-property
  3161. plain-list :post-blank (org-list--trailing-newlines end)))
  3162. ;; Build output.
  3163. (concat (and start (concat start "\n"))
  3164. (if (or start end splice (not backend))
  3165. contents
  3166. (org-export-with-backend backend plain-list contents info))
  3167. end)))))
  3168. (defun org-list--to-generic-item (params)
  3169. "Return a transcoder for `item' elements.
  3170. PARAMS is a plist used to tweak the behavior of the transcoder."
  3171. (let ((backend (plist-get params :backend))
  3172. (istart (plist-get params :istart))
  3173. (iend (plist-get params :iend))
  3174. (isep (plist-get params :isep))
  3175. (icount (plist-get params :icount))
  3176. (ifmt (plist-get params :ifmt))
  3177. (cboff (plist-get params :cboff))
  3178. (cbon (plist-get params :cbon))
  3179. (cbtrans (plist-get params :cbtrans))
  3180. (dtstart (plist-get params :dtstart))
  3181. (dtend (plist-get params :dtend))
  3182. (ddstart (plist-get params :ddstart))
  3183. (ddend (plist-get params :ddend)))
  3184. (lambda (item contents info)
  3185. (let* ((type
  3186. (org-element-property :type (org-element-property :parent item)))
  3187. (tag (org-element-property :tag item))
  3188. (depth (org-list--depth item))
  3189. (separator (and (org-export-get-next-element item info)
  3190. (org-list--generic-eval isep type depth)))
  3191. (closing (pcase (org-list--generic-eval iend type depth)
  3192. ((or `nil "") "\n")
  3193. ((and (guard separator) s)
  3194. (if (equal (substring s -1) "\n") s (concat s "\n")))
  3195. (s s))))
  3196. ;; When a closing line or a separator is provided, make sure
  3197. ;; its trailing newlines are taken into account when building
  3198. ;; output. This is done by setting `:post-blank' property to
  3199. ;; the number of such lines in the last line to be added.
  3200. (let ((last-string (or separator closing)))
  3201. (when last-string
  3202. (org-element-put-property
  3203. item
  3204. :post-blank
  3205. (max (1- (org-list--trailing-newlines last-string)) 0))))
  3206. ;; Build output.
  3207. (concat
  3208. (let ((c (org-element-property :counter item)))
  3209. (if (and c icount) (org-list--generic-eval icount type depth c)
  3210. (org-list--generic-eval istart type depth)))
  3211. (let ((body
  3212. (if (or istart iend icount ifmt cbon cboff cbtrans (not backend)
  3213. (and (eq type 'descriptive)
  3214. (or dtstart dtend ddstart ddend)))
  3215. (concat
  3216. (pcase (org-element-property :checkbox item)
  3217. (`on cbon)
  3218. (`off cboff)
  3219. (`trans cbtrans))
  3220. (and tag
  3221. (concat dtstart
  3222. (if backend
  3223. (org-export-data-with-backend
  3224. tag backend info)
  3225. (org-element-interpret-data tag))
  3226. dtend))
  3227. (and tag ddstart)
  3228. (let ((contents
  3229. (if (= (length contents) 0) ""
  3230. (substring contents 0 -1))))
  3231. (if ifmt (org-list--generic-eval ifmt type contents)
  3232. contents))
  3233. (and tag ddend))
  3234. (org-export-with-backend backend item contents info))))
  3235. ;; Remove final newline.
  3236. (if (equal body "") ""
  3237. (substring (org-element-normalize-string body) 0 -1)))
  3238. closing
  3239. separator)))))
  3240. (defun org-list-to-latex (list &optional params)
  3241. "Convert LIST into a LaTeX list.
  3242. LIST is a parsed plain list, as returned by `org-list-to-lisp'.
  3243. PARAMS is a property list with overruling parameters for
  3244. `org-list-to-generic'. Return converted list as a string."
  3245. (require 'ox-latex)
  3246. (org-list-to-generic list (org-combine-plists '(:backend latex) params)))
  3247. (defun org-list-to-html (list &optional params)
  3248. "Convert LIST into a HTML list.
  3249. LIST is a parsed plain list, as returned by `org-list-to-lisp'.
  3250. PARAMS is a property list with overruling parameters for
  3251. `org-list-to-generic'. Return converted list as a string."
  3252. (require 'ox-html)
  3253. (org-list-to-generic list (org-combine-plists '(:backend html) params)))
  3254. (defun org-list-to-texinfo (list &optional params)
  3255. "Convert LIST into a Texinfo list.
  3256. LIST is a parsed plain list, as returned by `org-list-to-lisp'.
  3257. PARAMS is a property list with overruling parameters for
  3258. `org-list-to-generic'. Return converted list as a string."
  3259. (require 'ox-texinfo)
  3260. (org-list-to-generic list (org-combine-plists '(:backend texinfo) params)))
  3261. (defun org-list-to-org (list &optional params)
  3262. "Convert LIST into an Org plain list.
  3263. LIST is as returned by `org-list-parse-list'. PARAMS is a property list
  3264. with overruling parameters for `org-list-to-generic'."
  3265. (let* ((make-item
  3266. (lambda (type _depth &optional c)
  3267. (concat (if (eq type 'ordered) "1. " "- ")
  3268. (and c (format "[@%d] " c)))))
  3269. (defaults
  3270. (list :istart make-item
  3271. :icount make-item
  3272. :ifmt (lambda (_type contents)
  3273. (replace-regexp-in-string "\n" "\n " contents))
  3274. :dtend " :: "
  3275. :cbon "[X] "
  3276. :cboff "[ ] "
  3277. :cbtrans "[-] ")))
  3278. (org-list-to-generic list (org-combine-plists defaults params))))
  3279. (defun org-list-to-subtree (list &optional start-level params)
  3280. "Convert LIST into an Org subtree.
  3281. LIST is as returned by `org-list-to-lisp'. Subtree starts at
  3282. START-LEVEL or level 1 if nil. PARAMS is a property list with
  3283. overruling parameters for `org-list-to-generic'."
  3284. (let* ((blank (pcase (cdr (assq 'heading org-blank-before-new-entry))
  3285. (`t t)
  3286. (`auto (save-excursion
  3287. (org-with-limited-levels (outline-previous-heading))
  3288. (org-previous-line-empty-p)))))
  3289. (level (or start-level 1))
  3290. (make-stars
  3291. (lambda (_type depth &optional _count)
  3292. ;; Return the string for the heading, depending on DEPTH
  3293. ;; of current sub-list.
  3294. (let ((oddeven-level (+ level (1- depth))))
  3295. (concat (make-string (if org-odd-levels-only
  3296. (1- (* 2 oddeven-level))
  3297. oddeven-level)
  3298. ?*)
  3299. " ")))))
  3300. (org-list-to-generic
  3301. list
  3302. (org-combine-plists
  3303. (list :splice t
  3304. :istart make-stars
  3305. :icount make-stars
  3306. :dtstart " " :dtend " "
  3307. :isep (if blank "\n\n" "\n")
  3308. :cbon "DONE " :cboff "TODO " :cbtrans "TODO ")
  3309. params))))
  3310. (provide 'org-list)
  3311. ;; Local variables:
  3312. ;; generated-autoload-file: "org-loaddefs.el"
  3313. ;; End:
  3314. ;;; org-list.el ends here