org-list.el 130 KB

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