org-clock.el 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000
  1. ;;; org-clock.el --- The time clocking code for Org mode -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; Homepage: https://orgmode.org
  6. ;;
  7. ;; This file is part of GNU Emacs.
  8. ;;
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  20. ;;
  21. ;;; Commentary:
  22. ;; This file contains the time clocking code for Org mode
  23. ;;; Code:
  24. (require 'cl-lib)
  25. (require 'org)
  26. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  27. (declare-function notifications-notify "notifications" (&rest params))
  28. (declare-function org-element-property "org-element" (property element))
  29. (declare-function org-element-type "org-element" (element))
  30. (declare-function org-table-goto-line "org-table" (n))
  31. (defvar org-frame-title-format-backup frame-title-format)
  32. (defvar org-time-stamp-formats)
  33. (defgroup org-clock nil
  34. "Options concerning clocking working time in Org mode."
  35. :tag "Org Clock"
  36. :group 'org-progress)
  37. (defcustom org-clock-into-drawer t
  38. "Non-nil when clocking info should be wrapped into a drawer.
  39. When non-nil, clocking info will be inserted into the same drawer
  40. as log notes (see variable `org-log-into-drawer'), if it exists,
  41. or \"LOGBOOK\" otherwise. If necessary, the drawer will be
  42. created.
  43. When an integer, the drawer is created only when the number of
  44. clocking entries in an item reaches or exceeds this value.
  45. When a string, it becomes the name of the drawer, ignoring the
  46. log notes drawer altogether.
  47. Do not check directly this variable in a Lisp program. Call
  48. function `org-clock-into-drawer' instead."
  49. :group 'org-todo
  50. :group 'org-clock
  51. :version "26.1"
  52. :package-version '(Org . "8.3")
  53. :type '(choice
  54. (const :tag "Always" t)
  55. (const :tag "Only when drawer exists" nil)
  56. (integer :tag "When at least N clock entries")
  57. (const :tag "Into LOGBOOK drawer" "LOGBOOK")
  58. (string :tag "Into Drawer named...")))
  59. (defun org-clock-into-drawer ()
  60. "Value of `org-clock-into-drawer'. but let properties overrule.
  61. If the current entry has or inherits a CLOCK_INTO_DRAWER
  62. property, it will be used instead of the default value.
  63. Return value is either a string, an integer, or nil."
  64. (let ((p (org-entry-get nil "CLOCK_INTO_DRAWER" 'inherit t)))
  65. (cond ((equal p "nil") nil)
  66. ((equal p "t") (or (org-log-into-drawer) "LOGBOOK"))
  67. ((org-string-nw-p p)
  68. (if (string-match-p "\\`[0-9]+\\'" p) (string-to-number p) p))
  69. ((org-string-nw-p org-clock-into-drawer))
  70. ((integerp org-clock-into-drawer) org-clock-into-drawer)
  71. ((not org-clock-into-drawer) nil)
  72. ((org-log-into-drawer))
  73. (t "LOGBOOK"))))
  74. (defcustom org-clock-out-when-done t
  75. "When non-nil, clock will be stopped when the clocked entry is marked DONE.
  76. \\<org-mode-map>\
  77. DONE here means any DONE-like state.
  78. A nil value means clock will keep running until stopped explicitly with
  79. `\\[org-clock-out]', or until the clock is started in a different item.
  80. Instead of t, this can also be a list of TODO states that should trigger
  81. clocking out."
  82. :group 'org-clock
  83. :type '(choice
  84. (const :tag "No" nil)
  85. (const :tag "Yes, when done" t)
  86. (repeat :tag "State list"
  87. (string :tag "TODO keyword"))))
  88. (defcustom org-clock-rounding-minutes 0
  89. "Rounding minutes when clocking in or out.
  90. The default value is 0 so that no rounding is done.
  91. When set to a non-integer value, use the car of
  92. `org-time-stamp-rounding-minutes', like for setting a time-stamp.
  93. E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47
  94. and you clock in: then the clock starts at 14:45. If you clock
  95. out within the next 5 minutes, the clock line will be removed;
  96. if you clock out 8 minutes after your clocked in, the clock
  97. out time will be 14:50."
  98. :group 'org-clock
  99. :version "24.4"
  100. :package-version '(Org . "8.0")
  101. :type '(choice
  102. (integer :tag "Minutes (0 for no rounding)")
  103. (symbol :tag "Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp)))
  104. (defcustom org-clock-out-remove-zero-time-clocks nil
  105. "Non-nil means remove the clock line when the resulting time is zero."
  106. :group 'org-clock
  107. :type 'boolean)
  108. (defcustom org-clock-in-switch-to-state nil
  109. "Set task to a special todo state while clocking it.
  110. The value should be the state to which the entry should be
  111. switched. If the value is a function, it must take one
  112. parameter (the current TODO state of the item) and return the
  113. state to switch it to."
  114. :group 'org-clock
  115. :group 'org-todo
  116. :type '(choice
  117. (const :tag "Don't force a state" nil)
  118. (string :tag "State")
  119. (symbol :tag "Function")))
  120. (defcustom org-clock-out-switch-to-state nil
  121. "Set task to a special todo state after clocking out.
  122. The value should be the state to which the entry should be
  123. switched. If the value is a function, it must take one
  124. parameter (the current TODO state of the item) and return the
  125. state to switch it to."
  126. :group 'org-clock
  127. :group 'org-todo
  128. :type '(choice
  129. (const :tag "Don't force a state" nil)
  130. (string :tag "State")
  131. (symbol :tag "Function")))
  132. (defcustom org-clock-history-length 5
  133. "Number of clock tasks to remember in history.
  134. Clocking in using history works best if this is at most 35, in
  135. which case all digits and capital letters are used up by the
  136. *Clock Task Select* buffer."
  137. :group 'org-clock
  138. :type 'integer)
  139. (defcustom org-clock-goto-may-find-recent-task t
  140. "Non-nil means `org-clock-goto' can go to recent task if no active clock."
  141. :group 'org-clock
  142. :type 'boolean)
  143. (defcustom org-clock-heading-function nil
  144. "When non-nil, should be a function to create `org-clock-heading'.
  145. This is the string shown in the mode line when a clock is running.
  146. The function is called with point at the beginning of the headline."
  147. :group 'org-clock
  148. :type '(choice (const nil) (function)))
  149. (defcustom org-clock-string-limit 0
  150. "Maximum length of clock strings in the mode line. 0 means no limit."
  151. :group 'org-clock
  152. :type 'integer)
  153. (defcustom org-clock-in-resume nil
  154. "If non-nil, resume clock when clocking into task with open clock.
  155. When clocking into a task with a clock entry which has not been closed,
  156. the clock can be resumed from that point."
  157. :group 'org-clock
  158. :type 'boolean)
  159. (defcustom org-clock-persist nil
  160. "When non-nil, save the running clock when Emacs is closed.
  161. The clock is resumed when Emacs restarts.
  162. When this is t, both the running clock, and the entire clock
  163. history are saved. When this is the symbol `clock', only the
  164. running clock is saved. When this is the symbol `history', only
  165. the clock history is saved.
  166. When Emacs restarts with saved clock information, the file containing
  167. the running clock as well as all files mentioned in the clock history
  168. will be visited.
  169. All this depends on running `org-clock-persistence-insinuate' in your
  170. Emacs initialization file."
  171. :group 'org-clock
  172. :type '(choice
  173. (const :tag "Just the running clock" clock)
  174. (const :tag "Just the history" history)
  175. (const :tag "Clock and history" t)
  176. (const :tag "No persistence" nil)))
  177. (defcustom org-clock-persist-file (convert-standard-filename
  178. (concat user-emacs-directory "org-clock-save.el"))
  179. "File to save clock data to."
  180. :group 'org-clock
  181. :type 'string)
  182. (defcustom org-clock-persist-query-save nil
  183. "When non-nil, ask before saving the current clock on exit."
  184. :group 'org-clock
  185. :type 'boolean)
  186. (defcustom org-clock-persist-query-resume t
  187. "When non-nil, ask before resuming any stored clock during load."
  188. :group 'org-clock
  189. :type 'boolean)
  190. (defcustom org-clock-sound nil
  191. "Sound to use for notifications.
  192. Possible values are:
  193. nil No sound played
  194. t Standard Emacs beep
  195. file name Play this sound file, fall back to beep"
  196. :group 'org-clock
  197. :type '(choice
  198. (const :tag "No sound" nil)
  199. (const :tag "Standard beep" t)
  200. (file :tag "Play sound file")))
  201. (defcustom org-clock-mode-line-total 'auto
  202. "Default setting for the time included for the mode line clock.
  203. This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
  204. Allowed values are:
  205. current Only the time in the current instance of the clock
  206. today All time clocked into this task today
  207. repeat All time clocked into this task since last repeat
  208. all All time ever recorded for this task
  209. auto Automatically, either `all', or `repeat' for repeating tasks"
  210. :group 'org-clock
  211. :type '(choice
  212. (const :tag "Current clock" current)
  213. (const :tag "Today's task time" today)
  214. (const :tag "Since last repeat" repeat)
  215. (const :tag "All task time" all)
  216. (const :tag "Automatically, `all' or since `repeat'" auto)))
  217. (defvaralias 'org-task-overrun-text 'org-clock-task-overrun-text)
  218. (defcustom org-clock-task-overrun-text nil
  219. "Extra mode line text to indicate that the clock is overrun.
  220. The can be nil to indicate that instead of adding text, the clock time
  221. should get a different face (`org-mode-line-clock-overrun').
  222. When this is a string, it is prepended to the clock string as an indication,
  223. also using the face `org-mode-line-clock-overrun'."
  224. :group 'org-clock
  225. :version "24.1"
  226. :type '(choice
  227. (const :tag "Just mark the time string" nil)
  228. (string :tag "Text to prepend")))
  229. (defcustom org-show-notification-handler nil
  230. "Function or program to send notification with.
  231. The function or program will be called with the notification
  232. string as argument."
  233. :group 'org-clock
  234. :type '(choice
  235. (const nil)
  236. (string :tag "Program")
  237. (function :tag "Function")))
  238. (defgroup org-clocktable nil
  239. "Options concerning the clock table in Org mode."
  240. :tag "Org Clock Table"
  241. :group 'org-clock)
  242. (defcustom org-clocktable-defaults
  243. (list
  244. :maxlevel 2
  245. :lang (or (bound-and-true-p org-export-default-language) "en")
  246. :scope 'file
  247. :block nil
  248. :wstart 1
  249. :mstart 1
  250. :tstart nil
  251. :tend nil
  252. :step nil
  253. :stepskip0 nil
  254. :fileskip0 nil
  255. :tags nil
  256. :match nil
  257. :emphasize nil
  258. :link nil
  259. :narrow '40!
  260. :indent t
  261. :formula nil
  262. :timestamp nil
  263. :level nil
  264. :tcolumns nil
  265. :formatter nil)
  266. "Default properties for clock tables."
  267. :group 'org-clock
  268. :version "24.1"
  269. :type 'plist)
  270. (defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
  271. "Function to turn clocking data into a table.
  272. For more information, see `org-clocktable-write-default'."
  273. :group 'org-clocktable
  274. :version "24.1"
  275. :type 'function)
  276. ;; FIXME: translate es and nl last string "Clock summary at"
  277. (defcustom org-clock-clocktable-language-setup
  278. '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
  279. ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
  280. ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à")
  281. ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at")
  282. ("de" "Datei" "E" "Zeitstempel" "Kopfzeile" "Dauer" "GESAMT"
  283. "Gesamtdauer" "Dateizeit" "Erstellt am"))
  284. "Terms used in clocktable, translated to different languages."
  285. :group 'org-clocktable
  286. :version "24.1"
  287. :type 'alist)
  288. (defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
  289. "Default properties for new clocktables.
  290. These will be inserted into the BEGIN line, to make it easy for users to
  291. play with them."
  292. :group 'org-clocktable
  293. :type 'plist)
  294. (defcustom org-clock-idle-time nil
  295. "When non-nil, resolve open clocks if the user is idle more than X minutes."
  296. :group 'org-clock
  297. :type '(choice
  298. (const :tag "Never" nil)
  299. (integer :tag "After N minutes")))
  300. (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
  301. "When to automatically resolve open clocks found in Org buffers."
  302. :group 'org-clock
  303. :type '(choice
  304. (const :tag "Never" nil)
  305. (const :tag "Always" t)
  306. (const :tag "When no clock is running" when-no-clock-is-running)))
  307. (defcustom org-clock-report-include-clocking-task nil
  308. "When non-nil, include the current clocking task time in clock reports."
  309. :group 'org-clock
  310. :version "24.1"
  311. :type 'boolean)
  312. (defcustom org-clock-resolve-expert nil
  313. "Non-nil means do not show the splash buffer with the clock resolver."
  314. :group 'org-clock
  315. :version "24.1"
  316. :type 'boolean)
  317. (defcustom org-clock-continuously nil
  318. "Non-nil means to start clocking from the last clock-out time, if any."
  319. :type 'boolean
  320. :version "24.1"
  321. :group 'org-clock)
  322. (defcustom org-clock-total-time-cell-format "*%s*"
  323. "Format string for the total time cells."
  324. :group 'org-clock
  325. :version "24.1"
  326. :type 'string)
  327. (defcustom org-clock-file-time-cell-format "*%s*"
  328. "Format string for the file time cells."
  329. :group 'org-clock
  330. :version "24.1"
  331. :type 'string)
  332. (defcustom org-clock-clocked-in-display 'mode-line
  333. "When clocked in for a task, Org can display the current
  334. task and accumulated time in the mode line and/or frame title.
  335. Allowed values are:
  336. both displays in both mode line and frame title
  337. mode-line displays only in mode line (default)
  338. frame-title displays only in frame title
  339. nil current clock is not displayed"
  340. :group 'org-clock
  341. :type '(choice
  342. (const :tag "Mode line" mode-line)
  343. (const :tag "Frame title" frame-title)
  344. (const :tag "Both" both)
  345. (const :tag "None" nil)))
  346. (defcustom org-clock-frame-title-format '(t org-mode-line-string)
  347. "The value for `frame-title-format' when clocking in.
  348. When `org-clock-clocked-in-display' is set to `frame-title'
  349. or `both', clocking in will replace `frame-title-format' with
  350. this value. Clocking out will restore `frame-title-format'.
  351. `org-frame-title-string' is a format string using the same
  352. specifications than `frame-title-format', which see."
  353. :version "24.1"
  354. :group 'org-clock
  355. :type 'sexp)
  356. (defcustom org-clock-x11idle-program-name "x11idle"
  357. "Name of the program which prints X11 idle time in milliseconds.
  358. You can find x11idle.c in the contrib/scripts directory of the
  359. Org git distribution. Or, you can do:
  360. sudo apt-get install xprintidle
  361. if you are using Debian."
  362. :group 'org-clock
  363. :version "24.4"
  364. :package-version '(Org . "8.0")
  365. :type 'string)
  366. (defcustom org-clock-goto-before-context 2
  367. "Number of lines of context to display before currently clocked-in entry.
  368. This applies when using `org-clock-goto'."
  369. :group 'org-clock
  370. :type 'integer)
  371. (defcustom org-clock-display-default-range 'thisyear
  372. "Default range when displaying clocks with `org-clock-display'.
  373. Valid values are: `today', `yesterday', `thisweek', `lastweek',
  374. `thismonth', `lastmonth', `thisyear', `lastyear' and `untilnow'."
  375. :group 'org-clock
  376. :type '(choice (const today)
  377. (const yesterday)
  378. (const thisweek)
  379. (const lastweek)
  380. (const thismonth)
  381. (const lastmonth)
  382. (const thisyear)
  383. (const lastyear)
  384. (const untilnow)
  385. (const :tag "Select range interactively" interactive))
  386. :safe #'symbolp)
  387. (defvar org-clock-in-prepare-hook nil
  388. "Hook run when preparing the clock.
  389. This hook is run before anything happens to the task that
  390. you want to clock in. For example, you can use this hook
  391. to add an effort property.")
  392. (defvar org-clock-in-hook nil
  393. "Hook run when starting the clock.")
  394. (defvar org-clock-out-hook nil
  395. "Hook run when stopping the current clock.")
  396. (defvar org-clock-cancel-hook nil
  397. "Hook run when canceling the current clock.")
  398. (defvar org-clock-goto-hook nil
  399. "Hook run when selecting the currently clocked-in entry.")
  400. (defvar org-clock-has-been-used nil
  401. "Has the clock been used during the current Emacs session?")
  402. (defvar org-clock-stored-history nil
  403. "Clock history, populated by `org-clock-load'")
  404. (defvar org-clock-stored-resume-clock nil
  405. "Clock to resume, saved by `org-clock-load'")
  406. ;;; The clock for measuring work time.
  407. (defvar org-mode-line-string "")
  408. (put 'org-mode-line-string 'risky-local-variable t)
  409. (defvar org-clock-mode-line-timer nil)
  410. (defvar org-clock-idle-timer nil)
  411. (defvar org-clock-heading) ; defined in org.el
  412. (defvar org-clock-start-time "")
  413. (defvar org-clock-leftover-time nil
  414. "If non-nil, user canceled a clock; this is when leftover time started.")
  415. (defvar org-clock-effort ""
  416. "Effort estimate of the currently clocking task.")
  417. (defvar org-clock-total-time nil
  418. "Holds total time, spent previously on currently clocked item.
  419. This does not include the time in the currently running clock.")
  420. (defvar org-clock-history nil
  421. "List of marker pointing to recent clocked tasks.")
  422. (defvar org-clock-default-task (make-marker)
  423. "Marker pointing to the default task that should clock time.
  424. The clock can be made to switch to this task after clocking out
  425. of a different task.")
  426. (defvar org-clock-interrupted-task (make-marker)
  427. "Marker pointing to the task that has been interrupted by the current clock.")
  428. (defvar org-clock-mode-line-map (make-sparse-keymap))
  429. (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
  430. (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
  431. (defun org-clock--translate (s language)
  432. "Translate string S into using string LANGUAGE.
  433. Assume S in the English term to translate. Return S as-is if it
  434. cannot be translated."
  435. (or (nth (pcase s
  436. ("File" 1) ("L" 2) ("Timestamp" 3) ("Headline" 4) ("Time" 5)
  437. ("ALL" 6) ("Total time" 7) ("File time" 8) ("Clock summary at" 9))
  438. (assoc-string language org-clock-clocktable-language-setup t))
  439. s))
  440. (defun org-clock--mode-line-heading ()
  441. "Return currently clocked heading, formatted for mode line."
  442. (cond ((functionp org-clock-heading-function)
  443. (funcall org-clock-heading-function))
  444. ((org-before-first-heading-p) "???")
  445. (t (replace-regexp-in-string
  446. org-bracket-link-analytic-regexp "\\5"
  447. (org-no-properties (org-get-heading t t t t))))))
  448. (defun org-clock-menu ()
  449. (interactive)
  450. (popup-menu
  451. '("Clock"
  452. ["Clock out" org-clock-out t]
  453. ["Change effort estimate" org-clock-modify-effort-estimate t]
  454. ["Go to clock entry" org-clock-goto t]
  455. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
  456. (defun org-clock-history-push (&optional pos buffer)
  457. "Push a marker to the clock history."
  458. (setq org-clock-history-length (max 1 org-clock-history-length))
  459. (let ((m (move-marker (make-marker)
  460. (or pos (point)) (org-base-buffer
  461. (or buffer (current-buffer)))))
  462. n l)
  463. (while (setq n (member m org-clock-history))
  464. (move-marker (car n) nil))
  465. (setq org-clock-history
  466. (delq nil
  467. (mapcar (lambda (x) (if (marker-buffer x) x nil))
  468. org-clock-history)))
  469. (when (>= (setq l (length org-clock-history)) org-clock-history-length)
  470. (setq org-clock-history
  471. (nreverse
  472. (nthcdr (- l org-clock-history-length -1)
  473. (nreverse org-clock-history)))))
  474. (push m org-clock-history)))
  475. (defun org-clock-save-markers-for-cut-and-paste (beg end)
  476. "Save relative positions of markers in region."
  477. (org-check-and-save-marker org-clock-marker beg end)
  478. (org-check-and-save-marker org-clock-hd-marker beg end)
  479. (org-check-and-save-marker org-clock-default-task beg end)
  480. (org-check-and-save-marker org-clock-interrupted-task beg end)
  481. (dolist (m org-clock-history)
  482. (org-check-and-save-marker m beg end)))
  483. (defun org-clock-drawer-name ()
  484. "Return clock drawer's name for current entry, or nil."
  485. (let ((drawer (org-clock-into-drawer)))
  486. (cond ((integerp drawer)
  487. (let ((log-drawer (org-log-into-drawer)))
  488. (if (stringp log-drawer) log-drawer "LOGBOOK")))
  489. ((stringp drawer) drawer)
  490. (t nil))))
  491. (defun org-clocking-buffer ()
  492. "Return the clocking buffer if we are currently clocking a task or nil."
  493. (marker-buffer org-clock-marker))
  494. (defun org-clocking-p ()
  495. "Return t when clocking a task."
  496. (not (equal (org-clocking-buffer) nil)))
  497. (defvar org-clock-before-select-task-hook nil
  498. "Hook called in task selection just before prompting the user.")
  499. (defun org-clock-select-task (&optional prompt)
  500. "Select a task that was recently associated with clocking.
  501. Return marker position of the selected task. Raise an error if
  502. there is no recent clock to choose from."
  503. (let (och chl sel-list rpl (i 0) s)
  504. ;; Remove successive dups from the clock history to consider
  505. (dolist (c org-clock-history)
  506. (unless (equal c (car och)) (push c och)))
  507. (setq och (reverse och) chl (length och))
  508. (if (zerop chl)
  509. (user-error "No recent clock")
  510. (save-window-excursion
  511. (org-switch-to-buffer-other-window
  512. (get-buffer-create "*Clock Task Select*"))
  513. (erase-buffer)
  514. (when (marker-buffer org-clock-default-task)
  515. (insert (org-add-props "Default Task\n" nil 'face 'bold))
  516. (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
  517. (push s sel-list))
  518. (when (marker-buffer org-clock-interrupted-task)
  519. (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
  520. (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
  521. (push s sel-list))
  522. (when (org-clocking-p)
  523. (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
  524. (setq s (org-clock-insert-selection-line ?c org-clock-marker))
  525. (push s sel-list))
  526. (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
  527. (dolist (m och)
  528. (when (marker-buffer m)
  529. (setq i (1+ i)
  530. s (org-clock-insert-selection-line
  531. (if (< i 10)
  532. (+ i ?0)
  533. (+ i (- ?A 10))) m))
  534. (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
  535. (push s sel-list)))
  536. (run-hooks 'org-clock-before-select-task-hook)
  537. (goto-char (point-min))
  538. ;; Set min-height relatively to circumvent a possible but in
  539. ;; `fit-window-to-buffer'
  540. (fit-window-to-buffer nil nil (if (< chl 10) chl (+ 5 chl)))
  541. (message (or prompt "Select task for clocking:"))
  542. (setq cursor-type nil rpl (read-char-exclusive))
  543. (kill-buffer)
  544. (cond
  545. ((eq rpl ?q) nil)
  546. ((eq rpl ?x) nil)
  547. ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
  548. (t (user-error "Invalid task choice %c" rpl)))))))
  549. (defun org-clock-insert-selection-line (i marker)
  550. "Insert a line for the clock selection menu.
  551. And return a cons cell with the selection character integer and the marker
  552. pointing to it."
  553. (when (marker-buffer marker)
  554. (let (cat task heading prefix)
  555. (with-current-buffer (org-base-buffer (marker-buffer marker))
  556. (org-with-wide-buffer
  557. (ignore-errors
  558. (goto-char marker)
  559. (setq cat (org-get-category)
  560. heading (org-get-heading 'notags)
  561. prefix (save-excursion
  562. (org-back-to-heading t)
  563. (looking-at org-outline-regexp)
  564. (match-string 0))
  565. task (substring
  566. (org-fontify-like-in-org-mode
  567. (concat prefix heading)
  568. org-odd-levels-only)
  569. (length prefix))))))
  570. (when (and cat task)
  571. (insert (format "[%c] %-12s %s\n" i cat task))
  572. (cons i marker)))))
  573. (defvar org-clock-task-overrun nil
  574. "Internal flag indicating if the clock has overrun the planned time.")
  575. (defvar org-clock-update-period 60
  576. "Number of seconds between mode line clock string updates.")
  577. (defun org-clock-get-clock-string ()
  578. "Form a clock-string, that will be shown in the mode line.
  579. If an effort estimate was defined for the current item, use
  580. 01:30/01:50 format (clocked/estimated).
  581. If not, show simply the clocked time like 01:50."
  582. (let ((clocked-time (org-clock-get-clocked-time)))
  583. (if org-clock-effort
  584. (let* ((effort-in-minutes (org-duration-to-minutes org-clock-effort))
  585. (work-done-str
  586. (propertize (org-duration-from-minutes clocked-time)
  587. 'face
  588. (if (and org-clock-task-overrun
  589. (not org-clock-task-overrun-text))
  590. 'org-mode-line-clock-overrun
  591. 'org-mode-line-clock)))
  592. (effort-str (org-duration-from-minutes effort-in-minutes)))
  593. (format (propertize " [%s/%s] (%s)" 'face 'org-mode-line-clock)
  594. work-done-str effort-str org-clock-heading))
  595. (format (propertize " [%s] (%s)" 'face 'org-mode-line-clock)
  596. (org-duration-from-minutes clocked-time)
  597. org-clock-heading))))
  598. (defun org-clock-get-last-clock-out-time ()
  599. "Get the last clock-out time for the current subtree."
  600. (save-excursion
  601. (let ((end (save-excursion (org-end-of-subtree))))
  602. (when (re-search-forward (concat org-clock-string
  603. ".*\\]--\\(\\[[^]]+\\]\\)") end t)
  604. (org-time-string-to-time (match-string 1))))))
  605. (defun org-clock-update-mode-line (&optional refresh)
  606. "Update mode line with clock information.
  607. When optional argument is non-nil, refresh cached heading."
  608. (if org-clock-effort
  609. (org-clock-notify-once-if-expired)
  610. (setq org-clock-task-overrun nil))
  611. (when refresh (setq org-clock-heading (org-clock--mode-line-heading)))
  612. (setq org-mode-line-string
  613. (propertize
  614. (let ((clock-string (org-clock-get-clock-string))
  615. (help-text "Org mode clock is running.\nmouse-1 shows a \
  616. menu\nmouse-2 will jump to task"))
  617. (if (and (> org-clock-string-limit 0)
  618. (> (length clock-string) org-clock-string-limit))
  619. (propertize
  620. (substring clock-string 0 org-clock-string-limit)
  621. 'help-echo (concat help-text ": " org-clock-heading))
  622. (propertize clock-string 'help-echo help-text)))
  623. 'local-map org-clock-mode-line-map
  624. 'mouse-face 'mode-line-highlight))
  625. (if (and org-clock-task-overrun org-clock-task-overrun-text)
  626. (setq org-mode-line-string
  627. (concat (propertize
  628. org-clock-task-overrun-text
  629. 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
  630. (force-mode-line-update))
  631. (defun org-clock-get-clocked-time ()
  632. "Get the clocked time for the current item in minutes.
  633. The time returned includes the time spent on this task in
  634. previous clocking intervals."
  635. (let ((currently-clocked-time
  636. (floor (- (float-time)
  637. (float-time org-clock-start-time)) 60)))
  638. (+ currently-clocked-time (or org-clock-total-time 0))))
  639. (defun org-clock-modify-effort-estimate (&optional value)
  640. "Add to or set the effort estimate of the item currently being clocked.
  641. VALUE can be a number of minutes, or a string with format hh:mm or mm.
  642. When the string starts with a + or a - sign, the current value of the effort
  643. property will be changed by that amount. If the effort value is expressed
  644. as an unit defined in `org-duration-units' (e.g. \"3h\"), the modified
  645. value will be converted to a hh:mm duration.
  646. This command will update the \"Effort\" property of the currently
  647. clocked item, and the value displayed in the mode line."
  648. (interactive)
  649. (if (org-clock-is-active)
  650. (let ((current org-clock-effort) sign)
  651. (unless value
  652. ;; Prompt user for a value or a change
  653. (setq value
  654. (read-string
  655. (format "Set effort (hh:mm or mm%s): "
  656. (if current
  657. (format ", prefix + to add to %s" org-clock-effort)
  658. "")))))
  659. (when (stringp value)
  660. ;; A string. See if it is a delta
  661. (setq sign (string-to-char value))
  662. (if (member sign '(?- ?+))
  663. (setq current (org-duration-to-minutes current)
  664. value (substring value 1))
  665. (setq current 0))
  666. (setq value (org-duration-to-minutes value))
  667. (if (equal ?- sign)
  668. (setq value (- current value))
  669. (if (equal ?+ sign) (setq value (+ current value)))))
  670. (setq value (max 0 value)
  671. org-clock-effort (org-duration-from-minutes value))
  672. (org-entry-put org-clock-marker "Effort" org-clock-effort)
  673. (org-clock-update-mode-line)
  674. (message "Effort is now %s" org-clock-effort))
  675. (message "Clock is not currently active")))
  676. (defvar org-clock-notification-was-shown nil
  677. "Shows if we have shown notification already.")
  678. (defun org-clock-notify-once-if-expired ()
  679. "Show notification if we spent more time than we estimated before.
  680. Notification is shown only once."
  681. (when (org-clocking-p)
  682. (let ((effort-in-minutes (org-duration-to-minutes org-clock-effort))
  683. (clocked-time (org-clock-get-clocked-time)))
  684. (if (setq org-clock-task-overrun
  685. (if (or (null effort-in-minutes) (zerop effort-in-minutes))
  686. nil
  687. (>= clocked-time effort-in-minutes)))
  688. (unless org-clock-notification-was-shown
  689. (setq org-clock-notification-was-shown t)
  690. (org-notify
  691. (format-message "Task `%s' should be finished by now. (%s)"
  692. org-clock-heading org-clock-effort)
  693. org-clock-sound))
  694. (setq org-clock-notification-was-shown nil)))))
  695. (defun org-notify (notification &optional play-sound)
  696. "Send a NOTIFICATION and maybe PLAY-SOUND.
  697. If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
  698. (org-show-notification notification)
  699. (if play-sound (org-clock-play-sound play-sound)))
  700. (defun org-show-notification (notification)
  701. "Show notification.
  702. Use `org-show-notification-handler' if defined,
  703. use libnotify if available, or fall back on a message."
  704. (cond ((functionp org-show-notification-handler)
  705. (funcall org-show-notification-handler notification))
  706. ((stringp org-show-notification-handler)
  707. (start-process "emacs-timer-notification" nil
  708. org-show-notification-handler notification))
  709. ((fboundp 'notifications-notify)
  710. (notifications-notify
  711. :title "Org mode message"
  712. :body notification
  713. ;; FIXME how to link to the Org icon?
  714. ;; :app-icon "~/.emacs.d/icons/mail.png"
  715. :urgency 'low))
  716. ((executable-find "notify-send")
  717. (start-process "emacs-timer-notification" nil
  718. "notify-send" notification))
  719. ;; Maybe the handler will send a message, so only use message as
  720. ;; a fall back option
  721. (t (message "%s" notification))))
  722. (defun org-clock-play-sound (&optional clock-sound)
  723. "Play sound as configured by `org-clock-sound'.
  724. Use alsa's aplay tool if available.
  725. If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
  726. (let ((org-clock-sound (or clock-sound org-clock-sound)))
  727. (cond
  728. ((not org-clock-sound))
  729. ((eq org-clock-sound t) (beep t) (beep t))
  730. ((stringp org-clock-sound)
  731. (let ((file (expand-file-name org-clock-sound)))
  732. (if (file-exists-p file)
  733. (if (executable-find "aplay")
  734. (start-process "org-clock-play-notification" nil
  735. "aplay" file)
  736. (condition-case nil
  737. (play-sound-file file)
  738. (error (beep t) (beep t))))))))))
  739. (defvar org-clock-mode-line-entry nil
  740. "Information for the mode line about the running clock.")
  741. (defun org-find-open-clocks (file)
  742. "Search through the given file and find all open clocks."
  743. (let ((buf (or (get-file-buffer file)
  744. (find-file-noselect file)))
  745. (org-clock-re (concat org-clock-string " \\(\\[.*?\\]\\)$"))
  746. clocks)
  747. (with-current-buffer buf
  748. (save-excursion
  749. (goto-char (point-min))
  750. (while (re-search-forward org-clock-re nil t)
  751. (push (cons (copy-marker (match-end 1) t)
  752. (org-time-string-to-time (match-string 1))) clocks))))
  753. clocks))
  754. (defsubst org-is-active-clock (clock)
  755. "Return t if CLOCK is the currently active clock."
  756. (and (org-clock-is-active)
  757. (= org-clock-marker (car clock))))
  758. (defmacro org-with-clock-position (clock &rest forms)
  759. "Evaluate FORMS with CLOCK as the current active clock."
  760. `(with-current-buffer (marker-buffer (car ,clock))
  761. (org-with-wide-buffer
  762. (goto-char (car ,clock))
  763. (beginning-of-line)
  764. ,@forms)))
  765. (def-edebug-spec org-with-clock-position (form body))
  766. (put 'org-with-clock-position 'lisp-indent-function 1)
  767. (defmacro org-with-clock (clock &rest forms)
  768. "Evaluate FORMS with CLOCK as the current active clock.
  769. This macro also protects the current active clock from being altered."
  770. `(org-with-clock-position ,clock
  771. (let ((org-clock-start-time (cdr ,clock))
  772. (org-clock-total-time)
  773. (org-clock-history)
  774. (org-clock-effort)
  775. (org-clock-marker (car ,clock))
  776. (org-clock-hd-marker (save-excursion
  777. (org-back-to-heading t)
  778. (point-marker))))
  779. ,@forms)))
  780. (def-edebug-spec org-with-clock (form body))
  781. (put 'org-with-clock 'lisp-indent-function 1)
  782. (defsubst org-clock-clock-in (clock &optional resume start-time)
  783. "Clock in to the clock located by CLOCK.
  784. If necessary, clock-out of the currently active clock."
  785. (org-with-clock-position clock
  786. (let ((org-clock-in-resume (or resume org-clock-in-resume)))
  787. (org-clock-in nil start-time))))
  788. (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
  789. "Clock out of the clock located by CLOCK."
  790. (let ((temp (copy-marker (car clock)
  791. (marker-insertion-type (car clock)))))
  792. (if (org-is-active-clock clock)
  793. (org-clock-out nil fail-quietly at-time)
  794. (org-with-clock clock
  795. (org-clock-out nil fail-quietly at-time)))
  796. (setcar clock temp)))
  797. (defsubst org-clock-clock-cancel (clock)
  798. "Cancel the clock located by CLOCK."
  799. (let ((temp (copy-marker (car clock)
  800. (marker-insertion-type (car clock)))))
  801. (if (org-is-active-clock clock)
  802. (org-clock-cancel)
  803. (org-with-clock clock
  804. (org-clock-cancel)))
  805. (setcar clock temp)))
  806. (defvar org-clock-clocking-in nil)
  807. (defvar org-clock-resolving-clocks nil)
  808. (defvar org-clock-resolving-clocks-due-to-idleness nil)
  809. (defun org-clock-resolve-clock (clock resolve-to clock-out-time
  810. &optional close-p restart-p fail-quietly)
  811. "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
  812. `CLOCK' is a cons cell of the form (MARKER START-TIME)."
  813. (let ((org-clock-resolving-clocks t))
  814. (cond
  815. ((null resolve-to)
  816. (org-clock-clock-cancel clock)
  817. (if (and restart-p (not org-clock-clocking-in))
  818. (org-clock-clock-in clock)))
  819. ((eq resolve-to 'now)
  820. (if restart-p
  821. (error "RESTART-P is not valid here"))
  822. (if (or close-p org-clock-clocking-in)
  823. (org-clock-clock-out clock fail-quietly)
  824. (unless (org-is-active-clock clock)
  825. (org-clock-clock-in clock t))))
  826. ((not (time-less-p resolve-to (current-time)))
  827. (error "RESOLVE-TO must refer to a time in the past"))
  828. (t
  829. (if restart-p
  830. (error "RESTART-P is not valid here"))
  831. (org-clock-clock-out clock fail-quietly (or clock-out-time
  832. resolve-to))
  833. (unless org-clock-clocking-in
  834. (if close-p
  835. (setq org-clock-leftover-time (and (null clock-out-time)
  836. resolve-to))
  837. (org-clock-clock-in clock nil (and clock-out-time
  838. resolve-to))))))))
  839. (defun org-clock-jump-to-current-clock (&optional effective-clock)
  840. "When an Org clock is running, jump to it."
  841. (let ((drawer (org-clock-into-drawer))
  842. (clock (or effective-clock (cons org-clock-marker
  843. org-clock-start-time))))
  844. (unless (marker-buffer (car clock))
  845. (user-error "No Org clock is currently running"))
  846. (org-with-clock clock (org-clock-goto))
  847. (with-current-buffer (marker-buffer (car clock))
  848. (goto-char (car clock))
  849. (when drawer
  850. (org-with-wide-buffer
  851. (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$"
  852. (regexp-quote (if (stringp drawer) drawer "LOGBOOK"))))
  853. (beg (save-excursion (org-back-to-heading t) (point))))
  854. (catch 'exit
  855. (while (re-search-backward drawer-re beg t)
  856. (let ((element (org-element-at-point)))
  857. (when (eq (org-element-type element) 'drawer)
  858. (when (> (org-element-property :end element) (car clock))
  859. (org-flag-drawer nil element))
  860. (throw 'exit nil)))))))))))
  861. (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
  862. "Resolve an open Org clock.
  863. An open clock was found, with `dangling' possibly being non-nil.
  864. If this function was invoked with a prefix argument, non-dangling
  865. open clocks are ignored. The given clock requires some sort of
  866. user intervention to resolve it, either because a clock was left
  867. dangling or due to an idle timeout. The clock resolution can
  868. either be:
  869. (a) deleted, the user doesn't care about the clock
  870. (b) restarted from the current time (if no other clock is open)
  871. (c) closed, giving the clock X minutes
  872. (d) closed and then restarted
  873. (e) resumed, as if the user had never left
  874. The format of clock is (CONS MARKER START-TIME), where MARKER
  875. identifies the buffer and position the clock is open at (and
  876. thus, the heading it's under), and START-TIME is when the clock
  877. was started."
  878. (cl-assert clock)
  879. (let* ((ch
  880. (save-window-excursion
  881. (save-excursion
  882. (unless org-clock-resolving-clocks-due-to-idleness
  883. (org-clock-jump-to-current-clock clock))
  884. (unless org-clock-resolve-expert
  885. (with-output-to-temp-buffer "*Org Clock*"
  886. (princ (format-message "Select a Clock Resolution Command:
  887. i/q Ignore this question; the same as keeping all the idle time.
  888. k/K Keep X minutes of the idle time (default is all). If this
  889. amount is less than the default, you will be clocked out
  890. that many minutes after the time that idling began, and then
  891. clocked back in at the present time.
  892. g/G Indicate that you \"got back\" X minutes ago. This is quite
  893. different from `k': it clocks you out from the beginning of
  894. the idle period and clock you back in X minutes ago.
  895. s/S Subtract the idle time from the current clock. This is the
  896. same as keeping 0 minutes.
  897. C Cancel the open timer altogether. It will be as though you
  898. never clocked in.
  899. j/J Jump to the current clock, to make manual adjustments.
  900. For all these options, using uppercase makes your final state
  901. to be CLOCKED OUT."))))
  902. (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
  903. (let (char-pressed)
  904. (while (or (null char-pressed)
  905. (and (not (memq char-pressed
  906. '(?k ?K ?g ?G ?s ?S ?C
  907. ?j ?J ?i ?q)))
  908. (or (ding) t)))
  909. (setq char-pressed
  910. (read-char (concat (funcall prompt-fn clock)
  911. " [jkKgGSscCiq]? ")
  912. nil 45)))
  913. (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
  914. (default
  915. (floor (/ (float-time
  916. (time-subtract (current-time) last-valid)) 60)))
  917. (keep
  918. (and (memq ch '(?k ?K))
  919. (read-number "Keep how many minutes? " default)))
  920. (gotback
  921. (and (memq ch '(?g ?G))
  922. (read-number "Got back how many minutes ago? " default)))
  923. (subtractp (memq ch '(?s ?S)))
  924. (barely-started-p (< (- (float-time last-valid)
  925. (float-time (cdr clock))) 45))
  926. (start-over (and subtractp barely-started-p)))
  927. (cond
  928. ((memq ch '(?j ?J))
  929. (if (eq ch ?J)
  930. (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
  931. (org-clock-jump-to-current-clock clock))
  932. ((or (null ch)
  933. (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
  934. (message ""))
  935. (t
  936. (org-clock-resolve-clock
  937. clock (cond
  938. ((or (eq ch ?C)
  939. ;; If the time on the clock was less than a minute before
  940. ;; the user went away, and they've ask to subtract all the
  941. ;; time...
  942. start-over)
  943. nil)
  944. ((or subtractp
  945. (and gotback (= gotback 0)))
  946. last-valid)
  947. ((or (and keep (= keep default))
  948. (and gotback (= gotback default)))
  949. 'now)
  950. (keep
  951. (time-add last-valid (seconds-to-time (* 60 keep))))
  952. (gotback
  953. (time-subtract (current-time)
  954. (seconds-to-time (* 60 gotback))))
  955. (t
  956. (error "Unexpected, please report this as a bug")))
  957. (and gotback last-valid)
  958. (memq ch '(?K ?G ?S))
  959. (and start-over
  960. (not (memq ch '(?K ?G ?S ?C))))
  961. fail-quietly)))))
  962. ;;;###autoload
  963. (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
  964. "Resolve all currently open Org clocks.
  965. If `only-dangling-p' is non-nil, only ask to resolve dangling
  966. \(i.e., not currently open and valid) clocks."
  967. (interactive "P")
  968. (unless org-clock-resolving-clocks
  969. (let ((org-clock-resolving-clocks t))
  970. (dolist (file (org-files-list))
  971. (let ((clocks (org-find-open-clocks file)))
  972. (dolist (clock clocks)
  973. (let ((dangling (or (not (org-clock-is-active))
  974. (/= (car clock) org-clock-marker))))
  975. (if (or (not only-dangling-p) dangling)
  976. (org-clock-resolve
  977. clock
  978. (or prompt-fn
  979. (function
  980. (lambda (clock)
  981. (format
  982. "Dangling clock started %d mins ago"
  983. (floor (- (float-time)
  984. (float-time (cdr clock)))
  985. 60)))))
  986. (or last-valid
  987. (cdr clock)))))))))))
  988. (defun org-emacs-idle-seconds ()
  989. "Return the current Emacs idle time in seconds, or nil if not idle."
  990. (let ((idle-time (current-idle-time)))
  991. (if idle-time
  992. (float-time idle-time)
  993. 0)))
  994. (defun org-mac-idle-seconds ()
  995. "Return the current Mac idle time in seconds."
  996. (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
  997. (defvar org-x11idle-exists-p
  998. ;; Check that x11idle exists
  999. (and (eq window-system 'x)
  1000. (eq 0 (call-process-shell-command
  1001. (format "command -v %s" org-clock-x11idle-program-name)))
  1002. ;; Check that x11idle can retrieve the idle time
  1003. ;; FIXME: Why "..-shell-command" rather than just `call-process'?
  1004. (eq 0 (call-process-shell-command org-clock-x11idle-program-name))))
  1005. (defun org-x11-idle-seconds ()
  1006. "Return the current X11 idle time in seconds."
  1007. (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name)) 1000))
  1008. (defun org-user-idle-seconds ()
  1009. "Return the number of seconds the user has been idle for.
  1010. This routine returns a floating point number."
  1011. (cond
  1012. ((eq system-type 'darwin)
  1013. (org-mac-idle-seconds))
  1014. ((and (eq window-system 'x) org-x11idle-exists-p)
  1015. (org-x11-idle-seconds))
  1016. (t
  1017. (org-emacs-idle-seconds))))
  1018. (defvar org-clock-user-idle-seconds)
  1019. (defun org-resolve-clocks-if-idle ()
  1020. "Resolve all currently open Org clocks.
  1021. This is performed after `org-clock-idle-time' minutes, to check
  1022. if the user really wants to stay clocked in after being idle for
  1023. so long."
  1024. (when (and org-clock-idle-time (not org-clock-resolving-clocks)
  1025. org-clock-marker (marker-buffer org-clock-marker))
  1026. (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
  1027. (org-clock-user-idle-start
  1028. (time-subtract (current-time)
  1029. (seconds-to-time org-clock-user-idle-seconds)))
  1030. (org-clock-resolving-clocks-due-to-idleness t))
  1031. (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
  1032. (org-clock-resolve
  1033. (cons org-clock-marker
  1034. org-clock-start-time)
  1035. (lambda (_)
  1036. (format "Clocked in & idle for %.1f mins"
  1037. (/ (float-time
  1038. (time-subtract (current-time)
  1039. org-clock-user-idle-start))
  1040. 60.0)))
  1041. org-clock-user-idle-start)))))
  1042. (defvar org-clock-current-task nil "Task currently clocked in.")
  1043. (defvar org-clock-out-time nil) ; store the time of the last clock-out
  1044. (defvar org--msg-extra)
  1045. ;;;###autoload
  1046. (defun org-clock-in (&optional select start-time)
  1047. "Start the clock on the current item.
  1048. If necessary, clock-out of the currently active clock.
  1049. With a `\\[universal-argument]' prefix argument SELECT, offer a list of \
  1050. recently clocked
  1051. tasks to clock into.
  1052. When SELECT is `\\[universal-argument] \ \\[universal-argument]', \
  1053. clock into the current task and mark it as
  1054. the default task, a special task that will always be offered in the
  1055. clocking selection, associated with the letter `d'.
  1056. When SELECT is `\\[universal-argument] \\[universal-argument] \
  1057. \\[universal-argument]', clock in by using the last clock-out
  1058. time as the start time. See `org-clock-continuously' to make this
  1059. the default behavior."
  1060. (interactive "P")
  1061. (setq org-clock-notification-was-shown nil)
  1062. (org-refresh-effort-properties)
  1063. (catch 'abort
  1064. (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
  1065. (org-clocking-p)))
  1066. ts selected-task target-pos (org--msg-extra "")
  1067. (leftover (and (not org-clock-resolving-clocks)
  1068. org-clock-leftover-time)))
  1069. (when (and org-clock-auto-clock-resolution
  1070. (or (not interrupting)
  1071. (eq t org-clock-auto-clock-resolution))
  1072. (not org-clock-clocking-in)
  1073. (not org-clock-resolving-clocks))
  1074. (setq org-clock-leftover-time nil)
  1075. (let ((org-clock-clocking-in t))
  1076. (org-resolve-clocks))) ; check if any clocks are dangling
  1077. (when (equal select '(64))
  1078. ;; Set start-time to `org-clock-out-time'
  1079. (let ((org-clock-continuously t))
  1080. (org-clock-in nil org-clock-out-time)
  1081. (throw 'abort nil)))
  1082. (when (equal select '(4))
  1083. (pcase (org-clock-select-task "Clock-in on task: ")
  1084. (`nil (error "Abort"))
  1085. (task (setq selected-task (copy-marker task)))))
  1086. (when (equal select '(16))
  1087. ;; Mark as default clocking task
  1088. (org-clock-mark-default-task))
  1089. (when interrupting
  1090. ;; We are interrupting the clocking of a different task. Save
  1091. ;; a marker to this task, so that we can go back. First check
  1092. ;; if we are trying to clock into the same task!
  1093. (when (or selected-task (derived-mode-p 'org-mode))
  1094. (org-with-point-at selected-task
  1095. (unless selected-task (org-back-to-heading t))
  1096. (when (and (eq (marker-buffer org-clock-hd-marker)
  1097. (org-base-buffer (current-buffer)))
  1098. (= (point) (marker-position org-clock-hd-marker))
  1099. (equal org-clock-current-task (org-get-heading t t t t)))
  1100. (message "Clock continues in %S" org-clock-heading)
  1101. (throw 'abort nil))))
  1102. (move-marker org-clock-interrupted-task
  1103. (marker-position org-clock-marker)
  1104. (marker-buffer org-clock-marker))
  1105. (let ((org-clock-clocking-in t))
  1106. (org-clock-out nil t)))
  1107. ;; Clock in at which position?
  1108. (setq target-pos
  1109. (if (and (eobp) (not (org-at-heading-p)))
  1110. (point-at-bol 0)
  1111. (point)))
  1112. (save-excursion
  1113. (when (and selected-task (marker-buffer selected-task))
  1114. ;; There is a selected task, move to the correct buffer
  1115. ;; and set the new target position.
  1116. (set-buffer (org-base-buffer (marker-buffer selected-task)))
  1117. (setq target-pos (marker-position selected-task))
  1118. (move-marker selected-task nil))
  1119. (org-with-wide-buffer
  1120. (goto-char target-pos)
  1121. (org-back-to-heading t)
  1122. (or interrupting (move-marker org-clock-interrupted-task nil))
  1123. (run-hooks 'org-clock-in-prepare-hook)
  1124. (org-clock-history-push)
  1125. (setq org-clock-current-task (org-get-heading t t t t))
  1126. (cond ((functionp org-clock-in-switch-to-state)
  1127. (let ((case-fold-search nil))
  1128. (looking-at org-complex-heading-regexp))
  1129. (let ((newstate (funcall org-clock-in-switch-to-state
  1130. (match-string 2))))
  1131. (when newstate (org-todo newstate))))
  1132. ((and org-clock-in-switch-to-state
  1133. (not (looking-at (concat org-outline-regexp "[ \t]*"
  1134. org-clock-in-switch-to-state
  1135. "\\>"))))
  1136. (org-todo org-clock-in-switch-to-state)))
  1137. (setq org-clock-heading (org-clock--mode-line-heading))
  1138. (org-clock-find-position org-clock-in-resume)
  1139. (cond
  1140. ((and org-clock-in-resume
  1141. (looking-at
  1142. (concat "^[ \t]*" org-clock-string
  1143. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1144. " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  1145. (message "Matched %s" (match-string 1))
  1146. (setq ts (concat "[" (match-string 1) "]"))
  1147. (goto-char (match-end 1))
  1148. (setq org-clock-start-time
  1149. (apply 'encode-time
  1150. (org-parse-time-string (match-string 1))))
  1151. (setq org-clock-effort (org-entry-get (point) org-effort-property))
  1152. (setq org-clock-total-time (org-clock-sum-current-item
  1153. (org-clock-get-sum-start))))
  1154. ((eq org-clock-in-resume 'auto-restart)
  1155. ;; called from org-clock-load during startup,
  1156. ;; do not interrupt, but warn!
  1157. (message "Cannot restart clock because task does not contain unfinished clock")
  1158. (ding)
  1159. (sit-for 2)
  1160. (throw 'abort nil))
  1161. (t
  1162. (insert-before-markers "\n")
  1163. (backward-char 1)
  1164. (org-indent-line)
  1165. (when (and (save-excursion
  1166. (end-of-line 0)
  1167. (org-in-item-p)))
  1168. (beginning-of-line 1)
  1169. (indent-line-to (- (current-indentation) 2)))
  1170. (insert org-clock-string " ")
  1171. (setq org-clock-effort (org-entry-get (point) org-effort-property))
  1172. (setq org-clock-total-time (org-clock-sum-current-item
  1173. (org-clock-get-sum-start)))
  1174. (setq org-clock-start-time
  1175. (or (and org-clock-continuously org-clock-out-time)
  1176. (and leftover
  1177. (y-or-n-p
  1178. (format
  1179. "You stopped another clock %d mins ago; start this one from then? "
  1180. (/ (- (float-time
  1181. (org-current-time org-clock-rounding-minutes t))
  1182. (float-time leftover))
  1183. 60)))
  1184. leftover)
  1185. start-time
  1186. (org-current-time org-clock-rounding-minutes t)))
  1187. (setq ts (org-insert-time-stamp org-clock-start-time
  1188. 'with-hm 'inactive))))
  1189. (move-marker org-clock-marker (point) (buffer-base-buffer))
  1190. (move-marker org-clock-hd-marker
  1191. (save-excursion (org-back-to-heading t) (point))
  1192. (buffer-base-buffer))
  1193. (setq org-clock-has-been-used t)
  1194. ;; add to mode line
  1195. (when (or (eq org-clock-clocked-in-display 'mode-line)
  1196. (eq org-clock-clocked-in-display 'both))
  1197. (or global-mode-string (setq global-mode-string '("")))
  1198. (or (memq 'org-mode-line-string global-mode-string)
  1199. (setq global-mode-string
  1200. (append global-mode-string '(org-mode-line-string)))))
  1201. ;; add to frame title
  1202. (when (or (eq org-clock-clocked-in-display 'frame-title)
  1203. (eq org-clock-clocked-in-display 'both))
  1204. (setq frame-title-format org-clock-frame-title-format))
  1205. (org-clock-update-mode-line)
  1206. (when org-clock-mode-line-timer
  1207. (cancel-timer org-clock-mode-line-timer)
  1208. (setq org-clock-mode-line-timer nil))
  1209. (when org-clock-clocked-in-display
  1210. (setq org-clock-mode-line-timer
  1211. (run-with-timer org-clock-update-period
  1212. org-clock-update-period
  1213. 'org-clock-update-mode-line)))
  1214. (when org-clock-idle-timer
  1215. (cancel-timer org-clock-idle-timer)
  1216. (setq org-clock-idle-timer nil))
  1217. (setq org-clock-idle-timer
  1218. (run-with-timer 60 60 'org-resolve-clocks-if-idle))
  1219. (message "Clock starts at %s - %s" ts org--msg-extra)
  1220. (run-hooks 'org-clock-in-hook))))))
  1221. ;;;###autoload
  1222. (defun org-clock-in-last (&optional arg)
  1223. "Clock in the last closed clocked item.
  1224. When already clocking in, send a warning.
  1225. With a universal prefix argument, select the task you want to
  1226. clock in from the last clocked in tasks.
  1227. With two universal prefix arguments, start clocking using the
  1228. last clock-out time, if any.
  1229. With three universal prefix arguments, interactively prompt
  1230. for a todo state to switch to, overriding the existing value
  1231. `org-clock-in-switch-to-state'."
  1232. (interactive "P")
  1233. (if (equal arg '(4)) (org-clock-in arg)
  1234. (let ((start-time (if (or org-clock-continuously (equal arg '(16)))
  1235. (or org-clock-out-time
  1236. (org-current-time org-clock-rounding-minutes t))
  1237. (org-current-time org-clock-rounding-minutes t))))
  1238. (if (null org-clock-history)
  1239. (message "No last clock")
  1240. (let ((org-clock-in-switch-to-state
  1241. (if (and (not org-clock-current-task) (equal arg '(64)))
  1242. (completing-read "Switch to state: "
  1243. (and org-clock-history
  1244. (with-current-buffer
  1245. (marker-buffer (car org-clock-history))
  1246. org-todo-keywords-1)))
  1247. org-clock-in-switch-to-state))
  1248. (already-clocking org-clock-current-task))
  1249. (org-clock-clock-in (list (car org-clock-history)) nil start-time)
  1250. (or already-clocking
  1251. ;; Don't display a message if we are already clocking in
  1252. (message "Clocking back: %s (in %s)"
  1253. org-clock-current-task
  1254. (buffer-name (marker-buffer org-clock-marker)))))))))
  1255. (defun org-clock-mark-default-task ()
  1256. "Mark current task as default task."
  1257. (interactive)
  1258. (save-excursion
  1259. (org-back-to-heading t)
  1260. (move-marker org-clock-default-task (point))))
  1261. (defun org-clock-get-sum-start ()
  1262. "Return the time from which clock times should be counted.
  1263. This is for the currently running clock as it is displayed in the
  1264. mode line. This function looks at the properties LAST_REPEAT and
  1265. in particular CLOCK_MODELINE_TOTAL and the corresponding variable
  1266. `org-clock-mode-line-total' and then decides which time to use.
  1267. The time is always returned as UTC."
  1268. (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL" 'selective)
  1269. (symbol-name org-clock-mode-line-total)))
  1270. (lr (org-entry-get nil "LAST_REPEAT")))
  1271. (cond
  1272. ((equal cmt "current")
  1273. (setq org--msg-extra "showing time in current clock instance")
  1274. (current-time))
  1275. ((equal cmt "today")
  1276. (setq org--msg-extra "showing today's task time.")
  1277. (let* ((dt (decode-time))
  1278. (hour (nth 2 dt))
  1279. (day (nth 3 dt)))
  1280. (if (< hour org-extend-today-until) (setf (nth 3 dt) (1- day)))
  1281. (setf (nth 2 dt) org-extend-today-until)
  1282. (apply #'encode-time (append (list 0 0) (nthcdr 2 dt)))))
  1283. ((or (equal cmt "all")
  1284. (and (or (not cmt) (equal cmt "auto"))
  1285. (not lr)))
  1286. (setq org--msg-extra "showing entire task time.")
  1287. nil)
  1288. ((or (equal cmt "repeat")
  1289. (and (or (not cmt) (equal cmt "auto"))
  1290. lr))
  1291. (setq org--msg-extra "showing task time since last repeat.")
  1292. (and lr (org-time-string-to-time lr)))
  1293. (t nil))))
  1294. (defun org-clock-find-position (find-unclosed)
  1295. "Find the location where the next clock line should be inserted.
  1296. When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
  1297. line and position cursor in that line."
  1298. (org-back-to-heading t)
  1299. (catch 'exit
  1300. (let* ((beg (line-beginning-position))
  1301. (end (save-excursion (outline-next-heading) (point)))
  1302. (org-clock-into-drawer (org-clock-into-drawer))
  1303. (drawer (org-clock-drawer-name)))
  1304. ;; Look for a running clock if FIND-UNCLOSED in non-nil.
  1305. (when find-unclosed
  1306. (let ((open-clock-re
  1307. (concat "^[ \t]*"
  1308. org-clock-string
  1309. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1310. " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  1311. (while (re-search-forward open-clock-re end t)
  1312. (let ((element (org-element-at-point)))
  1313. (when (and (eq (org-element-type element) 'clock)
  1314. (eq (org-element-property :status element) 'running))
  1315. (beginning-of-line)
  1316. (throw 'exit t))))))
  1317. ;; Look for an existing clock drawer.
  1318. (when drawer
  1319. (goto-char beg)
  1320. (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$")))
  1321. (while (re-search-forward drawer-re end t)
  1322. (let ((element (org-element-at-point)))
  1323. (when (eq (org-element-type element) 'drawer)
  1324. (let ((cend (org-element-property :contents-end element)))
  1325. (if (and (not org-log-states-order-reversed) cend)
  1326. (goto-char cend)
  1327. (forward-line))
  1328. (throw 'exit t)))))))
  1329. (goto-char beg)
  1330. (let ((clock-re (concat "^[ \t]*" org-clock-string))
  1331. (count 0)
  1332. positions)
  1333. ;; Count the CLOCK lines and store their positions.
  1334. (save-excursion
  1335. (while (re-search-forward clock-re end t)
  1336. (let ((element (org-element-at-point)))
  1337. (when (eq (org-element-type element) 'clock)
  1338. (setq positions (cons (line-beginning-position) positions)
  1339. count (1+ count))))))
  1340. (cond
  1341. ((null positions)
  1342. ;; Skip planning line and property drawer, if any.
  1343. (org-end-of-meta-data)
  1344. (unless (bolp) (insert "\n"))
  1345. ;; Create a new drawer if necessary.
  1346. (when (and org-clock-into-drawer
  1347. (or (not (wholenump org-clock-into-drawer))
  1348. (< org-clock-into-drawer 2)))
  1349. (let ((beg (point)))
  1350. (insert ":" drawer ":\n:END:\n")
  1351. (org-indent-region beg (point))
  1352. (org-flag-region
  1353. (line-end-position -1) (1- (point)) t 'org-hide-drawer)
  1354. (forward-line -1))))
  1355. ;; When a clock drawer needs to be created because of the
  1356. ;; number of clock items or simply if it is missing, collect
  1357. ;; all clocks in the section and wrap them within the drawer.
  1358. ((if (wholenump org-clock-into-drawer)
  1359. (>= (1+ count) org-clock-into-drawer)
  1360. drawer)
  1361. ;; Skip planning line and property drawer, if any.
  1362. (org-end-of-meta-data)
  1363. (let ((beg (point)))
  1364. (insert
  1365. (mapconcat
  1366. (lambda (p)
  1367. (save-excursion
  1368. (goto-char p)
  1369. (org-trim (delete-and-extract-region
  1370. (save-excursion (skip-chars-backward " \r\t\n")
  1371. (line-beginning-position 2))
  1372. (line-beginning-position 2)))))
  1373. positions "\n")
  1374. "\n:END:\n")
  1375. (let ((end (point-marker)))
  1376. (goto-char beg)
  1377. (save-excursion (insert ":" drawer ":\n"))
  1378. (org-flag-region (line-end-position) (1- end) t 'org-hide-drawer)
  1379. (org-indent-region (point) end)
  1380. (forward-line)
  1381. (unless org-log-states-order-reversed
  1382. (goto-char end)
  1383. (beginning-of-line -1))
  1384. (set-marker end nil))))
  1385. (org-log-states-order-reversed (goto-char (car (last positions))))
  1386. (t (goto-char (car positions))))))))
  1387. ;;;###autoload
  1388. (defun org-clock-out (&optional switch-to-state fail-quietly at-time)
  1389. "Stop the currently running clock.
  1390. Throw an error if there is no running clock and FAIL-QUIETLY is nil.
  1391. With a universal prefix, prompt for a state to switch the clocked out task
  1392. to, overriding the existing value of `org-clock-out-switch-to-state'."
  1393. (interactive "P")
  1394. (catch 'exit
  1395. (when (not (org-clocking-p))
  1396. (setq global-mode-string
  1397. (delq 'org-mode-line-string global-mode-string))
  1398. (setq frame-title-format org-frame-title-format-backup)
  1399. (force-mode-line-update)
  1400. (if fail-quietly (throw 'exit t) (user-error "No active clock")))
  1401. (let ((org-clock-out-switch-to-state
  1402. (if switch-to-state
  1403. (completing-read "Switch to state: "
  1404. (with-current-buffer
  1405. (marker-buffer org-clock-marker)
  1406. org-todo-keywords-1)
  1407. nil t "DONE")
  1408. org-clock-out-switch-to-state))
  1409. (now (org-current-time org-clock-rounding-minutes))
  1410. ts te s h m remove)
  1411. (setq org-clock-out-time now)
  1412. (save-excursion ; Do not replace this with `with-current-buffer'.
  1413. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1414. (save-restriction
  1415. (widen)
  1416. (goto-char org-clock-marker)
  1417. (beginning-of-line 1)
  1418. (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1419. (equal (match-string 1) org-clock-string))
  1420. (setq ts (match-string 2))
  1421. (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
  1422. (goto-char (match-end 0))
  1423. (delete-region (point) (point-at-eol))
  1424. (insert "--")
  1425. (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
  1426. (setq s (- (float-time
  1427. (apply #'encode-time (org-parse-time-string te)))
  1428. (float-time
  1429. (apply #'encode-time (org-parse-time-string ts))))
  1430. h (floor (/ s 3600))
  1431. s (- s (* 3600 h))
  1432. m (floor (/ s 60))
  1433. s (- s (* 60 s)))
  1434. (insert " => " (format "%2d:%02d" h m))
  1435. (move-marker org-clock-marker nil)
  1436. (move-marker org-clock-hd-marker nil)
  1437. ;; Possibly remove zero time clocks. However, do not add
  1438. ;; a note associated to the CLOCK line in this case.
  1439. (cond ((and org-clock-out-remove-zero-time-clocks
  1440. (= (+ h m) 0))
  1441. (setq remove t)
  1442. (delete-region (line-beginning-position)
  1443. (line-beginning-position 2)))
  1444. (org-log-note-clock-out
  1445. (org-add-log-setup
  1446. 'clock-out nil nil nil
  1447. (concat "# Task: " (org-get-heading t) "\n\n"))))
  1448. (when org-clock-mode-line-timer
  1449. (cancel-timer org-clock-mode-line-timer)
  1450. (setq org-clock-mode-line-timer nil))
  1451. (when org-clock-idle-timer
  1452. (cancel-timer org-clock-idle-timer)
  1453. (setq org-clock-idle-timer nil))
  1454. (setq global-mode-string
  1455. (delq 'org-mode-line-string global-mode-string))
  1456. (setq frame-title-format org-frame-title-format-backup)
  1457. (when org-clock-out-switch-to-state
  1458. (save-excursion
  1459. (org-back-to-heading t)
  1460. (let ((org-clock-out-when-done nil))
  1461. (cond
  1462. ((functionp org-clock-out-switch-to-state)
  1463. (let ((case-fold-search nil))
  1464. (looking-at org-complex-heading-regexp))
  1465. (let ((newstate (funcall org-clock-out-switch-to-state
  1466. (match-string 2))))
  1467. (when newstate (org-todo newstate))))
  1468. ((and org-clock-out-switch-to-state
  1469. (not (looking-at (concat org-outline-regexp "[ \t]*"
  1470. org-clock-out-switch-to-state
  1471. "\\>"))))
  1472. (org-todo org-clock-out-switch-to-state))))))
  1473. (force-mode-line-update)
  1474. (message (concat "Clock stopped at %s after "
  1475. (org-duration-from-minutes (+ (* 60 h) m)) "%s")
  1476. te (if remove " => LINE REMOVED" ""))
  1477. (run-hooks 'org-clock-out-hook)
  1478. (unless (org-clocking-p)
  1479. (setq org-clock-current-task nil)))))))
  1480. (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
  1481. (defun org-clock-remove-empty-clock-drawer ()
  1482. "Remove empty clock drawers in current subtree."
  1483. (save-excursion
  1484. (org-back-to-heading t)
  1485. (org-map-tree
  1486. (lambda ()
  1487. (let ((drawer (org-clock-drawer-name))
  1488. (case-fold-search t))
  1489. (when drawer
  1490. (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer)))
  1491. (end (save-excursion (outline-next-heading))))
  1492. (while (re-search-forward re end t)
  1493. (org-remove-empty-drawer-at (point))))))))))
  1494. (defun org-clock-timestamps-up (&optional n)
  1495. "Increase CLOCK timestamps at cursor.
  1496. Optional argument N tells to change by that many units."
  1497. (interactive "P")
  1498. (org-clock-timestamps-change 'up n))
  1499. (defun org-clock-timestamps-down (&optional n)
  1500. "Increase CLOCK timestamps at cursor.
  1501. Optional argument N tells to change by that many units."
  1502. (interactive "P")
  1503. (org-clock-timestamps-change 'down n))
  1504. (defun org-clock-timestamps-change (updown &optional n)
  1505. "Change CLOCK timestamps synchronously at cursor.
  1506. UPDOWN tells whether to change `up' or `down'.
  1507. Optional argument N tells to change by that many units."
  1508. (let ((tschange (if (eq updown 'up) 'org-timestamp-up
  1509. 'org-timestamp-down))
  1510. (timestamp? (org-at-timestamp-p 'lax))
  1511. ts1 begts1 ts2 begts2 updatets1 tdiff)
  1512. (when timestamp?
  1513. (save-excursion
  1514. (move-beginning-of-line 1)
  1515. (re-search-forward org-ts-regexp3 nil t)
  1516. (setq ts1 (match-string 0) begts1 (match-beginning 0))
  1517. (when (re-search-forward org-ts-regexp3 nil t)
  1518. (setq ts2 (match-string 0) begts2 (match-beginning 0))))
  1519. ;; Are we on the second timestamp?
  1520. (if (<= begts2 (point)) (setq updatets1 t))
  1521. (if (not ts2)
  1522. ;; fall back on org-timestamp-up if there is only one
  1523. (funcall tschange n)
  1524. (funcall tschange n)
  1525. (let ((ts (if updatets1 ts2 ts1))
  1526. (begts (if updatets1 begts1 begts2)))
  1527. (setq tdiff
  1528. (time-subtract
  1529. (org-time-string-to-time org-last-changed-timestamp)
  1530. (org-time-string-to-time ts)))
  1531. (save-excursion
  1532. (goto-char begts)
  1533. (org-timestamp-change
  1534. (round (/ (float-time tdiff)
  1535. (pcase timestamp?
  1536. (`minute 60)
  1537. (`hour 3600)
  1538. (`day (* 24 3600))
  1539. (`month (* 24 3600 31))
  1540. (`year (* 24 3600 365.2)))))
  1541. timestamp? 'updown)))))))
  1542. ;;;###autoload
  1543. (defun org-clock-cancel ()
  1544. "Cancel the running clock by removing the start timestamp."
  1545. (interactive)
  1546. (when (not (org-clocking-p))
  1547. (setq global-mode-string
  1548. (delq 'org-mode-line-string global-mode-string))
  1549. (setq frame-title-format org-frame-title-format-backup)
  1550. (force-mode-line-update)
  1551. (error "No active clock"))
  1552. (save-excursion ; Do not replace this with `with-current-buffer'.
  1553. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1554. (goto-char org-clock-marker)
  1555. (if (looking-back (concat "^[ \t]*" org-clock-string ".*")
  1556. (line-beginning-position))
  1557. (progn (delete-region (1- (point-at-bol)) (point-at-eol))
  1558. (org-remove-empty-drawer-at (point)))
  1559. (message "Clock gone, cancel the timer anyway")
  1560. (sit-for 2)))
  1561. (move-marker org-clock-marker nil)
  1562. (move-marker org-clock-hd-marker nil)
  1563. (setq global-mode-string
  1564. (delq 'org-mode-line-string global-mode-string))
  1565. (setq frame-title-format org-frame-title-format-backup)
  1566. (force-mode-line-update)
  1567. (message "Clock canceled")
  1568. (run-hooks 'org-clock-cancel-hook))
  1569. ;;;###autoload
  1570. (defun org-clock-goto (&optional select)
  1571. "Go to the currently clocked-in entry, or to the most recently clocked one.
  1572. With prefix arg SELECT, offer recently clocked tasks for selection."
  1573. (interactive "@P")
  1574. (let* ((recent nil)
  1575. (m (cond
  1576. (select
  1577. (or (org-clock-select-task "Select task to go to: ")
  1578. (error "No task selected")))
  1579. ((org-clocking-p) org-clock-marker)
  1580. ((and org-clock-goto-may-find-recent-task
  1581. (car org-clock-history)
  1582. (marker-buffer (car org-clock-history)))
  1583. (setq recent t)
  1584. (car org-clock-history))
  1585. (t (error "No active or recent clock task")))))
  1586. (pop-to-buffer-same-window (marker-buffer m))
  1587. (if (or (< m (point-min)) (> m (point-max))) (widen))
  1588. (goto-char m)
  1589. (org-show-entry)
  1590. (org-back-to-heading t)
  1591. (recenter org-clock-goto-before-context)
  1592. (org-reveal)
  1593. (if recent
  1594. (message "No running clock, this is the most recently clocked task"))
  1595. (run-hooks 'org-clock-goto-hook)))
  1596. (defvar-local org-clock-file-total-minutes nil
  1597. "Holds the file total time in minutes, after a call to `org-clock-sum'.")
  1598. ;;;###autoload
  1599. (defun org-clock-sum-today (&optional headline-filter)
  1600. "Sum the times for each subtree for today."
  1601. (let ((range (org-clock-special-range 'today)))
  1602. (org-clock-sum (car range) (cadr range)
  1603. headline-filter :org-clock-minutes-today)))
  1604. (defun org-clock-sum-custom (&optional headline-filter range propname)
  1605. "Sum the times for each subtree for today."
  1606. (let ((r (or (and (symbolp range) (org-clock-special-range range))
  1607. (org-clock-special-range
  1608. (intern (completing-read
  1609. "Range: "
  1610. '("today" "yesterday" "thisweek" "lastweek"
  1611. "thismonth" "lastmonth" "thisyear" "lastyear"
  1612. "interactive")
  1613. nil t))))))
  1614. (org-clock-sum (car r) (cadr r)
  1615. headline-filter (or propname :org-clock-minutes-custom))))
  1616. ;;;###autoload
  1617. (defun org-clock-sum (&optional tstart tend headline-filter propname)
  1618. "Sum the times for each subtree.
  1619. Puts the resulting times in minutes as a text property on each headline.
  1620. TSTART and TEND can mark a time range to be considered.
  1621. HEADLINE-FILTER is a zero-arg function that, if specified, is called for
  1622. each headline in the time range with point at the headline. Headlines for
  1623. which HEADLINE-FILTER returns nil are excluded from the clock summation.
  1624. PROPNAME lets you set a custom text property instead of :org-clock-minutes."
  1625. (with-silent-modifications
  1626. (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
  1627. org-clock-string
  1628. "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
  1629. (lmax 30)
  1630. (ltimes (make-vector lmax 0))
  1631. (level 0)
  1632. (tstart (cond ((stringp tstart) (org-time-string-to-seconds tstart))
  1633. ((consp tstart) (float-time tstart))
  1634. (t tstart)))
  1635. (tend (cond ((stringp tend) (org-time-string-to-seconds tend))
  1636. ((consp tend) (float-time tend))
  1637. (t tend)))
  1638. (t1 0)
  1639. time)
  1640. (remove-text-properties (point-min) (point-max)
  1641. `(,(or propname :org-clock-minutes) t
  1642. :org-clock-force-headline-inclusion t))
  1643. (save-excursion
  1644. (goto-char (point-max))
  1645. (while (re-search-backward re nil t)
  1646. (cond
  1647. ((match-end 2)
  1648. ;; Two time stamps.
  1649. (let* ((ts (float-time
  1650. (apply #'encode-time
  1651. (save-match-data
  1652. (org-parse-time-string (match-string 2))))))
  1653. (te (float-time
  1654. (apply #'encode-time
  1655. (org-parse-time-string (match-string 3)))))
  1656. (dt (- (if tend (min te tend) te)
  1657. (if tstart (max ts tstart) ts))))
  1658. (when (> dt 0) (cl-incf t1 (floor (/ dt 60))))))
  1659. ((match-end 4)
  1660. ;; A naked time.
  1661. (setq t1 (+ t1 (string-to-number (match-string 5))
  1662. (* 60 (string-to-number (match-string 4))))))
  1663. (t ;A headline
  1664. ;; Add the currently clocking item time to the total.
  1665. (when (and org-clock-report-include-clocking-task
  1666. (eq (org-clocking-buffer) (current-buffer))
  1667. (eq (marker-position org-clock-hd-marker) (point))
  1668. tstart
  1669. tend
  1670. (>= (float-time org-clock-start-time) tstart)
  1671. (<= (float-time org-clock-start-time) tend))
  1672. (let ((time (floor (- (float-time)
  1673. (float-time org-clock-start-time))
  1674. 60)))
  1675. (setq t1 (+ t1 time))))
  1676. (let* ((headline-forced
  1677. (get-text-property (point)
  1678. :org-clock-force-headline-inclusion))
  1679. (headline-included
  1680. (or (null headline-filter)
  1681. (save-excursion
  1682. (save-match-data (funcall headline-filter))))))
  1683. (setq level (- (match-end 1) (match-beginning 1)))
  1684. (when (>= level lmax)
  1685. (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
  1686. (when (or (> t1 0) (> (aref ltimes level) 0))
  1687. (when (or headline-included headline-forced)
  1688. (if headline-included
  1689. (cl-loop for l from 0 to level do
  1690. (aset ltimes l (+ (aref ltimes l) t1))))
  1691. (setq time (aref ltimes level))
  1692. (goto-char (match-beginning 0))
  1693. (put-text-property (point) (point-at-eol)
  1694. (or propname :org-clock-minutes) time)
  1695. (when headline-filter
  1696. (save-excursion
  1697. (save-match-data
  1698. (while (org-up-heading-safe)
  1699. (put-text-property
  1700. (point) (line-end-position)
  1701. :org-clock-force-headline-inclusion t))))))
  1702. (setq t1 0)
  1703. (cl-loop for l from level to (1- lmax) do
  1704. (aset ltimes l 0)))))))
  1705. (setq org-clock-file-total-minutes (aref ltimes 0))))))
  1706. (defun org-clock-sum-current-item (&optional tstart)
  1707. "Return time, clocked on current item in total."
  1708. (save-excursion
  1709. (save-restriction
  1710. (org-narrow-to-subtree)
  1711. (org-clock-sum tstart)
  1712. org-clock-file-total-minutes)))
  1713. ;;;###autoload
  1714. (defun org-clock-display (&optional arg)
  1715. "Show subtree times in the entire buffer.
  1716. By default, show the total time for the range defined in
  1717. `org-clock-display-default-range'. With `\\[universal-argument]' \
  1718. prefix, show
  1719. the total time for today instead.
  1720. With `\\[universal-argument] \\[universal-argument]' prefix, \
  1721. use a custom range, entered at prompt.
  1722. With `\\[universal-argument] \ \\[universal-argument] \
  1723. \\[universal-argument]' prefix, display the total time in the
  1724. echo area.
  1725. Use `\\[org-clock-remove-overlays]' to remove the subtree times."
  1726. (interactive "P")
  1727. (org-clock-remove-overlays)
  1728. (let* ((todayp (equal arg '(4)))
  1729. (customp (member arg '((16) today yesterday
  1730. thisweek lastweek thismonth
  1731. lastmonth thisyear lastyear
  1732. untilnow interactive)))
  1733. (prop (cond ((not arg) :org-clock-minutes-default)
  1734. (todayp :org-clock-minutes-today)
  1735. (customp :org-clock-minutes-custom)
  1736. (t :org-clock-minutes))))
  1737. (cond ((not arg) (org-clock-sum-custom
  1738. nil org-clock-display-default-range prop))
  1739. (todayp (org-clock-sum-today))
  1740. (customp (org-clock-sum-custom nil arg))
  1741. (t (org-clock-sum)))
  1742. (unless (equal arg '(64))
  1743. (save-excursion
  1744. (goto-char (point-min))
  1745. (let ((p nil))
  1746. (while (or (and (equal (setq p (point)) (point-min))
  1747. (get-text-property p prop))
  1748. (setq p (next-single-property-change (point) prop)))
  1749. (goto-char p)
  1750. (let ((time (get-text-property p prop)))
  1751. (when time (org-clock-put-overlay time)))))
  1752. ;; Arrange to remove the overlays upon next change.
  1753. (when org-remove-highlights-with-change
  1754. (add-hook 'before-change-functions 'org-clock-remove-overlays
  1755. nil 'local))))
  1756. (let* ((h (/ org-clock-file-total-minutes 60))
  1757. (m (- org-clock-file-total-minutes (* 60 h))))
  1758. (message (concat (format "Total file time%s: "
  1759. (cond (todayp " for today")
  1760. (customp " (custom)")
  1761. (t "")))
  1762. (org-duration-from-minutes
  1763. org-clock-file-total-minutes)
  1764. " (%d hours and %d minutes)")
  1765. h m))))
  1766. (defvar-local org-clock-overlays nil)
  1767. (defun org-clock-put-overlay (time)
  1768. "Put an overlay on the headline at point, displaying TIME.
  1769. Create a new overlay and store it in `org-clock-overlays', so
  1770. that it will be easy to remove. This function assumes point is
  1771. on a headline."
  1772. (org-match-line org-complex-heading-regexp)
  1773. (goto-char (match-beginning 4))
  1774. (let* ((headline (match-string 4))
  1775. (text (concat headline
  1776. (org-add-props
  1777. (make-string
  1778. (max (- (- 60 (current-column))
  1779. (org-string-width headline)
  1780. (length (org-get-at-bol 'line-prefix)))
  1781. 0)
  1782. ?\·)
  1783. '(face shadow))
  1784. (org-add-props
  1785. (format " %9s " (org-duration-from-minutes time))
  1786. '(face org-clock-overlay))))
  1787. (o (make-overlay (point) (line-end-position))))
  1788. (org-overlay-display o text)
  1789. (push o org-clock-overlays)))
  1790. ;;;###autoload
  1791. (defun org-clock-remove-overlays (&optional _beg _end noremove)
  1792. "Remove the occur highlights from the buffer.
  1793. If NOREMOVE is nil, remove this function from the
  1794. `before-change-functions' in the current buffer."
  1795. (interactive)
  1796. (unless org-inhibit-highlight-removal
  1797. (mapc #'delete-overlay org-clock-overlays)
  1798. (setq org-clock-overlays nil)
  1799. (unless noremove
  1800. (remove-hook 'before-change-functions
  1801. 'org-clock-remove-overlays 'local))))
  1802. (defvar org-state) ;; dynamically scoped into this function
  1803. (defun org-clock-out-if-current ()
  1804. "Clock out if the current entry contains the running clock.
  1805. This is used to stop the clock after a TODO entry is marked DONE,
  1806. and is only done if the variable `org-clock-out-when-done' is not nil."
  1807. (when (and (org-clocking-p)
  1808. org-clock-out-when-done
  1809. (marker-buffer org-clock-marker)
  1810. (or (and (eq t org-clock-out-when-done)
  1811. (member org-state org-done-keywords))
  1812. (and (listp org-clock-out-when-done)
  1813. (member org-state org-clock-out-when-done)))
  1814. (equal (or (buffer-base-buffer (org-clocking-buffer))
  1815. (org-clocking-buffer))
  1816. (or (buffer-base-buffer (current-buffer))
  1817. (current-buffer)))
  1818. (< (point) org-clock-marker)
  1819. (> (save-excursion (outline-next-heading) (point))
  1820. org-clock-marker))
  1821. ;; Clock out, but don't accept a logging message for this.
  1822. (let ((org-log-note-clock-out nil)
  1823. (org-clock-out-switch-to-state nil))
  1824. (org-clock-out))))
  1825. (add-hook 'org-after-todo-state-change-hook
  1826. 'org-clock-out-if-current)
  1827. ;;;###autoload
  1828. (defun org-clock-get-clocktable (&rest props)
  1829. "Get a formatted clocktable with parameters according to PROPS.
  1830. The table is created in a temporary buffer, fully formatted and
  1831. fontified, and then returned."
  1832. ;; Set the defaults
  1833. (setq props (plist-put props :name "clocktable"))
  1834. (unless (plist-member props :maxlevel)
  1835. (setq props (plist-put props :maxlevel 2)))
  1836. (unless (plist-member props :scope)
  1837. (setq props (plist-put props :scope 'agenda)))
  1838. (with-temp-buffer
  1839. (org-mode)
  1840. (org-create-dblock props)
  1841. (org-update-dblock)
  1842. (org-font-lock-ensure)
  1843. (forward-line 2)
  1844. (buffer-substring (point) (progn
  1845. (re-search-forward "^[ \t]*#\\+END" nil t)
  1846. (point-at-bol)))))
  1847. ;;;###autoload
  1848. (defun org-clock-report (&optional arg)
  1849. "Update or create a table containing a report about clocked time.
  1850. If point is inside an existing clocktable block, update it.
  1851. Otherwise, insert a new one.
  1852. The new table inherits its properties from the variable
  1853. `org-clock-clocktable-default-properties'. The scope of the
  1854. clocktable, when not specified in the previous variable, is
  1855. `subtree' when the function is called from within a subtree, and
  1856. `file' elsewhere.
  1857. When called with a prefix argument, move to the first clock table
  1858. in the buffer and update it."
  1859. (interactive "P")
  1860. (org-clock-remove-overlays)
  1861. (when arg
  1862. (org-find-dblock "clocktable")
  1863. (org-show-entry))
  1864. (pcase (org-in-clocktable-p)
  1865. (`nil
  1866. (org-create-dblock
  1867. (org-combine-plists
  1868. (list :scope (if (org-before-first-heading-p) 'file 'subtree))
  1869. org-clock-clocktable-default-properties
  1870. '(:name "clocktable"))))
  1871. (start (goto-char start)))
  1872. (org-update-dblock))
  1873. (defun org-day-of-week (day month year)
  1874. "Returns the day of the week as an integer."
  1875. (nth 6
  1876. (decode-time
  1877. (date-to-time
  1878. (format "%d-%02d-%02dT00:00:00" year month day)))))
  1879. (defun org-quarter-to-date (quarter year)
  1880. "Get the date (week day year) of the first day of a given quarter."
  1881. (let (startday)
  1882. (cond
  1883. ((= quarter 1)
  1884. (setq startday (org-day-of-week 1 1 year))
  1885. (cond
  1886. ((= startday 0)
  1887. (list 52 7 (- year 1)))
  1888. ((= startday 6)
  1889. (list 52 6 (- year 1)))
  1890. ((<= startday 4)
  1891. (list 1 startday year))
  1892. ((> startday 4)
  1893. (list 53 startday (- year 1)))
  1894. )
  1895. )
  1896. ((= quarter 2)
  1897. (setq startday (org-day-of-week 1 4 year))
  1898. (cond
  1899. ((= startday 0)
  1900. (list 13 startday year))
  1901. ((< startday 4)
  1902. (list 14 startday year))
  1903. ((>= startday 4)
  1904. (list 13 startday year))
  1905. )
  1906. )
  1907. ((= quarter 3)
  1908. (setq startday (org-day-of-week 1 7 year))
  1909. (cond
  1910. ((= startday 0)
  1911. (list 26 startday year))
  1912. ((< startday 4)
  1913. (list 27 startday year))
  1914. ((>= startday 4)
  1915. (list 26 startday year))
  1916. )
  1917. )
  1918. ((= quarter 4)
  1919. (setq startday (org-day-of-week 1 10 year))
  1920. (cond
  1921. ((= startday 0)
  1922. (list 39 startday year))
  1923. ((<= startday 4)
  1924. (list 40 startday year))
  1925. ((> startday 4)
  1926. (list 39 startday year)))))))
  1927. (defun org-clock-special-range (key &optional time as-strings wstart mstart)
  1928. "Return two times bordering a special time range.
  1929. KEY is a symbol specifying the range and can be one of `today',
  1930. `yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
  1931. `thisyear', `lastyear' or `untilnow'. If set to `interactive',
  1932. user is prompted for range boundaries. It can be a string or an
  1933. integer.
  1934. By default, a week starts Monday 0:00 and ends Sunday 24:00. The
  1935. range is determined relative to TIME, which defaults to current
  1936. time.
  1937. The return value is a list containing two internal times, one for
  1938. the beginning of the range and one for its end, like the ones
  1939. returned by `current-time' or `encode-time' and a string used to
  1940. display information. If AS-STRINGS is non-nil, the returned
  1941. times will be formatted strings.
  1942. If WSTART is non-nil, use this number to specify the starting day
  1943. of a week (monday is 1). If MSTART is non-nil, use this number
  1944. to specify the starting day of a month (1 is the first day of the
  1945. month). If you can combine both, the month starting day will
  1946. have priority."
  1947. (let* ((tm (decode-time time))
  1948. (m (nth 1 tm))
  1949. (h (nth 2 tm))
  1950. (d (nth 3 tm))
  1951. (month (nth 4 tm))
  1952. (y (nth 5 tm))
  1953. (dow (nth 6 tm))
  1954. (skey (format "%s" key))
  1955. (shift 0)
  1956. (q (cond ((>= month 10) 4)
  1957. ((>= month 7) 3)
  1958. ((>= month 4) 2)
  1959. (t 1)))
  1960. m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq)
  1961. (cond
  1962. ((string-match "\\`[0-9]+\\'" skey)
  1963. (setq y (string-to-number skey) month 1 d 1 key 'year))
  1964. ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey)
  1965. (setq y (string-to-number (match-string 1 skey))
  1966. month (string-to-number (match-string 2 skey))
  1967. d 1
  1968. key 'month))
  1969. ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey)
  1970. (require 'cal-iso)
  1971. (let ((date (calendar-gregorian-from-absolute
  1972. (calendar-iso-to-absolute
  1973. (list (string-to-number (match-string 2 skey))
  1974. 1
  1975. (string-to-number (match-string 1 skey)))))))
  1976. (setq d (nth 1 date)
  1977. month (car date)
  1978. y (nth 2 date)
  1979. dow 1
  1980. key 'week)))
  1981. ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey)
  1982. (require 'cal-iso)
  1983. (setq q (string-to-number (match-string 2 skey)))
  1984. (let ((date (calendar-gregorian-from-absolute
  1985. (calendar-iso-to-absolute
  1986. (org-quarter-to-date
  1987. q (string-to-number (match-string 1 skey)))))))
  1988. (setq d (nth 1 date)
  1989. month (car date)
  1990. y (nth 2 date)
  1991. dow 1
  1992. key 'quarter)))
  1993. ((string-match
  1994. "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
  1995. skey)
  1996. (setq y (string-to-number (match-string 1 skey))
  1997. month (string-to-number (match-string 2 skey))
  1998. d (string-to-number (match-string 3 skey))
  1999. key 'day))
  2000. ((string-match "\\([-+][0-9]+\\)\\'" skey)
  2001. (setq shift (string-to-number (match-string 1 skey))
  2002. key (intern (substring skey 0 (match-beginning 1))))
  2003. (when (and (memq key '(quarter thisq)) (> shift 0))
  2004. (error "Looking forward with quarters isn't implemented"))))
  2005. (when (= shift 0)
  2006. (pcase key
  2007. (`yesterday (setq key 'today shift -1))
  2008. (`lastweek (setq key 'week shift -1))
  2009. (`lastmonth (setq key 'month shift -1))
  2010. (`lastyear (setq key 'year shift -1))
  2011. (`lastq (setq key 'quarter shift -1))))
  2012. ;; Prepare start and end times depending on KEY's type.
  2013. (pcase key
  2014. ((or `day `today) (setq m 0
  2015. h org-extend-today-until
  2016. h1 (+ 24 org-extend-today-until)
  2017. d (+ d shift)))
  2018. ((or `week `thisweek)
  2019. (let* ((ws (or wstart 1))
  2020. (diff (+ (* -7 shift) (if (= dow 0) (- 7 ws) (- dow ws)))))
  2021. (setq m 0 h org-extend-today-until d (- d diff) d1 (+ 7 d))))
  2022. ((or `month `thismonth)
  2023. (setq h org-extend-today-until m 0 d (or mstart 1)
  2024. month (+ month shift) month1 (1+ month)))
  2025. ((or `quarter `thisq)
  2026. ;; Compute if this shift remains in this year. If not, compute
  2027. ;; how many years and quarters we have to shift (via floor*) and
  2028. ;; compute the shifted years, months and quarters.
  2029. (cond
  2030. ((< (+ (- q 1) shift) 0) ; Shift not in this year.
  2031. (let* ((interval (* -1 (+ (- q 1) shift)))
  2032. ;; Set tmp to ((years to shift) (quarters to shift)).
  2033. (tmp (cl-floor interval 4)))
  2034. ;; Due to the use of floor, 0 quarters actually means 4.
  2035. (if (= 0 (nth 1 tmp))
  2036. (setq shiftedy (- y (nth 0 tmp))
  2037. shiftedm 1
  2038. shiftedq 1)
  2039. (setq shiftedy (- y (+ 1 (nth 0 tmp)))
  2040. shiftedm (- 13 (* 3 (nth 1 tmp)))
  2041. shiftedq (- 5 (nth 1 tmp)))))
  2042. (setq m 0 h org-extend-today-until d 1
  2043. month shiftedm month1 (+ 3 shiftedm) y shiftedy))
  2044. ((> (+ q shift) 0) ; Shift is within this year.
  2045. (setq shiftedq (+ q shift))
  2046. (setq shiftedy y)
  2047. (let ((qshift (* 3 (1- (+ q shift)))))
  2048. (setq m 0 h org-extend-today-until d 1
  2049. month (+ 1 qshift) month1 (+ 4 qshift))))))
  2050. ((or `year `thisyear)
  2051. (setq m 0 h org-extend-today-until d 1 month 1 y (+ y shift) y1 (1+ y)))
  2052. ((or `interactive `untilnow)) ; Special cases, ignore them.
  2053. (_ (user-error "No such time block %s" key)))
  2054. ;; Format start and end times according to AS-STRINGS.
  2055. (let* ((start (pcase key
  2056. (`interactive (org-read-date nil t nil "Range start? "))
  2057. ;; In theory, all clocks started after the dawn of
  2058. ;; humanity.
  2059. (`untilnow (encode-time 0 0 0 0 0 -50000))
  2060. (_ (encode-time 0 m h d month y))))
  2061. (end (pcase key
  2062. (`interactive (org-read-date nil t nil "Range end? "))
  2063. (`untilnow (current-time))
  2064. (_ (encode-time 0
  2065. (or m1 m)
  2066. (or h1 h)
  2067. (or d1 d)
  2068. (or month1 month)
  2069. (or y1 y)))))
  2070. (text
  2071. (pcase key
  2072. ((or `day `today) (format-time-string "%A, %B %d, %Y" start))
  2073. ((or `week `thisweek) (format-time-string "week %G-W%V" start))
  2074. ((or `month `thismonth) (format-time-string "%B %Y" start))
  2075. ((or `year `thisyear) (format-time-string "the year %Y" start))
  2076. ((or `quarter `thisq)
  2077. (concat (org-count-quarter shiftedq)
  2078. " quarter of " (number-to-string shiftedy)))
  2079. (`interactive "(Range interactively set)")
  2080. (`untilnow "now"))))
  2081. (if (not as-strings) (list start end text)
  2082. (let ((f (cdr org-time-stamp-formats)))
  2083. (list (format-time-string f start)
  2084. (format-time-string f end)
  2085. text))))))
  2086. (defun org-count-quarter (n)
  2087. (cond
  2088. ((= n 1) "1st")
  2089. ((= n 2) "2nd")
  2090. ((= n 3) "3rd")
  2091. ((= n 4) "4th")))
  2092. ;;;###autoload
  2093. (defun org-clocktable-shift (dir n)
  2094. "Try to shift the :block date of the clocktable at point.
  2095. Point must be in the #+BEGIN: line of a clocktable, or this function
  2096. will throw an error.
  2097. DIR is a direction, a symbol `left', `right', `up', or `down'.
  2098. Both `left' and `down' shift the block toward the past, `up' and `right'
  2099. push it toward the future.
  2100. N is the number of shift steps to take. The size of the step depends on
  2101. the currently selected interval size."
  2102. (setq n (prefix-numeric-value n))
  2103. (and (memq dir '(left down)) (setq n (- n)))
  2104. (save-excursion
  2105. (goto-char (point-at-bol))
  2106. (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
  2107. (error "Line needs a :block definition before this command works")
  2108. (let* ((b (match-beginning 1)) (e (match-end 1))
  2109. (s (match-string 1))
  2110. block shift ins y mw d date wp m)
  2111. (cond
  2112. ((equal s "yesterday") (setq s "today-1"))
  2113. ((equal s "lastweek") (setq s "thisweek-1"))
  2114. ((equal s "lastmonth") (setq s "thismonth-1"))
  2115. ((equal s "lastyear") (setq s "thisyear-1"))
  2116. ((equal s "lastq") (setq s "thisq-1")))
  2117. (cond
  2118. ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
  2119. (setq block (match-string 1 s)
  2120. shift (if (match-end 2)
  2121. (string-to-number (match-string 2 s))
  2122. 0))
  2123. (setq shift (+ shift n))
  2124. (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
  2125. ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
  2126. ;; 1 1 2 3 3 4 4 5 6 6 5 2
  2127. (setq y (string-to-number (match-string 1 s))
  2128. wp (and (match-end 3) (match-string 3 s))
  2129. mw (and (match-end 4) (string-to-number (match-string 4 s)))
  2130. d (and (match-end 6) (string-to-number (match-string 6 s))))
  2131. (cond
  2132. (d (setq ins (format-time-string
  2133. "%Y-%m-%d"
  2134. (encode-time 0 0 0 (+ d n) m y))))
  2135. ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
  2136. (require 'cal-iso)
  2137. (setq date (calendar-gregorian-from-absolute
  2138. (calendar-iso-to-absolute (list (+ mw n) 1 y))))
  2139. (setq ins (format-time-string
  2140. "%G-W%V"
  2141. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  2142. ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
  2143. (require 'cal-iso)
  2144. ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
  2145. (if (> (+ mw n) 4)
  2146. (setq mw 0
  2147. y (+ 1 y))
  2148. ())
  2149. ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
  2150. (if (= (+ mw n) 0)
  2151. (setq mw 5
  2152. y (- y 1))
  2153. ())
  2154. (setq date (calendar-gregorian-from-absolute
  2155. (calendar-iso-to-absolute (org-quarter-to-date (+ mw n) y))))
  2156. (setq ins (format-time-string
  2157. (concat (number-to-string y) "-Q" (number-to-string (+ mw n)))
  2158. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  2159. (mw
  2160. (setq ins (format-time-string
  2161. "%Y-%m"
  2162. (encode-time 0 0 0 1 (+ mw n) y))))
  2163. (y
  2164. (setq ins (number-to-string (+ y n))))))
  2165. (t (error "Cannot shift clocktable block")))
  2166. (when ins
  2167. (goto-char b)
  2168. (insert ins)
  2169. (delete-region (point) (+ (point) (- e b)))
  2170. (beginning-of-line 1)
  2171. (org-update-dblock)
  2172. t)))))
  2173. ;;;###autoload
  2174. (defun org-dblock-write:clocktable (params)
  2175. "Write the standard clocktable."
  2176. (setq params (org-combine-plists org-clocktable-defaults params))
  2177. (catch 'exit
  2178. (let* ((scope (plist-get params :scope))
  2179. (files (pcase scope
  2180. (`agenda
  2181. (org-agenda-files t))
  2182. (`agenda-with-archives
  2183. (org-add-archive-files (org-agenda-files t)))
  2184. (`file-with-archives
  2185. (and buffer-file-name
  2186. (org-add-archive-files (list buffer-file-name))))
  2187. ((pred functionp) (funcall scope))
  2188. ((pred consp) scope)
  2189. (_ (or (buffer-file-name) (current-buffer)))))
  2190. (block (plist-get params :block))
  2191. (ts (plist-get params :tstart))
  2192. (te (plist-get params :tend))
  2193. (ws (plist-get params :wstart))
  2194. (ms (plist-get params :mstart))
  2195. (step (plist-get params :step))
  2196. (formatter (or (plist-get params :formatter)
  2197. org-clock-clocktable-formatter
  2198. 'org-clocktable-write-default))
  2199. cc)
  2200. ;; Check if we need to do steps
  2201. (when block
  2202. ;; Get the range text for the header
  2203. (setq cc (org-clock-special-range block nil t ws ms)
  2204. ts (car cc)
  2205. te (nth 1 cc)))
  2206. (when step
  2207. ;; Write many tables, in steps
  2208. (unless (or block (and ts te))
  2209. (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
  2210. (org-clocktable-steps params)
  2211. (throw 'exit nil))
  2212. (org-agenda-prepare-buffers (if (consp files) files (list files)))
  2213. (let ((origin (point))
  2214. (tables
  2215. (if (consp files)
  2216. (mapcar (lambda (file)
  2217. (with-current-buffer (find-buffer-visiting file)
  2218. (save-excursion
  2219. (save-restriction
  2220. (org-clock-get-table-data file params)))))
  2221. files)
  2222. ;; Get the right restriction for the scope.
  2223. (save-restriction
  2224. (cond
  2225. ((not scope)) ;use the restriction as it is now
  2226. ((eq scope 'file) (widen))
  2227. ((eq scope 'subtree) (org-narrow-to-subtree))
  2228. ((eq scope 'tree)
  2229. (while (org-up-heading-safe))
  2230. (org-narrow-to-subtree))
  2231. ((and (symbolp scope)
  2232. (string-match "\\`tree\\([0-9]+\\)\\'"
  2233. (symbol-name scope)))
  2234. (let ((level (string-to-number
  2235. (match-string 1 (symbol-name scope)))))
  2236. (catch 'exit
  2237. (while (org-up-heading-safe)
  2238. (looking-at org-outline-regexp)
  2239. (when (<= (org-reduced-level (funcall outline-level))
  2240. level)
  2241. (throw 'exit nil))))
  2242. (org-narrow-to-subtree))))
  2243. (list (org-clock-get-table-data nil params)))))
  2244. (multifile
  2245. ;; Even though `file-with-archives' can consist of
  2246. ;; multiple files, we consider this is one extended file
  2247. ;; instead.
  2248. (and (consp files) (not (eq scope 'file-with-archives)))))
  2249. (funcall formatter
  2250. origin
  2251. tables
  2252. (org-combine-plists params `(:multifile ,multifile)))))))
  2253. (defun org-clocktable-write-default (ipos tables params)
  2254. "Write out a clock table at position IPOS in the current buffer.
  2255. TABLES is a list of tables with clocking data as produced by
  2256. `org-clock-get-table-data'. PARAMS is the parameter property list obtained
  2257. from the dynamic block definition."
  2258. ;; This function looks quite complicated, mainly because there are a
  2259. ;; lot of options which can add or remove columns. I have massively
  2260. ;; commented this function, the I hope it is understandable. If
  2261. ;; someone wants to write their own special formatter, this maybe
  2262. ;; much easier because there can be a fixed format with a
  2263. ;; well-defined number of columns...
  2264. (let* ((lang (or (plist-get params :lang) "en"))
  2265. (multifile (plist-get params :multifile))
  2266. (block (plist-get params :block))
  2267. (sort (plist-get params :sort))
  2268. (header (plist-get params :header))
  2269. (link (plist-get params :link))
  2270. (maxlevel (or (plist-get params :maxlevel) 3))
  2271. (emph (plist-get params :emphasize))
  2272. (compact? (plist-get params :compact))
  2273. (narrow (or (plist-get params :narrow) (and compact? '40!)))
  2274. (level? (and (not compact?) (plist-get params :level)))
  2275. (timestamp (plist-get params :timestamp))
  2276. (tags (plist-get params :tags))
  2277. (properties (plist-get params :properties))
  2278. (time-columns
  2279. (if (or compact? (< maxlevel 2)) 1
  2280. ;; Deepest headline level is a hard limit for the number
  2281. ;; of time columns.
  2282. (let ((levels
  2283. (cl-mapcan
  2284. (lambda (table)
  2285. (pcase table
  2286. (`(,_ ,(and (pred wholenump) (pred (/= 0))) ,entries)
  2287. (mapcar #'car entries))))
  2288. tables)))
  2289. (min maxlevel
  2290. (or (plist-get params :tcolumns) 100)
  2291. (if (null levels) 1 (apply #'max levels))))))
  2292. (indent (or compact? (plist-get params :indent)))
  2293. (formula (plist-get params :formula))
  2294. (case-fold-search t)
  2295. (total-time (apply #'+ (mapcar #'cadr tables)))
  2296. recalc narrow-cut-p)
  2297. (when (and narrow (integerp narrow) link)
  2298. ;; We cannot have both integer narrow and link.
  2299. (message "Using hard narrowing in clocktable to allow for links")
  2300. (setq narrow (intern (format "%d!" narrow))))
  2301. (pcase narrow
  2302. ((or `nil (pred integerp)) nil) ;nothing to do
  2303. ((and (pred symbolp)
  2304. (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow))))
  2305. (setq narrow-cut-p t)
  2306. (setq narrow (string-to-number (symbol-name narrow))))
  2307. (_ (error "Invalid value %s of :narrow property in clock table" narrow)))
  2308. ;; Now we need to output this table stuff.
  2309. (goto-char ipos)
  2310. ;; Insert the text *before* the actual table.
  2311. (insert-before-markers
  2312. (or header
  2313. ;; Format the standard header.
  2314. (format "#+CAPTION: %s %s%s\n"
  2315. (org-clock--translate "Clock summary at" lang)
  2316. (format-time-string (org-time-stamp-format t t))
  2317. (if block
  2318. (let ((range-text
  2319. (nth 2 (org-clock-special-range
  2320. block nil t
  2321. (plist-get params :wstart)
  2322. (plist-get params :mstart)))))
  2323. (format ", for %s." range-text))
  2324. ""))))
  2325. ;; Insert the narrowing line
  2326. (when (and narrow (integerp narrow) (not narrow-cut-p))
  2327. (insert-before-markers
  2328. "|" ;table line starter
  2329. (if multifile "|" "") ;file column, maybe
  2330. (if level? "|" "") ;level column, maybe
  2331. (if timestamp "|" "") ;timestamp column, maybe
  2332. (if tags "|" "") ;tags columns, maybe
  2333. (if properties ;properties columns, maybe
  2334. (make-string (length properties) ?|)
  2335. "")
  2336. (format "<%d>| |\n" narrow))) ;headline and time columns
  2337. ;; Insert the table header line
  2338. (insert-before-markers
  2339. "|" ;table line starter
  2340. (if multifile ;file column, maybe
  2341. (concat (org-clock--translate "File" lang) "|")
  2342. "")
  2343. (if level? ;level column, maybe
  2344. (concat (org-clock--translate "L" lang) "|")
  2345. "")
  2346. (if timestamp ;timestamp column, maybe
  2347. (concat (org-clock--translate "Timestamp" lang) "|")
  2348. "")
  2349. (if tags "Tags |" "") ;tags columns, maybe
  2350. (if properties ;properties columns, maybe
  2351. (concat (mapconcat #'identity properties "|") "|")
  2352. "")
  2353. (concat (org-clock--translate "Headline" lang)"|")
  2354. (concat (org-clock--translate "Time" lang) "|")
  2355. (make-string (max 0 (1- time-columns)) ?|) ;other time columns
  2356. (if (eq formula '%) "%|\n" "\n"))
  2357. ;; Insert the total time in the table
  2358. (insert-before-markers
  2359. "|-\n" ;a hline
  2360. "|" ;table line starter
  2361. (if multifile (format "| %s " (org-clock--translate "ALL" lang)) "")
  2362. ;file column, maybe
  2363. (if level? "|" "") ;level column, maybe
  2364. (if timestamp "|" "") ;timestamp column, maybe
  2365. (if tags "|" "") ;timestamp column, maybe
  2366. (make-string (length properties) ?|) ;properties columns, maybe
  2367. (concat (format org-clock-total-time-cell-format
  2368. (org-clock--translate "Total time" lang))
  2369. "| ")
  2370. (format org-clock-total-time-cell-format
  2371. (org-duration-from-minutes (or total-time 0))) ;time
  2372. "|"
  2373. (make-string (max 0 (1- time-columns)) ?|)
  2374. (cond ((not (eq formula '%)) "")
  2375. ((or (not total-time) (= total-time 0)) "0.0|")
  2376. (t "100.0|"))
  2377. "\n")
  2378. ;; Now iterate over the tables and insert the data but only if any
  2379. ;; time has been collected.
  2380. (when (and total-time (> total-time 0))
  2381. (pcase-dolist (`(,file-name ,file-time ,entries) tables)
  2382. (when (or (and file-time (> file-time 0))
  2383. (not (plist-get params :fileskip0)))
  2384. (insert-before-markers "|-\n") ;hline at new file
  2385. ;; First the file time, if we have multiple files.
  2386. (when multifile
  2387. ;; Summarize the time collected from this file.
  2388. (insert-before-markers
  2389. (format (concat "| %s %s | %s%s"
  2390. (format org-clock-file-time-cell-format
  2391. (org-clock--translate "File time" lang))
  2392. " | *%s*|\n")
  2393. (file-name-nondirectory file-name)
  2394. (if level? "| " "") ;level column, maybe
  2395. (if timestamp "| " "") ;timestamp column, maybe
  2396. (if tags "| " "") ;tags column, maybe
  2397. (if properties ;properties columns, maybe
  2398. (make-string (length properties) ?|)
  2399. "")
  2400. (org-duration-from-minutes file-time)))) ;time
  2401. ;; Get the list of node entries and iterate over it
  2402. (when (> maxlevel 0)
  2403. (pcase-dolist (`(,level ,headline ,tgs ,ts ,time ,props) entries)
  2404. (when narrow-cut-p
  2405. (setq headline
  2406. (if (and (string-match
  2407. (format "\\`%s\\'" org-bracket-link-regexp)
  2408. headline)
  2409. (match-end 3))
  2410. (format "[[%s][%s]]"
  2411. (match-string 1 headline)
  2412. (org-shorten-string (match-string 3 headline)
  2413. narrow))
  2414. (org-shorten-string headline narrow))))
  2415. (cl-flet ((format-field (f) (format (cond ((not emph) "%s |")
  2416. ((= level 1) "*%s* |")
  2417. ((= level 2) "/%s/ |")
  2418. (t "%s |"))
  2419. f)))
  2420. (insert-before-markers
  2421. "|" ;start the table line
  2422. (if multifile "|" "") ;free space for file name column?
  2423. (if level? (format "%d|" level) "") ;level, maybe
  2424. (if timestamp (concat ts "|") "") ;timestamp, maybe
  2425. (if tags (concat (mapconcat #'identity tgs ", ") "|") "") ;tags, maybe
  2426. (if properties ;properties columns, maybe
  2427. (concat (mapconcat (lambda (p) (or (cdr (assoc p props)) ""))
  2428. properties
  2429. "|")
  2430. "|")
  2431. "")
  2432. (if indent ;indentation
  2433. (org-clocktable-indent-string level)
  2434. "")
  2435. (format-field headline)
  2436. ;; Empty fields for higher levels.
  2437. (make-string (max 0 (1- (min time-columns level))) ?|)
  2438. (format-field (org-duration-from-minutes time))
  2439. (make-string (max 0 (- time-columns level)) ?|)
  2440. (if (eq formula '%)
  2441. (format "%.1f |" (* 100 (/ time (float total-time))))
  2442. "")
  2443. "\n")))))))
  2444. (delete-char -1)
  2445. (cond
  2446. ;; Possibly rescue old formula?
  2447. ((or (not formula) (eq formula '%))
  2448. (let ((contents (org-string-nw-p (plist-get params :content))))
  2449. (when (and contents (string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents))
  2450. (setq recalc t)
  2451. (insert "\n" (match-string 1 contents))
  2452. (beginning-of-line 0))))
  2453. ;; Insert specified formula line.
  2454. ((stringp formula)
  2455. (insert "\n#+TBLFM: " formula)
  2456. (setq recalc t))
  2457. (t
  2458. (user-error "Invalid :formula parameter in clocktable")))
  2459. ;; Back to beginning, align the table, recalculate if necessary.
  2460. (goto-char ipos)
  2461. (skip-chars-forward "^|")
  2462. (org-table-align)
  2463. (when org-hide-emphasis-markers
  2464. ;; We need to align a second time.
  2465. (org-table-align))
  2466. (when sort
  2467. (save-excursion
  2468. (org-table-goto-line 3)
  2469. (org-table-goto-column (car sort))
  2470. (org-table-sort-lines nil (cdr sort))))
  2471. (when recalc (org-table-recalculate 'all))
  2472. total-time))
  2473. (defun org-clocktable-indent-string (level)
  2474. "Return indentation string according to LEVEL.
  2475. LEVEL is an integer. Indent by two spaces per level above 1."
  2476. (if (= level 1) ""
  2477. (concat "\\_" (make-string (* 2 (1- level)) ?\s))))
  2478. (defun org-clocktable-increment-day (ts &optional n)
  2479. "Increment day in TS by N (defaulting to 1).
  2480. The TS argument has the same type as the return values of
  2481. `float-time' or `current-time'."
  2482. (let ((tsd (decode-time ts)))
  2483. (cl-incf (nth 3 tsd) (or n 1))
  2484. (setf (nth 8 tsd) nil) ; no time zone: increasing day skips one whole day
  2485. (apply 'encode-time tsd)))
  2486. (defun org-clocktable-steps (params)
  2487. "Step through the range to make a number of clock tables."
  2488. (let* ((ts (plist-get params :tstart))
  2489. (te (plist-get params :tend))
  2490. (ws (plist-get params :wstart))
  2491. (ms (plist-get params :mstart))
  2492. (step0 (plist-get params :step))
  2493. (stepskip0 (plist-get params :stepskip0))
  2494. (block (plist-get params :block))
  2495. cc tsb)
  2496. (when block
  2497. (setq cc (org-clock-special-range block nil t ws ms)
  2498. ts (car cc)
  2499. te (nth 1 cc)))
  2500. (cond
  2501. ((numberp ts)
  2502. ;; If ts is a number, it's an absolute day number from
  2503. ;; org-agenda.
  2504. (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute ts)))
  2505. (setq ts (float-time (encode-time 0 0 0 day month year)))))
  2506. (ts
  2507. (setq ts (float-time (apply #'encode-time (org-parse-time-string ts))))))
  2508. (cond
  2509. ((numberp te)
  2510. ;; Likewise for te.
  2511. (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute te)))
  2512. (setq te (float-time (encode-time 0 0 0 day month year)))))
  2513. (te
  2514. (setq te (float-time (apply #'encode-time (org-parse-time-string te))))))
  2515. (setq tsb
  2516. (if (eq step0 'week)
  2517. (let ((dow (nth 6 (decode-time (seconds-to-time ts)))))
  2518. (if (<= dow ws) ts
  2519. (org-clocktable-increment-day ts ; decrement
  2520. (- ws dow))))
  2521. ts))
  2522. (while (< tsb te)
  2523. (unless (bolp) (insert "\n"))
  2524. (let* ((start-time (seconds-to-time (max tsb ts)))
  2525. (dow (nth 6 (decode-time (seconds-to-time tsb))))
  2526. (days-to-skip (cond ((eq step0 'day) 1)
  2527. ;; else 'week:
  2528. ((= dow ws) 7)
  2529. (t (- ws dow)))))
  2530. (setq tsb (time-to-seconds (org-clocktable-increment-day tsb
  2531. days-to-skip)))
  2532. (insert "\n"
  2533. (if (eq step0 'day) "Daily report: "
  2534. "Weekly report starting on: ")
  2535. (format-time-string (org-time-stamp-format nil t) start-time)
  2536. "\n")
  2537. (let ((table-begin (line-beginning-position 0))
  2538. (step-time
  2539. (org-dblock-write:clocktable
  2540. (org-combine-plists
  2541. params
  2542. (list
  2543. :header "" :step nil :block nil
  2544. :tstart (format-time-string (org-time-stamp-format t t)
  2545. start-time)
  2546. :tend (format-time-string (org-time-stamp-format t t)
  2547. (seconds-to-time (min te tsb))))))))
  2548. (re-search-forward "^[ \t]*#\\+END:")
  2549. (when (and stepskip0 (equal step-time 0))
  2550. ;; Remove the empty table
  2551. (delete-region (line-beginning-position) table-begin))))
  2552. (end-of-line 0))))
  2553. (defun org-clock-get-table-data (file params)
  2554. "Get the clocktable data for file FILE, with parameters PARAMS.
  2555. FILE is only for identification - this function assumes that
  2556. the correct buffer is current, and that the wanted restriction is
  2557. in place.
  2558. The return value will be a list with the file name and the total
  2559. file time (in minutes) as 1st and 2nd elements. The third element
  2560. of this list will be a list of headline entries. Each entry has the
  2561. following structure:
  2562. (LEVEL HEADLINE TAGS TIMESTAMP TIME PROPERTIES)
  2563. LEVEL: The level of the headline, as an integer. This will be
  2564. the reduced level, so 1,2,3,... even if only odd levels
  2565. are being used.
  2566. HEADLINE: The text of the headline. Depending on PARAMS, this may
  2567. already be formatted like a link.
  2568. TAGS: The list of tags of the headline.
  2569. TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
  2570. entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
  2571. in this sequence.
  2572. TIME: The sum of all time spend in this tree, in minutes. This time
  2573. will of cause be restricted to the time block and tags match
  2574. specified in PARAMS.
  2575. PROPERTIES: The list properties specified in the `:properties' parameter
  2576. along with their value, as an alist following the pattern
  2577. (NAME . VALUE)."
  2578. (let* ((maxlevel (or (plist-get params :maxlevel) 3))
  2579. (timestamp (plist-get params :timestamp))
  2580. (ts (plist-get params :tstart))
  2581. (te (plist-get params :tend))
  2582. (ws (plist-get params :wstart))
  2583. (ms (plist-get params :mstart))
  2584. (block (plist-get params :block))
  2585. (link (plist-get params :link))
  2586. (tags (plist-get params :tags))
  2587. (match (plist-get params :match))
  2588. (properties (plist-get params :properties))
  2589. (inherit-property-p (plist-get params :inherit-props))
  2590. (matcher (and match (cdr (org-make-tags-matcher match))))
  2591. cc st p tbl)
  2592. (setq org-clock-file-total-minutes nil)
  2593. (when block
  2594. (setq cc (org-clock-special-range block nil t ws ms)
  2595. ts (car cc)
  2596. te (nth 1 cc)))
  2597. (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
  2598. (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
  2599. (when (and ts (listp ts))
  2600. (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
  2601. (when (and te (listp te))
  2602. (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
  2603. ;; Now the times are strings we can parse.
  2604. (if ts (setq ts (org-matcher-time ts)))
  2605. (if te (setq te (org-matcher-time te)))
  2606. (save-excursion
  2607. (org-clock-sum ts te
  2608. (when matcher
  2609. `(lambda ()
  2610. (let* ((todo (org-get-todo-state))
  2611. (tags-list (org-get-tags))
  2612. (org-scanner-tags tags-list)
  2613. (org-trust-scanner-tags t))
  2614. (funcall ,matcher todo tags-list nil)))))
  2615. (goto-char (point-min))
  2616. (setq st t)
  2617. (while (or (and (bobp) (prog1 st (setq st nil))
  2618. (get-text-property (point) :org-clock-minutes)
  2619. (setq p (point-min)))
  2620. (setq p (next-single-property-change
  2621. (point) :org-clock-minutes)))
  2622. (goto-char p)
  2623. (let ((time (get-text-property p :org-clock-minutes)))
  2624. (when (and time (> time 0) (org-at-heading-p))
  2625. (let ((level (org-reduced-level (org-current-level))))
  2626. (when (<= level maxlevel)
  2627. (let* ((headline (org-get-heading t t t t))
  2628. (hdl
  2629. (if (not link) headline
  2630. (let ((search
  2631. (org-make-org-heading-search-string headline)))
  2632. (org-make-link-string
  2633. (if (not (buffer-file-name)) search
  2634. (format "file:%s::%s" (buffer-file-name) search))
  2635. ;; Prune statistics cookies. Replace
  2636. ;; links with their description, or
  2637. ;; a plain link if there is none.
  2638. (org-trim
  2639. (org-link-display-format
  2640. (replace-regexp-in-string
  2641. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  2642. headline)))))))
  2643. (tgs (and tags (org-get-tags)))
  2644. (tsp
  2645. (and timestamp
  2646. (cl-some (lambda (p) (org-entry-get (point) p))
  2647. '("SCHEDULED" "DEADLINE" "TIMESTAMP"
  2648. "TIMESTAMP_IA"))))
  2649. (props
  2650. (and properties
  2651. (delq nil
  2652. (mapcar
  2653. (lambda (p)
  2654. (let ((v (org-entry-get
  2655. (point) p inherit-property-p)))
  2656. (and v (cons p v))))
  2657. properties)))))
  2658. (push (list level hdl tgs tsp time props) tbl)))))))
  2659. (list file org-clock-file-total-minutes (nreverse tbl)))))
  2660. ;; Saving and loading the clock
  2661. (defvar org-clock-loaded nil
  2662. "Was the clock file loaded?")
  2663. ;;;###autoload
  2664. (defun org-clock-update-time-maybe ()
  2665. "If this is a CLOCK line, update it and return t.
  2666. Otherwise, return nil."
  2667. (interactive)
  2668. (save-excursion
  2669. (beginning-of-line 1)
  2670. (skip-chars-forward " \t")
  2671. (when (looking-at org-clock-string)
  2672. (let ((re (concat "[ \t]*" org-clock-string
  2673. " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
  2674. "\\([ \t]*=>.*\\)?\\)?"))
  2675. ts te h m s neg)
  2676. (cond
  2677. ((not (looking-at re))
  2678. nil)
  2679. ((not (match-end 2))
  2680. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  2681. (> org-clock-marker (point))
  2682. (<= org-clock-marker (point-at-eol)))
  2683. ;; The clock is running here
  2684. (setq org-clock-start-time
  2685. (apply 'encode-time
  2686. (org-parse-time-string (match-string 1))))
  2687. (org-clock-update-mode-line)))
  2688. (t
  2689. (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
  2690. (end-of-line 1)
  2691. (setq ts (match-string 1)
  2692. te (match-string 3))
  2693. (setq s (- (float-time
  2694. (apply #'encode-time (org-parse-time-string te)))
  2695. (float-time
  2696. (apply #'encode-time (org-parse-time-string ts))))
  2697. neg (< s 0)
  2698. s (abs s)
  2699. h (floor (/ s 3600))
  2700. s (- s (* 3600 h))
  2701. m (floor (/ s 60))
  2702. s (- s (* 60 s)))
  2703. (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
  2704. t))))))
  2705. (defun org-clock-save ()
  2706. "Persist various clock-related data to disk.
  2707. The details of what will be saved are regulated by the variable
  2708. `org-clock-persist'."
  2709. (when (and org-clock-persist
  2710. (or org-clock-loaded
  2711. org-clock-has-been-used
  2712. (not (file-exists-p org-clock-persist-file))))
  2713. (with-temp-file org-clock-persist-file
  2714. (insert (format ";; %s - %s at %s\n"
  2715. (file-name-nondirectory org-clock-persist-file)
  2716. (system-name)
  2717. (format-time-string (org-time-stamp-format t))))
  2718. ;; Store clock to be resumed.
  2719. (when (and (memq org-clock-persist '(t clock))
  2720. (let ((b (org-base-buffer (org-clocking-buffer))))
  2721. (and (buffer-live-p b)
  2722. (buffer-file-name b)
  2723. (or (not org-clock-persist-query-save)
  2724. (y-or-n-p (format "Save current clock (%s) "
  2725. org-clock-heading))))))
  2726. (insert
  2727. (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
  2728. (buffer-file-name (org-base-buffer (org-clocking-buffer)))
  2729. (marker-position org-clock-marker))))
  2730. ;; Store clocked task history. Tasks are stored reversed to
  2731. ;; make reading simpler.
  2732. (when (and (memq org-clock-persist '(t history))
  2733. org-clock-history)
  2734. (insert
  2735. (format "(setq org-clock-stored-history '(%s))\n"
  2736. (mapconcat
  2737. (lambda (m)
  2738. (let ((b (org-base-buffer (marker-buffer m))))
  2739. (when (and (buffer-live-p b)
  2740. (buffer-file-name b))
  2741. (format "(%S . %d)"
  2742. (buffer-file-name b)
  2743. (marker-position m)))))
  2744. (reverse org-clock-history)
  2745. " ")))))))
  2746. (defun org-clock-load ()
  2747. "Load clock-related data from disk, maybe resuming a stored clock."
  2748. (when (and org-clock-persist (not org-clock-loaded))
  2749. (if (not (file-readable-p org-clock-persist-file))
  2750. (message "Not restoring clock data; %S not found" org-clock-persist-file)
  2751. (message "Restoring clock data")
  2752. ;; Load history.
  2753. (load-file org-clock-persist-file)
  2754. (setq org-clock-loaded t)
  2755. (pcase-dolist (`(,(and file (pred file-exists-p)) . ,position)
  2756. org-clock-stored-history)
  2757. (org-clock-history-push position (find-file-noselect file)))
  2758. ;; Resume clock.
  2759. (pcase org-clock-stored-resume-clock
  2760. (`(,(and file (pred file-exists-p)) . ,position)
  2761. (with-current-buffer (find-file-noselect file)
  2762. (when (or (not org-clock-persist-query-resume)
  2763. (y-or-n-p (format "Resume clock (%s) "
  2764. (save-excursion
  2765. (goto-char position)
  2766. (org-get-heading t t)))))
  2767. (goto-char position)
  2768. (let ((org-clock-in-resume 'auto-restart)
  2769. (org-clock-auto-clock-resolution nil))
  2770. (org-clock-in)
  2771. (when (org-invisible-p) (org-show-context))))))
  2772. (_ nil)))))
  2773. ;; Suggested bindings
  2774. (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
  2775. (provide 'org-clock)
  2776. ;; Local variables:
  2777. ;; generated-autoload-file: "org-loaddefs.el"
  2778. ;; coding: utf-8
  2779. ;; End:
  2780. ;;; org-clock.el ends here