org-clock.el 109 KB

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