org-clock.el 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006
  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. (defvar org-frame-title-format-backup frame-title-format)
  32. (defvar org-state)
  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)
  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. :package-version '(Org . "9.2")
  295. :type 'plist)
  296. (defcustom org-clock-idle-time nil
  297. "When non-nil, resolve open clocks if the user is idle more than X minutes."
  298. :group 'org-clock
  299. :type '(choice
  300. (const :tag "Never" nil)
  301. (integer :tag "After N minutes")))
  302. (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
  303. "When to automatically resolve open clocks found in Org buffers."
  304. :group 'org-clock
  305. :type '(choice
  306. (const :tag "Never" nil)
  307. (const :tag "Always" t)
  308. (const :tag "When no clock is running" when-no-clock-is-running)))
  309. (defcustom org-clock-report-include-clocking-task nil
  310. "When non-nil, include the current clocking task time in clock reports."
  311. :group 'org-clock
  312. :version "24.1"
  313. :type 'boolean)
  314. (defcustom org-clock-resolve-expert nil
  315. "Non-nil means do not show the splash buffer with the clock resolver."
  316. :group 'org-clock
  317. :version "24.1"
  318. :type 'boolean)
  319. (defcustom org-clock-continuously nil
  320. "Non-nil means to start clocking from the last clock-out time, if any."
  321. :type 'boolean
  322. :version "24.1"
  323. :group 'org-clock)
  324. (defcustom org-clock-total-time-cell-format "*%s*"
  325. "Format string for the total time cells."
  326. :group 'org-clock
  327. :version "24.1"
  328. :type 'string)
  329. (defcustom org-clock-file-time-cell-format "*%s*"
  330. "Format string for the file time cells."
  331. :group 'org-clock
  332. :version "24.1"
  333. :type 'string)
  334. (defcustom org-clock-clocked-in-display 'mode-line
  335. "When clocked in for a task, Org can display the current
  336. task and accumulated time in the mode line and/or frame title.
  337. Allowed values are:
  338. both displays in both mode line and frame title
  339. mode-line displays only in mode line (default)
  340. frame-title displays only in frame title
  341. nil current clock is not displayed"
  342. :group 'org-clock
  343. :type '(choice
  344. (const :tag "Mode line" mode-line)
  345. (const :tag "Frame title" frame-title)
  346. (const :tag "Both" both)
  347. (const :tag "None" nil)))
  348. (defcustom org-clock-frame-title-format '(t org-mode-line-string)
  349. "The value for `frame-title-format' when clocking in.
  350. When `org-clock-clocked-in-display' is set to `frame-title'
  351. or `both', clocking in will replace `frame-title-format' with
  352. this value. Clocking out will restore `frame-title-format'.
  353. `org-frame-title-string' is a format string using the same
  354. specifications than `frame-title-format', which see."
  355. :version "24.1"
  356. :group 'org-clock
  357. :type 'sexp)
  358. (defcustom org-clock-x11idle-program-name "x11idle"
  359. "Name of the program which prints X11 idle time in milliseconds.
  360. You can find x11idle.c in the contrib/scripts directory of the
  361. Org git distribution. Or, you can do:
  362. sudo apt-get install xprintidle
  363. if you are using Debian."
  364. :group 'org-clock
  365. :version "24.4"
  366. :package-version '(Org . "8.0")
  367. :type 'string)
  368. (defcustom org-clock-goto-before-context 2
  369. "Number of lines of context to display before currently clocked-in entry.
  370. This applies when using `org-clock-goto'."
  371. :group 'org-clock
  372. :type 'integer)
  373. (defcustom org-clock-display-default-range 'thisyear
  374. "Default range when displaying clocks with `org-clock-display'.
  375. Valid values are: `today', `yesterday', `thisweek', `lastweek',
  376. `thismonth', `lastmonth', `thisyear', `lastyear' and `untilnow'."
  377. :group 'org-clock
  378. :type '(choice (const today)
  379. (const yesterday)
  380. (const thisweek)
  381. (const lastweek)
  382. (const thismonth)
  383. (const lastmonth)
  384. (const thisyear)
  385. (const lastyear)
  386. (const untilnow)
  387. (const :tag "Select range interactively" interactive))
  388. :safe #'symbolp)
  389. (defvar org-clock-in-prepare-hook nil
  390. "Hook run when preparing the clock.
  391. This hook is run before anything happens to the task that
  392. you want to clock in. For example, you can use this hook
  393. to add an effort property.")
  394. (defvar org-clock-in-hook nil
  395. "Hook run when starting the clock.")
  396. (defvar org-clock-out-hook nil
  397. "Hook run when stopping the current clock.")
  398. (defvar org-clock-cancel-hook nil
  399. "Hook run when canceling the current clock.")
  400. (defvar org-clock-goto-hook nil
  401. "Hook run when selecting the currently clocked-in entry.")
  402. (defvar org-clock-has-been-used nil
  403. "Has the clock been used during the current Emacs session?")
  404. (defvar org-clock-stored-history nil
  405. "Clock history, populated by `org-clock-load'")
  406. (defvar org-clock-stored-resume-clock nil
  407. "Clock to resume, saved by `org-clock-load'")
  408. ;;; The clock for measuring work time.
  409. (defvar org-mode-line-string "")
  410. (put 'org-mode-line-string 'risky-local-variable t)
  411. (defvar org-clock-mode-line-timer nil)
  412. (defvar org-clock-idle-timer nil)
  413. (defvar org-clock-heading) ; defined in org.el
  414. (defvar org-clock-start-time "")
  415. (defvar org-clock-leftover-time nil
  416. "If non-nil, user canceled a clock; this is when leftover time started.")
  417. (defvar org-clock-effort ""
  418. "Effort estimate of the currently clocking task.")
  419. (defvar org-clock-total-time nil
  420. "Holds total time, spent previously on currently clocked item.
  421. This does not include the time in the currently running clock.")
  422. (defvar org-clock-history nil
  423. "List of marker pointing to recent clocked tasks.")
  424. (defvar org-clock-default-task (make-marker)
  425. "Marker pointing to the default task that should clock time.
  426. The clock can be made to switch to this task after clocking out
  427. of a different task.")
  428. (defvar org-clock-interrupted-task (make-marker)
  429. "Marker pointing to the task that has been interrupted by the current clock.")
  430. (defvar org-clock-mode-line-map (make-sparse-keymap))
  431. (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
  432. (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
  433. (defun org-clock--translate (s language)
  434. "Translate string S into using string LANGUAGE.
  435. Assume S in the English term to translate. Return S as-is if it
  436. cannot be translated."
  437. (or (nth (pcase s
  438. ("File" 1) ("L" 2) ("Timestamp" 3) ("Headline" 4) ("Time" 5)
  439. ("ALL" 6) ("Total time" 7) ("File time" 8) ("Clock summary at" 9))
  440. (assoc-string language org-clock-clocktable-language-setup t))
  441. s))
  442. (defun org-clock--mode-line-heading ()
  443. "Return currently clocked heading, formatted for mode line."
  444. (cond ((functionp org-clock-heading-function)
  445. (funcall org-clock-heading-function))
  446. ((org-before-first-heading-p) "???")
  447. (t (replace-regexp-in-string
  448. org-bracket-link-analytic-regexp "\\5"
  449. (org-no-properties (org-get-heading t t t t))))))
  450. (defun org-clock-menu ()
  451. (interactive)
  452. (popup-menu
  453. '("Clock"
  454. ["Clock out" org-clock-out t]
  455. ["Change effort estimate" org-clock-modify-effort-estimate t]
  456. ["Go to clock entry" org-clock-goto t]
  457. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
  458. (defun org-clock-history-push (&optional pos buffer)
  459. "Push a marker to the clock history."
  460. (setq org-clock-history-length (max 1 org-clock-history-length))
  461. (let ((m (move-marker (make-marker)
  462. (or pos (point)) (org-base-buffer
  463. (or buffer (current-buffer)))))
  464. n l)
  465. (while (setq n (member m org-clock-history))
  466. (move-marker (car n) nil))
  467. (setq org-clock-history
  468. (delq nil
  469. (mapcar (lambda (x) (if (marker-buffer x) x nil))
  470. org-clock-history)))
  471. (when (>= (setq l (length org-clock-history)) org-clock-history-length)
  472. (setq org-clock-history
  473. (nreverse
  474. (nthcdr (- l org-clock-history-length -1)
  475. (nreverse org-clock-history)))))
  476. (push m org-clock-history)))
  477. (defun org-clock-save-markers-for-cut-and-paste (beg end)
  478. "Save relative positions of markers in region."
  479. (org-check-and-save-marker org-clock-marker beg end)
  480. (org-check-and-save-marker org-clock-hd-marker beg end)
  481. (org-check-and-save-marker org-clock-default-task beg end)
  482. (org-check-and-save-marker org-clock-interrupted-task beg end)
  483. (dolist (m org-clock-history)
  484. (org-check-and-save-marker m beg end)))
  485. (defun org-clock-drawer-name ()
  486. "Return clock drawer's name for current entry, or nil."
  487. (let ((drawer (org-clock-into-drawer)))
  488. (cond ((integerp drawer)
  489. (let ((log-drawer (org-log-into-drawer)))
  490. (if (stringp log-drawer) log-drawer "LOGBOOK")))
  491. ((stringp drawer) drawer)
  492. (t nil))))
  493. (defun org-clocking-buffer ()
  494. "Return the clocking buffer if we are currently clocking a task or nil."
  495. (marker-buffer org-clock-marker))
  496. (defun org-clocking-p ()
  497. "Return t when clocking a task."
  498. (not (equal (org-clocking-buffer) nil)))
  499. (defvar org-clock-before-select-task-hook nil
  500. "Hook called in task selection just before prompting the user.")
  501. (defun org-clock-select-task (&optional prompt)
  502. "Select a task that was recently associated with clocking.
  503. Return marker position of the selected task. Raise an error if
  504. there is no recent clock to choose from."
  505. (let (och chl sel-list rpl (i 0) s)
  506. ;; Remove successive dups from the clock history to consider
  507. (dolist (c org-clock-history)
  508. (unless (equal c (car och)) (push c och)))
  509. (setq och (reverse och) chl (length och))
  510. (if (zerop chl)
  511. (user-error "No recent clock")
  512. (save-window-excursion
  513. (org-switch-to-buffer-other-window
  514. (get-buffer-create "*Clock Task Select*"))
  515. (erase-buffer)
  516. (when (marker-buffer org-clock-default-task)
  517. (insert (org-add-props "Default Task\n" nil 'face 'bold))
  518. (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
  519. (push s sel-list))
  520. (when (marker-buffer org-clock-interrupted-task)
  521. (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
  522. (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
  523. (push s sel-list))
  524. (when (org-clocking-p)
  525. (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
  526. (setq s (org-clock-insert-selection-line ?c org-clock-marker))
  527. (push s sel-list))
  528. (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
  529. (dolist (m och)
  530. (when (marker-buffer m)
  531. (setq i (1+ i)
  532. s (org-clock-insert-selection-line
  533. (if (< i 10)
  534. (+ i ?0)
  535. (+ i (- ?A 10))) m))
  536. (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
  537. (push s sel-list)))
  538. (run-hooks 'org-clock-before-select-task-hook)
  539. (goto-char (point-min))
  540. ;; Set min-height relatively to circumvent a possible but in
  541. ;; `fit-window-to-buffer'
  542. (fit-window-to-buffer nil nil (if (< chl 10) chl (+ 5 chl)))
  543. (message (or prompt "Select task for clocking:"))
  544. (setq cursor-type nil rpl (read-char-exclusive))
  545. (kill-buffer)
  546. (cond
  547. ((eq rpl ?q) nil)
  548. ((eq rpl ?x) nil)
  549. ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
  550. (t (user-error "Invalid task choice %c" rpl)))))))
  551. (defun org-clock-insert-selection-line (i marker)
  552. "Insert a line for the clock selection menu.
  553. And return a cons cell with the selection character integer and the marker
  554. pointing to it."
  555. (when (marker-buffer marker)
  556. (let (cat task heading prefix)
  557. (with-current-buffer (org-base-buffer (marker-buffer marker))
  558. (org-with-wide-buffer
  559. (ignore-errors
  560. (goto-char marker)
  561. (setq cat (org-get-category)
  562. heading (org-get-heading 'notags)
  563. prefix (save-excursion
  564. (org-back-to-heading t)
  565. (looking-at org-outline-regexp)
  566. (match-string 0))
  567. task (substring
  568. (org-fontify-like-in-org-mode
  569. (concat prefix heading)
  570. org-odd-levels-only)
  571. (length prefix))))))
  572. (when (and cat task)
  573. (insert (format "[%c] %-12s %s\n" i cat task))
  574. (cons i marker)))))
  575. (defvar org-clock-task-overrun nil
  576. "Internal flag indicating if the clock has overrun the planned time.")
  577. (defvar org-clock-update-period 60
  578. "Number of seconds between mode line clock string updates.")
  579. (defun org-clock-get-clock-string ()
  580. "Form a clock-string, that will be shown in the mode line.
  581. If an effort estimate was defined for the current item, use
  582. 01:30/01:50 format (clocked/estimated).
  583. If not, show simply the clocked time like 01:50."
  584. (let ((clocked-time (org-clock-get-clocked-time)))
  585. (if org-clock-effort
  586. (let* ((effort-in-minutes (org-duration-to-minutes org-clock-effort))
  587. (work-done-str
  588. (propertize (org-duration-from-minutes clocked-time)
  589. 'face
  590. (if (and org-clock-task-overrun
  591. (not org-clock-task-overrun-text))
  592. 'org-mode-line-clock-overrun
  593. 'org-mode-line-clock)))
  594. (effort-str (org-duration-from-minutes effort-in-minutes)))
  595. (format (propertize " [%s/%s] (%s)" 'face 'org-mode-line-clock)
  596. work-done-str effort-str org-clock-heading))
  597. (format (propertize " [%s] (%s)" 'face 'org-mode-line-clock)
  598. (org-duration-from-minutes clocked-time)
  599. org-clock-heading))))
  600. (defun org-clock-get-last-clock-out-time ()
  601. "Get the last clock-out time for the current subtree."
  602. (save-excursion
  603. (let ((end (save-excursion (org-end-of-subtree))))
  604. (when (re-search-forward (concat org-clock-string
  605. ".*\\]--\\(\\[[^]]+\\]\\)") end t)
  606. (org-time-string-to-time (match-string 1))))))
  607. (defun org-clock-update-mode-line (&optional refresh)
  608. "Update mode line with clock information.
  609. When optional argument is non-nil, refresh cached heading."
  610. (if org-clock-effort
  611. (org-clock-notify-once-if-expired)
  612. (setq org-clock-task-overrun nil))
  613. (when refresh (setq org-clock-heading (org-clock--mode-line-heading)))
  614. (setq org-mode-line-string
  615. (propertize
  616. (let ((clock-string (org-clock-get-clock-string))
  617. (help-text "Org mode clock is running.\nmouse-1 shows a \
  618. menu\nmouse-2 will jump to task"))
  619. (if (and (> org-clock-string-limit 0)
  620. (> (length clock-string) org-clock-string-limit))
  621. (propertize
  622. (substring clock-string 0 org-clock-string-limit)
  623. 'help-echo (concat help-text ": " org-clock-heading))
  624. (propertize clock-string 'help-echo help-text)))
  625. 'local-map org-clock-mode-line-map
  626. 'mouse-face 'mode-line-highlight))
  627. (if (and org-clock-task-overrun org-clock-task-overrun-text)
  628. (setq org-mode-line-string
  629. (concat (propertize
  630. org-clock-task-overrun-text
  631. 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
  632. (force-mode-line-update))
  633. (defun org-clock-get-clocked-time ()
  634. "Get the clocked time for the current item in minutes.
  635. The time returned includes the time spent on this task in
  636. previous clocking intervals."
  637. (let ((currently-clocked-time
  638. (floor (org-time-convert-to-integer
  639. (org-time-since org-clock-start-time))
  640. 60)))
  641. (+ currently-clocked-time (or org-clock-total-time 0))))
  642. (defun org-clock-modify-effort-estimate (&optional value)
  643. "Add to or set the effort estimate of the item currently being clocked.
  644. VALUE can be a number of minutes, or a string with format hh:mm or mm.
  645. When the string starts with a + or a - sign, the current value of the effort
  646. property will be changed by that amount. If the effort value is expressed
  647. as an unit defined in `org-duration-units' (e.g. \"3h\"), the modified
  648. value will be converted to a hh:mm duration.
  649. This command will update the \"Effort\" property of the currently
  650. clocked item, and the value displayed in the mode line."
  651. (interactive)
  652. (if (org-clock-is-active)
  653. (let ((current org-clock-effort) sign)
  654. (unless value
  655. ;; Prompt user for a value or a change
  656. (setq value
  657. (read-string
  658. (format "Set effort (hh:mm or mm%s): "
  659. (if current
  660. (format ", prefix + to add to %s" org-clock-effort)
  661. "")))))
  662. (when (stringp value)
  663. ;; A string. See if it is a delta
  664. (setq sign (string-to-char value))
  665. (if (member sign '(?- ?+))
  666. (setq current (org-duration-to-minutes current)
  667. value (substring value 1))
  668. (setq current 0))
  669. (setq value (org-duration-to-minutes value))
  670. (if (equal ?- sign)
  671. (setq value (- current value))
  672. (if (equal ?+ sign) (setq value (+ current value)))))
  673. (setq value (max 0 value)
  674. org-clock-effort (org-duration-from-minutes value))
  675. (org-entry-put org-clock-marker "Effort" org-clock-effort)
  676. (org-clock-update-mode-line)
  677. (message "Effort is now %s" org-clock-effort))
  678. (message "Clock is not currently active")))
  679. (defvar org-clock-notification-was-shown nil
  680. "Shows if we have shown notification already.")
  681. (defun org-clock-notify-once-if-expired ()
  682. "Show notification if we spent more time than we estimated before.
  683. Notification is shown only once."
  684. (when (org-clocking-p)
  685. (let ((effort-in-minutes (org-duration-to-minutes org-clock-effort))
  686. (clocked-time (org-clock-get-clocked-time)))
  687. (if (setq org-clock-task-overrun
  688. (if (or (null effort-in-minutes) (zerop effort-in-minutes))
  689. nil
  690. (>= clocked-time effort-in-minutes)))
  691. (unless org-clock-notification-was-shown
  692. (setq org-clock-notification-was-shown t)
  693. (org-notify
  694. (format-message "Task `%s' should be finished by now. (%s)"
  695. org-clock-heading org-clock-effort)
  696. org-clock-sound))
  697. (setq org-clock-notification-was-shown nil)))))
  698. (defun org-notify (notification &optional play-sound)
  699. "Send a NOTIFICATION and maybe PLAY-SOUND.
  700. If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
  701. (org-show-notification notification)
  702. (if play-sound (org-clock-play-sound play-sound)))
  703. (defun org-show-notification (notification)
  704. "Show notification.
  705. Use `org-show-notification-handler' if defined,
  706. use libnotify if available, or fall back on a message."
  707. (cond ((functionp org-show-notification-handler)
  708. (funcall org-show-notification-handler notification))
  709. ((stringp org-show-notification-handler)
  710. (start-process "emacs-timer-notification" nil
  711. org-show-notification-handler notification))
  712. ((fboundp 'notifications-notify)
  713. (notifications-notify
  714. :title "Org mode message"
  715. :body notification
  716. ;; FIXME how to link to the Org icon?
  717. ;; :app-icon "~/.emacs.d/icons/mail.png"
  718. :urgency 'low))
  719. ((executable-find "notify-send")
  720. (start-process "emacs-timer-notification" nil
  721. "notify-send" notification))
  722. ;; Maybe the handler will send a message, so only use message as
  723. ;; a fall back option
  724. (t (message "%s" notification))))
  725. (defun org-clock-play-sound (&optional clock-sound)
  726. "Play sound as configured by `org-clock-sound'.
  727. Use alsa's aplay tool if available.
  728. If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
  729. (let ((org-clock-sound (or clock-sound org-clock-sound)))
  730. (cond
  731. ((not org-clock-sound))
  732. ((eq org-clock-sound t) (beep t) (beep t))
  733. ((stringp org-clock-sound)
  734. (let ((file (expand-file-name org-clock-sound)))
  735. (if (file-exists-p file)
  736. (if (executable-find "aplay")
  737. (start-process "org-clock-play-notification" nil
  738. "aplay" file)
  739. (condition-case nil
  740. (play-sound-file file)
  741. (error (beep t) (beep t))))))))))
  742. (defvar org-clock-mode-line-entry nil
  743. "Information for the mode line about the running clock.")
  744. (defun org-find-open-clocks (file)
  745. "Search through the given file and find all open clocks."
  746. (let ((buf (or (get-file-buffer file)
  747. (find-file-noselect file)))
  748. (org-clock-re (concat org-clock-string " \\(\\[.*?\\]\\)$"))
  749. clocks)
  750. (with-current-buffer buf
  751. (save-excursion
  752. (goto-char (point-min))
  753. (while (re-search-forward org-clock-re nil t)
  754. (push (cons (copy-marker (match-end 1) t)
  755. (org-time-string-to-time (match-string 1))) clocks))))
  756. clocks))
  757. (defsubst org-is-active-clock (clock)
  758. "Return t if CLOCK is the currently active clock."
  759. (and (org-clock-is-active)
  760. (= org-clock-marker (car clock))))
  761. (defmacro org-with-clock-position (clock &rest forms)
  762. "Evaluate FORMS with CLOCK as the current active clock."
  763. `(with-current-buffer (marker-buffer (car ,clock))
  764. (org-with-wide-buffer
  765. (goto-char (car ,clock))
  766. (beginning-of-line)
  767. ,@forms)))
  768. (def-edebug-spec org-with-clock-position (form body))
  769. (put 'org-with-clock-position 'lisp-indent-function 1)
  770. (defmacro org-with-clock (clock &rest forms)
  771. "Evaluate FORMS with CLOCK as the current active clock.
  772. This macro also protects the current active clock from being altered."
  773. `(org-with-clock-position ,clock
  774. (let ((org-clock-start-time (cdr ,clock))
  775. (org-clock-total-time)
  776. (org-clock-history)
  777. (org-clock-effort)
  778. (org-clock-marker (car ,clock))
  779. (org-clock-hd-marker (save-excursion
  780. (org-back-to-heading t)
  781. (point-marker))))
  782. ,@forms)))
  783. (def-edebug-spec org-with-clock (form body))
  784. (put 'org-with-clock 'lisp-indent-function 1)
  785. (defsubst org-clock-clock-in (clock &optional resume start-time)
  786. "Clock in to the clock located by CLOCK.
  787. If necessary, clock-out of the currently active clock."
  788. (org-with-clock-position clock
  789. (let ((org-clock-in-resume (or resume org-clock-in-resume)))
  790. (org-clock-in nil start-time))))
  791. (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
  792. "Clock out of the clock located by CLOCK."
  793. (let ((temp (copy-marker (car clock)
  794. (marker-insertion-type (car clock)))))
  795. (if (org-is-active-clock clock)
  796. (org-clock-out nil fail-quietly at-time)
  797. (org-with-clock clock
  798. (org-clock-out nil fail-quietly at-time)))
  799. (setcar clock temp)))
  800. (defsubst org-clock-clock-cancel (clock)
  801. "Cancel the clock located by CLOCK."
  802. (let ((temp (copy-marker (car clock)
  803. (marker-insertion-type (car clock)))))
  804. (if (org-is-active-clock clock)
  805. (org-clock-cancel)
  806. (org-with-clock clock
  807. (org-clock-cancel)))
  808. (setcar clock temp)))
  809. (defvar org-clock-clocking-in nil)
  810. (defvar org-clock-resolving-clocks nil)
  811. (defvar org-clock-resolving-clocks-due-to-idleness nil)
  812. (defun org-clock-resolve-clock
  813. (clock resolve-to clock-out-time close restart fail-quietly)
  814. "Resolve CLOCK given the time RESOLVE-TO, and the present.
  815. CLOCK is a cons cell of the form (MARKER START-TIME)."
  816. (let ((org-clock-resolving-clocks t)
  817. ;; If the clocked entry contained only a clock and possibly
  818. ;; the associated drawer, and we either cancel it or clock it
  819. ;; out, `org-clock-out-remove-zero-time-clocks' may clear all
  820. ;; contents, and leave point on the /next/ headline. We store
  821. ;; the current entry location to be able to get back here when
  822. ;; we need to clock in again the previously clocked task.
  823. (heading (org-with-point-at (car clock)
  824. (org-back-to-heading t)
  825. (point-marker))))
  826. (pcase resolve-to
  827. (`nil
  828. (org-clock-clock-cancel clock)
  829. (when (and restart (not org-clock-clocking-in))
  830. (org-with-point-at heading (org-clock-in))))
  831. (`now
  832. (cond
  833. (restart (error "RESTART is not valid here"))
  834. ((or close org-clock-clocking-in)
  835. (org-clock-clock-out clock fail-quietly))
  836. ((org-is-active-clock clock) nil)
  837. (t (org-clock-clock-in clock t))))
  838. ((pred (org-time-less-p nil))
  839. (error "RESOLVE-TO must refer to a time in the past"))
  840. (_
  841. (when restart (error "RESTART is not valid here"))
  842. (org-clock-clock-out clock fail-quietly (or clock-out-time resolve-to))
  843. (cond
  844. (org-clock-clocking-in nil)
  845. (close
  846. (setq org-clock-leftover-time (and (null clock-out-time) resolve-to)))
  847. (t
  848. (org-with-point-at heading
  849. (org-clock-in nil (and clock-out-time resolve-to)))))))))
  850. (defun org-clock-jump-to-current-clock (&optional effective-clock)
  851. "When an Org clock is running, jump to it."
  852. (let ((drawer (org-clock-into-drawer))
  853. (clock (or effective-clock (cons org-clock-marker
  854. org-clock-start-time))))
  855. (unless (marker-buffer (car clock))
  856. (user-error "No Org clock is currently running"))
  857. (org-with-clock clock (org-clock-goto))
  858. (with-current-buffer (marker-buffer (car clock))
  859. (goto-char (car clock))
  860. (when drawer
  861. (org-with-wide-buffer
  862. (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$"
  863. (regexp-quote (if (stringp drawer) drawer "LOGBOOK"))))
  864. (beg (save-excursion (org-back-to-heading t) (point))))
  865. (catch 'exit
  866. (while (re-search-backward drawer-re beg t)
  867. (let ((element (org-element-at-point)))
  868. (when (eq (org-element-type element) 'drawer)
  869. (when (> (org-element-property :end element) (car clock))
  870. (org-flag-drawer nil element))
  871. (throw 'exit nil)))))))))))
  872. (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
  873. "Resolve an open Org clock.
  874. An open clock was found, with `dangling' possibly being non-nil.
  875. If this function was invoked with a prefix argument, non-dangling
  876. open clocks are ignored. The given clock requires some sort of
  877. user intervention to resolve it, either because a clock was left
  878. dangling or due to an idle timeout. The clock resolution can
  879. either be:
  880. (a) deleted, the user doesn't care about the clock
  881. (b) restarted from the current time (if no other clock is open)
  882. (c) closed, giving the clock X minutes
  883. (d) closed and then restarted
  884. (e) resumed, as if the user had never left
  885. The format of clock is (CONS MARKER START-TIME), where MARKER
  886. identifies the buffer and position the clock is open at (and
  887. thus, the heading it's under), and START-TIME is when the clock
  888. was started."
  889. (cl-assert clock)
  890. (let* ((ch
  891. (save-window-excursion
  892. (save-excursion
  893. (unless org-clock-resolving-clocks-due-to-idleness
  894. (org-clock-jump-to-current-clock clock))
  895. (unless org-clock-resolve-expert
  896. (with-output-to-temp-buffer "*Org Clock*"
  897. (princ (format-message "Select a Clock Resolution Command:
  898. i/q Ignore this question; the same as keeping all the idle time.
  899. k/K Keep X minutes of the idle time (default is all). If this
  900. amount is less than the default, you will be clocked out
  901. that many minutes after the time that idling began, and then
  902. clocked back in at the present time.
  903. g/G Indicate that you \"got back\" X minutes ago. This is quite
  904. different from `k': it clocks you out from the beginning of
  905. the idle period and clock you back in X minutes ago.
  906. s/S Subtract the idle time from the current clock. This is the
  907. same as keeping 0 minutes.
  908. C Cancel the open timer altogether. It will be as though you
  909. never clocked in.
  910. j/J Jump to the current clock, to make manual adjustments.
  911. For all these options, using uppercase makes your final state
  912. to be CLOCKED OUT."))))
  913. (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
  914. (let (char-pressed)
  915. (while (or (null char-pressed)
  916. (and (not (memq char-pressed
  917. '(?k ?K ?g ?G ?s ?S ?C
  918. ?j ?J ?i ?q)))
  919. (or (ding) t)))
  920. (setq char-pressed
  921. (read-char (concat (funcall prompt-fn clock)
  922. " [jkKgGSscCiq]? ")
  923. nil 45)))
  924. (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
  925. (default
  926. (floor (org-time-convert-to-integer (org-time-since last-valid))
  927. 60))
  928. (keep
  929. (and (memq ch '(?k ?K))
  930. (read-number "Keep how many minutes? " default)))
  931. (gotback
  932. (and (memq ch '(?g ?G))
  933. (read-number "Got back how many minutes ago? " default)))
  934. (subtractp (memq ch '(?s ?S)))
  935. (barely-started-p (org-time-less-p
  936. (org-time-subtract last-valid (cdr clock))
  937. 45))
  938. (start-over (and subtractp barely-started-p)))
  939. (cond
  940. ((memq ch '(?j ?J))
  941. (if (eq ch ?J)
  942. (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
  943. (org-clock-jump-to-current-clock clock))
  944. ((or (null ch)
  945. (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
  946. (message ""))
  947. (t
  948. (org-clock-resolve-clock
  949. clock (cond
  950. ((or (eq ch ?C)
  951. ;; If the time on the clock was less than a minute before
  952. ;; the user went away, and they've ask to subtract all the
  953. ;; time...
  954. start-over)
  955. nil)
  956. ((or subtractp
  957. (and gotback (= gotback 0)))
  958. last-valid)
  959. ((or (and keep (= keep default))
  960. (and gotback (= gotback default)))
  961. 'now)
  962. (keep
  963. (org-time-add last-valid (* 60 keep)))
  964. (gotback
  965. (org-time-since (* 60 gotback)))
  966. (t
  967. (error "Unexpected, please report this as a bug")))
  968. (and gotback last-valid)
  969. (memq ch '(?K ?G ?S))
  970. (and start-over
  971. (not (memq ch '(?K ?G ?S ?C))))
  972. fail-quietly)))))
  973. ;;;###autoload
  974. (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
  975. "Resolve all currently open Org clocks.
  976. If `only-dangling-p' is non-nil, only ask to resolve dangling
  977. \(i.e., not currently open and valid) clocks."
  978. (interactive "P")
  979. (unless org-clock-resolving-clocks
  980. (let ((org-clock-resolving-clocks t))
  981. (dolist (file (org-files-list))
  982. (let ((clocks (org-find-open-clocks file)))
  983. (dolist (clock clocks)
  984. (let ((dangling (or (not (org-clock-is-active))
  985. (/= (car clock) org-clock-marker))))
  986. (if (or (not only-dangling-p) dangling)
  987. (org-clock-resolve
  988. clock
  989. (or prompt-fn
  990. (function
  991. (lambda (clock)
  992. (format
  993. "Dangling clock started %d mins ago"
  994. (floor (org-time-convert-to-integer
  995. (org-time-since (cdr clock)))
  996. 60)))))
  997. (or last-valid
  998. (cdr clock)))))))))))
  999. (defun org-emacs-idle-seconds ()
  1000. "Return the current Emacs idle time in seconds, or nil if not idle."
  1001. (let ((idle-time (current-idle-time)))
  1002. (if idle-time
  1003. (float-time idle-time)
  1004. 0)))
  1005. (defun org-mac-idle-seconds ()
  1006. "Return the current Mac idle time in seconds."
  1007. (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
  1008. (defvar org-x11idle-exists-p
  1009. ;; Check that x11idle exists
  1010. (and (eq window-system 'x)
  1011. (eq 0 (call-process-shell-command
  1012. (format "command -v %s" org-clock-x11idle-program-name)))
  1013. ;; Check that x11idle can retrieve the idle time
  1014. ;; FIXME: Why "..-shell-command" rather than just `call-process'?
  1015. (eq 0 (call-process-shell-command org-clock-x11idle-program-name))))
  1016. (defun org-x11-idle-seconds ()
  1017. "Return the current X11 idle time in seconds."
  1018. (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name)) 1000))
  1019. (defun org-user-idle-seconds ()
  1020. "Return the number of seconds the user has been idle for.
  1021. This routine returns a floating point number."
  1022. (cond
  1023. ((eq system-type 'darwin)
  1024. (org-mac-idle-seconds))
  1025. ((and (eq window-system 'x) org-x11idle-exists-p)
  1026. (org-x11-idle-seconds))
  1027. (t
  1028. (org-emacs-idle-seconds))))
  1029. (defvar org-clock-user-idle-seconds)
  1030. (defun org-resolve-clocks-if-idle ()
  1031. "Resolve all currently open Org clocks.
  1032. This is performed after `org-clock-idle-time' minutes, to check
  1033. if the user really wants to stay clocked in after being idle for
  1034. so long."
  1035. (when (and org-clock-idle-time (not org-clock-resolving-clocks)
  1036. org-clock-marker (marker-buffer org-clock-marker))
  1037. (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
  1038. (org-clock-user-idle-start
  1039. (org-time-since org-clock-user-idle-seconds))
  1040. (org-clock-resolving-clocks-due-to-idleness t))
  1041. (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
  1042. (org-clock-resolve
  1043. (cons org-clock-marker
  1044. org-clock-start-time)
  1045. (lambda (_)
  1046. (format "Clocked in & idle for %.1f mins"
  1047. (/ (float-time
  1048. (time-since org-clock-user-idle-start))
  1049. 60)))
  1050. org-clock-user-idle-start)))))
  1051. (defvar org-clock-current-task nil "Task currently clocked in.")
  1052. (defvar org-clock-out-time nil) ; store the time of the last clock-out
  1053. (defvar org--msg-extra)
  1054. ;;;###autoload
  1055. (defun org-clock-in (&optional select start-time)
  1056. "Start the clock on the current item.
  1057. If necessary, clock-out of the currently active clock.
  1058. With a `\\[universal-argument]' prefix argument SELECT, offer a list of \
  1059. recently clocked
  1060. tasks to clock into.
  1061. When SELECT is `\\[universal-argument] \ \\[universal-argument]', \
  1062. clock into the current task and mark it as
  1063. the default task, a special task that will always be offered in the
  1064. clocking selection, associated with the letter `d'.
  1065. When SELECT is `\\[universal-argument] \\[universal-argument] \
  1066. \\[universal-argument]', clock in by using the last clock-out
  1067. time as the start time. See `org-clock-continuously' to make this
  1068. the default behavior."
  1069. (interactive "P")
  1070. (setq org-clock-notification-was-shown nil)
  1071. (org-refresh-effort-properties)
  1072. (catch 'abort
  1073. (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
  1074. (org-clocking-p)))
  1075. ts selected-task target-pos (org--msg-extra "")
  1076. (leftover (and (not org-clock-resolving-clocks)
  1077. org-clock-leftover-time)))
  1078. (when (and org-clock-auto-clock-resolution
  1079. (or (not interrupting)
  1080. (eq t org-clock-auto-clock-resolution))
  1081. (not org-clock-clocking-in)
  1082. (not org-clock-resolving-clocks))
  1083. (setq org-clock-leftover-time nil)
  1084. (let ((org-clock-clocking-in t))
  1085. (org-resolve-clocks))) ; check if any clocks are dangling
  1086. (when (equal select '(64))
  1087. ;; Set start-time to `org-clock-out-time'
  1088. (let ((org-clock-continuously t))
  1089. (org-clock-in nil org-clock-out-time)
  1090. (throw 'abort nil)))
  1091. (when (equal select '(4))
  1092. (pcase (org-clock-select-task "Clock-in on task: ")
  1093. (`nil (error "Abort"))
  1094. (task (setq selected-task (copy-marker task)))))
  1095. (when (equal select '(16))
  1096. ;; Mark as default clocking task
  1097. (org-clock-mark-default-task))
  1098. (when interrupting
  1099. ;; We are interrupting the clocking of a different task. Save
  1100. ;; a marker to this task, so that we can go back. First check
  1101. ;; if we are trying to clock into the same task!
  1102. (when (or selected-task (derived-mode-p 'org-mode))
  1103. (org-with-point-at selected-task
  1104. (unless selected-task (org-back-to-heading t))
  1105. (when (and (eq (marker-buffer org-clock-hd-marker)
  1106. (org-base-buffer (current-buffer)))
  1107. (= (point) (marker-position org-clock-hd-marker))
  1108. (equal org-clock-current-task (org-get-heading t t t t)))
  1109. (message "Clock continues in %S" org-clock-heading)
  1110. (throw 'abort nil))))
  1111. (move-marker org-clock-interrupted-task
  1112. (marker-position org-clock-marker)
  1113. (marker-buffer org-clock-marker))
  1114. (let ((org-clock-clocking-in t))
  1115. (org-clock-out nil t)))
  1116. ;; Clock in at which position?
  1117. (setq target-pos
  1118. (if (and (eobp) (not (org-at-heading-p)))
  1119. (point-at-bol 0)
  1120. (point)))
  1121. (save-excursion
  1122. (when (and selected-task (marker-buffer selected-task))
  1123. ;; There is a selected task, move to the correct buffer
  1124. ;; and set the new target position.
  1125. (set-buffer (org-base-buffer (marker-buffer selected-task)))
  1126. (setq target-pos (marker-position selected-task))
  1127. (move-marker selected-task nil))
  1128. (org-with-wide-buffer
  1129. (goto-char target-pos)
  1130. (org-back-to-heading t)
  1131. (or interrupting (move-marker org-clock-interrupted-task nil))
  1132. (run-hooks 'org-clock-in-prepare-hook)
  1133. (org-clock-history-push)
  1134. (setq org-clock-current-task (org-get-heading t t t t))
  1135. (cond ((functionp org-clock-in-switch-to-state)
  1136. (let ((case-fold-search nil))
  1137. (looking-at org-complex-heading-regexp))
  1138. (let ((newstate (funcall org-clock-in-switch-to-state
  1139. (match-string 2))))
  1140. (when newstate (org-todo newstate))))
  1141. ((and org-clock-in-switch-to-state
  1142. (not (looking-at (concat org-outline-regexp "[ \t]*"
  1143. org-clock-in-switch-to-state
  1144. "\\>"))))
  1145. (org-todo org-clock-in-switch-to-state)))
  1146. (setq org-clock-heading (org-clock--mode-line-heading))
  1147. (org-clock-find-position org-clock-in-resume)
  1148. (cond
  1149. ((and org-clock-in-resume
  1150. (looking-at
  1151. (concat "^[ \t]*" org-clock-string
  1152. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1153. " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  1154. (message "Matched %s" (match-string 1))
  1155. (setq ts (concat "[" (match-string 1) "]"))
  1156. (goto-char (match-end 1))
  1157. (setq org-clock-start-time
  1158. (org-time-string-to-time (match-string 1)))
  1159. (setq org-clock-effort (org-entry-get (point) org-effort-property))
  1160. (setq org-clock-total-time (org-clock-sum-current-item
  1161. (org-clock-get-sum-start))))
  1162. ((eq org-clock-in-resume 'auto-restart)
  1163. ;; called from org-clock-load during startup,
  1164. ;; do not interrupt, but warn!
  1165. (message "Cannot restart clock because task does not contain unfinished clock")
  1166. (ding)
  1167. (sit-for 2)
  1168. (throw 'abort nil))
  1169. (t
  1170. (insert-before-markers "\n")
  1171. (backward-char 1)
  1172. (org-indent-line)
  1173. (when (and (save-excursion
  1174. (end-of-line 0)
  1175. (org-in-item-p)))
  1176. (beginning-of-line 1)
  1177. (indent-line-to (- (current-indentation) 2)))
  1178. (insert org-clock-string " ")
  1179. (setq org-clock-effort (org-entry-get (point) org-effort-property))
  1180. (setq org-clock-total-time (org-clock-sum-current-item
  1181. (org-clock-get-sum-start)))
  1182. (setq org-clock-start-time
  1183. (or (and org-clock-continuously org-clock-out-time)
  1184. (and leftover
  1185. (y-or-n-p
  1186. (format
  1187. "You stopped another clock %d mins ago; start this one from then? "
  1188. (/ (org-time-convert-to-integer
  1189. (org-time-subtract
  1190. (org-current-time org-clock-rounding-minutes t)
  1191. leftover))
  1192. 60)))
  1193. leftover)
  1194. start-time
  1195. (org-current-time org-clock-rounding-minutes t)))
  1196. (setq ts (org-insert-time-stamp org-clock-start-time
  1197. 'with-hm 'inactive))))
  1198. (move-marker org-clock-marker (point) (buffer-base-buffer))
  1199. (move-marker org-clock-hd-marker
  1200. (save-excursion (org-back-to-heading t) (point))
  1201. (buffer-base-buffer))
  1202. (setq org-clock-has-been-used t)
  1203. ;; add to mode line
  1204. (when (or (eq org-clock-clocked-in-display 'mode-line)
  1205. (eq org-clock-clocked-in-display 'both))
  1206. (or global-mode-string (setq global-mode-string '("")))
  1207. (or (memq 'org-mode-line-string global-mode-string)
  1208. (setq global-mode-string
  1209. (append global-mode-string '(org-mode-line-string)))))
  1210. ;; add to frame title
  1211. (when (or (eq org-clock-clocked-in-display 'frame-title)
  1212. (eq org-clock-clocked-in-display 'both))
  1213. (setq frame-title-format org-clock-frame-title-format))
  1214. (org-clock-update-mode-line)
  1215. (when org-clock-mode-line-timer
  1216. (cancel-timer org-clock-mode-line-timer)
  1217. (setq org-clock-mode-line-timer nil))
  1218. (when org-clock-clocked-in-display
  1219. (setq org-clock-mode-line-timer
  1220. (run-with-timer org-clock-update-period
  1221. org-clock-update-period
  1222. 'org-clock-update-mode-line)))
  1223. (when org-clock-idle-timer
  1224. (cancel-timer org-clock-idle-timer)
  1225. (setq org-clock-idle-timer nil))
  1226. (setq org-clock-idle-timer
  1227. (run-with-timer 60 60 'org-resolve-clocks-if-idle))
  1228. (message "Clock starts at %s - %s" ts org--msg-extra)
  1229. (run-hooks 'org-clock-in-hook))))))
  1230. ;;;###autoload
  1231. (defun org-clock-in-last (&optional arg)
  1232. "Clock in the last closed clocked item.
  1233. When already clocking in, send a warning.
  1234. With a universal prefix argument, select the task you want to
  1235. clock in from the last clocked in tasks.
  1236. With two universal prefix arguments, start clocking using the
  1237. last clock-out time, if any.
  1238. With three universal prefix arguments, interactively prompt
  1239. for a todo state to switch to, overriding the existing value
  1240. `org-clock-in-switch-to-state'."
  1241. (interactive "P")
  1242. (if (equal arg '(4)) (org-clock-in arg)
  1243. (let ((start-time (if (or org-clock-continuously (equal arg '(16)))
  1244. (or org-clock-out-time
  1245. (org-current-time org-clock-rounding-minutes t))
  1246. (org-current-time org-clock-rounding-minutes t))))
  1247. (if (null org-clock-history)
  1248. (message "No last clock")
  1249. (let ((org-clock-in-switch-to-state
  1250. (if (and (not org-clock-current-task) (equal arg '(64)))
  1251. (completing-read "Switch to state: "
  1252. (and org-clock-history
  1253. (with-current-buffer
  1254. (marker-buffer (car org-clock-history))
  1255. org-todo-keywords-1)))
  1256. org-clock-in-switch-to-state))
  1257. (already-clocking org-clock-current-task))
  1258. (org-clock-clock-in (list (car org-clock-history)) nil start-time)
  1259. (or already-clocking
  1260. ;; Don't display a message if we are already clocking in
  1261. (message "Clocking back: %s (in %s)"
  1262. org-clock-current-task
  1263. (buffer-name (marker-buffer org-clock-marker)))))))))
  1264. (defun org-clock-mark-default-task ()
  1265. "Mark current task as default task."
  1266. (interactive)
  1267. (save-excursion
  1268. (org-back-to-heading t)
  1269. (move-marker org-clock-default-task (point))))
  1270. (defun org-clock-get-sum-start ()
  1271. "Return the time from which clock times should be counted.
  1272. This is for the currently running clock as it is displayed in the
  1273. mode line. This function looks at the properties LAST_REPEAT and
  1274. in particular CLOCK_MODELINE_TOTAL and the corresponding variable
  1275. `org-clock-mode-line-total' and then decides which time to use.
  1276. The time is always returned as UTC."
  1277. (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL" 'selective)
  1278. (symbol-name org-clock-mode-line-total)))
  1279. (lr (org-entry-get nil "LAST_REPEAT")))
  1280. (cond
  1281. ((equal cmt "current")
  1282. (setq org--msg-extra "showing time in current clock instance")
  1283. (current-time))
  1284. ((equal cmt "today")
  1285. (setq org--msg-extra "showing today's task time.")
  1286. (let* ((dt (decode-time))
  1287. (hour (nth 2 dt))
  1288. (day (nth 3 dt)))
  1289. (if (< hour org-extend-today-until) (setf (nth 3 dt) (1- day)))
  1290. (setf (nth 2 dt) org-extend-today-until)
  1291. (apply #'encode-time 0 0 (nthcdr 2 dt))))
  1292. ((or (equal cmt "all")
  1293. (and (or (not cmt) (equal cmt "auto"))
  1294. (not lr)))
  1295. (setq org--msg-extra "showing entire task time.")
  1296. nil)
  1297. ((or (equal cmt "repeat")
  1298. (and (or (not cmt) (equal cmt "auto"))
  1299. lr))
  1300. (setq org--msg-extra "showing task time since last repeat.")
  1301. (and lr (org-time-string-to-time lr)))
  1302. (t nil))))
  1303. (defun org-clock-find-position (find-unclosed)
  1304. "Find the location where the next clock line should be inserted.
  1305. When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
  1306. line and position cursor in that line."
  1307. (org-back-to-heading t)
  1308. (catch 'exit
  1309. (let* ((beg (line-beginning-position))
  1310. (end (save-excursion (outline-next-heading) (point)))
  1311. (org-clock-into-drawer (org-clock-into-drawer))
  1312. (drawer (org-clock-drawer-name)))
  1313. ;; Look for a running clock if FIND-UNCLOSED in non-nil.
  1314. (when find-unclosed
  1315. (let ((open-clock-re
  1316. (concat "^[ \t]*"
  1317. org-clock-string
  1318. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1319. " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  1320. (while (re-search-forward open-clock-re end t)
  1321. (let ((element (org-element-at-point)))
  1322. (when (and (eq (org-element-type element) 'clock)
  1323. (eq (org-element-property :status element) 'running))
  1324. (beginning-of-line)
  1325. (throw 'exit t))))))
  1326. ;; Look for an existing clock drawer.
  1327. (when drawer
  1328. (goto-char beg)
  1329. (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$")))
  1330. (while (re-search-forward drawer-re end t)
  1331. (let ((element (org-element-at-point)))
  1332. (when (eq (org-element-type element) 'drawer)
  1333. (let ((cend (org-element-property :contents-end element)))
  1334. (if (and (not org-log-states-order-reversed) cend)
  1335. (goto-char cend)
  1336. (forward-line))
  1337. (throw 'exit t)))))))
  1338. (goto-char beg)
  1339. (let ((clock-re (concat "^[ \t]*" org-clock-string))
  1340. (count 0)
  1341. positions)
  1342. ;; Count the CLOCK lines and store their positions.
  1343. (save-excursion
  1344. (while (re-search-forward clock-re end t)
  1345. (let ((element (org-element-at-point)))
  1346. (when (eq (org-element-type element) 'clock)
  1347. (setq positions (cons (line-beginning-position) positions)
  1348. count (1+ count))))))
  1349. (cond
  1350. ((null positions)
  1351. ;; Skip planning line and property drawer, if any.
  1352. (org-end-of-meta-data)
  1353. (unless (bolp) (insert "\n"))
  1354. ;; Create a new drawer if necessary.
  1355. (when (and org-clock-into-drawer
  1356. (or (not (wholenump org-clock-into-drawer))
  1357. (< org-clock-into-drawer 2)))
  1358. (let ((beg (point)))
  1359. (insert ":" drawer ":\n:END:\n")
  1360. (org-indent-region beg (point))
  1361. (org-flag-region
  1362. (line-end-position -1) (1- (point)) t 'org-hide-drawer)
  1363. (forward-line -1))))
  1364. ;; When a clock drawer needs to be created because of the
  1365. ;; number of clock items or simply if it is missing, collect
  1366. ;; all clocks in the section and wrap them within the drawer.
  1367. ((if (wholenump org-clock-into-drawer)
  1368. (>= (1+ count) org-clock-into-drawer)
  1369. drawer)
  1370. ;; Skip planning line and property drawer, if any.
  1371. (org-end-of-meta-data)
  1372. (let ((beg (point)))
  1373. (insert
  1374. (mapconcat
  1375. (lambda (p)
  1376. (save-excursion
  1377. (goto-char p)
  1378. (org-trim (delete-and-extract-region
  1379. (save-excursion (skip-chars-backward " \r\t\n")
  1380. (line-beginning-position 2))
  1381. (line-beginning-position 2)))))
  1382. positions "\n")
  1383. "\n:END:\n")
  1384. (let ((end (point-marker)))
  1385. (goto-char beg)
  1386. (save-excursion (insert ":" drawer ":\n"))
  1387. (org-flag-region (line-end-position) (1- end) t 'org-hide-drawer)
  1388. (org-indent-region (point) end)
  1389. (forward-line)
  1390. (unless org-log-states-order-reversed
  1391. (goto-char end)
  1392. (beginning-of-line -1))
  1393. (set-marker end nil))))
  1394. (org-log-states-order-reversed (goto-char (car (last positions))))
  1395. (t (goto-char (car positions))))))))
  1396. ;;;###autoload
  1397. (defun org-clock-out (&optional switch-to-state fail-quietly at-time)
  1398. "Stop the currently running clock.
  1399. Throw an error if there is no running clock and FAIL-QUIETLY is nil.
  1400. With a universal prefix, prompt for a state to switch the clocked out task
  1401. to, overriding the existing value of `org-clock-out-switch-to-state'."
  1402. (interactive "P")
  1403. (catch 'exit
  1404. (when (not (org-clocking-p))
  1405. (setq global-mode-string
  1406. (delq 'org-mode-line-string global-mode-string))
  1407. (setq frame-title-format org-frame-title-format-backup)
  1408. (force-mode-line-update)
  1409. (if fail-quietly (throw 'exit t) (user-error "No active clock")))
  1410. (let ((org-clock-out-switch-to-state
  1411. (if switch-to-state
  1412. (completing-read "Switch to state: "
  1413. (with-current-buffer
  1414. (marker-buffer org-clock-marker)
  1415. org-todo-keywords-1)
  1416. nil t "DONE")
  1417. org-clock-out-switch-to-state))
  1418. (now (org-current-time org-clock-rounding-minutes))
  1419. ts te s h m remove)
  1420. (setq org-clock-out-time now)
  1421. (save-excursion ; Do not replace this with `with-current-buffer'.
  1422. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1423. (save-restriction
  1424. (widen)
  1425. (goto-char org-clock-marker)
  1426. (beginning-of-line 1)
  1427. (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1428. (equal (match-string 1) org-clock-string))
  1429. (setq ts (match-string 2))
  1430. (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
  1431. (goto-char (match-end 0))
  1432. (delete-region (point) (point-at-eol))
  1433. (insert "--")
  1434. (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
  1435. (setq s (org-time-convert-to-integer
  1436. (time-subtract
  1437. (org-time-string-to-time te)
  1438. (org-time-string-to-time ts)))
  1439. h (floor s 3600)
  1440. m (floor (mod s 3600) 60))
  1441. (insert " => " (format "%2d:%02d" h m))
  1442. (move-marker org-clock-marker nil)
  1443. (move-marker org-clock-hd-marker nil)
  1444. ;; Possibly remove zero time clocks. However, do not add
  1445. ;; a note associated to the CLOCK line in this case.
  1446. (cond ((and org-clock-out-remove-zero-time-clocks
  1447. (= 0 h m))
  1448. (setq remove t)
  1449. (delete-region (line-beginning-position)
  1450. (line-beginning-position 2)))
  1451. (org-log-note-clock-out
  1452. (org-add-log-setup
  1453. 'clock-out nil nil nil
  1454. (concat "# Task: " (org-get-heading t) "\n\n"))))
  1455. (when org-clock-mode-line-timer
  1456. (cancel-timer org-clock-mode-line-timer)
  1457. (setq org-clock-mode-line-timer nil))
  1458. (when org-clock-idle-timer
  1459. (cancel-timer org-clock-idle-timer)
  1460. (setq org-clock-idle-timer nil))
  1461. (setq global-mode-string
  1462. (delq 'org-mode-line-string global-mode-string))
  1463. (setq frame-title-format org-frame-title-format-backup)
  1464. (when org-clock-out-switch-to-state
  1465. (save-excursion
  1466. (org-back-to-heading t)
  1467. (let ((org-clock-out-when-done nil))
  1468. (cond
  1469. ((functionp org-clock-out-switch-to-state)
  1470. (let ((case-fold-search nil))
  1471. (looking-at org-complex-heading-regexp))
  1472. (let ((newstate (funcall org-clock-out-switch-to-state
  1473. (match-string 2))))
  1474. (when newstate (org-todo newstate))))
  1475. ((and org-clock-out-switch-to-state
  1476. (not (looking-at (concat org-outline-regexp "[ \t]*"
  1477. org-clock-out-switch-to-state
  1478. "\\>"))))
  1479. (org-todo org-clock-out-switch-to-state))))))
  1480. (force-mode-line-update)
  1481. (message (if remove
  1482. "Clock stopped at %s after %s => LINE REMOVED"
  1483. "Clock stopped at %s after %s")
  1484. te (org-duration-from-minutes (+ (* 60 h) m)))
  1485. (run-hooks 'org-clock-out-hook)
  1486. (unless (org-clocking-p)
  1487. (setq org-clock-current-task nil)))))))
  1488. (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
  1489. (defun org-clock-remove-empty-clock-drawer ()
  1490. "Remove empty clock drawers in current subtree."
  1491. (save-excursion
  1492. (org-back-to-heading t)
  1493. (org-map-tree
  1494. (lambda ()
  1495. (let ((drawer (org-clock-drawer-name))
  1496. (case-fold-search t))
  1497. (when drawer
  1498. (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer)))
  1499. (end (save-excursion (outline-next-heading))))
  1500. (while (re-search-forward re end t)
  1501. (org-remove-empty-drawer-at (point))))))))))
  1502. (defun org-clock-timestamps-up (&optional n)
  1503. "Increase CLOCK timestamps at cursor.
  1504. Optional argument N tells to change by that many units."
  1505. (interactive "P")
  1506. (org-clock-timestamps-change 'up n))
  1507. (defun org-clock-timestamps-down (&optional n)
  1508. "Increase CLOCK timestamps at cursor.
  1509. Optional argument N tells to change by that many units."
  1510. (interactive "P")
  1511. (org-clock-timestamps-change 'down n))
  1512. (defun org-clock-timestamps-change (updown &optional n)
  1513. "Change CLOCK timestamps synchronously at cursor.
  1514. UPDOWN tells whether to change `up' or `down'.
  1515. Optional argument N tells to change by that many units."
  1516. (let ((tschange (if (eq updown 'up) 'org-timestamp-up
  1517. 'org-timestamp-down))
  1518. (timestamp? (org-at-timestamp-p 'lax))
  1519. ts1 begts1 ts2 begts2 updatets1 tdiff)
  1520. (when timestamp?
  1521. (save-excursion
  1522. (move-beginning-of-line 1)
  1523. (re-search-forward org-ts-regexp3 nil t)
  1524. (setq ts1 (match-string 0) begts1 (match-beginning 0))
  1525. (when (re-search-forward org-ts-regexp3 nil t)
  1526. (setq ts2 (match-string 0) begts2 (match-beginning 0))))
  1527. ;; Are we on the second timestamp?
  1528. (if (<= begts2 (point)) (setq updatets1 t))
  1529. (if (not ts2)
  1530. ;; fall back on org-timestamp-up if there is only one
  1531. (funcall tschange n)
  1532. (funcall tschange n)
  1533. (let ((ts (if updatets1 ts2 ts1))
  1534. (begts (if updatets1 begts1 begts2)))
  1535. (setq tdiff
  1536. (time-subtract
  1537. (org-time-string-to-time org-last-changed-timestamp)
  1538. (org-time-string-to-time ts)))
  1539. (save-excursion
  1540. (goto-char begts)
  1541. (org-timestamp-change
  1542. (round (/ (float-time tdiff)
  1543. (pcase timestamp?
  1544. (`minute 60)
  1545. (`hour 3600)
  1546. (`day (* 24 3600))
  1547. (`month (* 24 3600 31))
  1548. (`year (* 24 3600 365.2)))))
  1549. timestamp? 'updown)))))))
  1550. ;;;###autoload
  1551. (defun org-clock-cancel ()
  1552. "Cancel the running clock by removing the start timestamp."
  1553. (interactive)
  1554. (when (not (org-clocking-p))
  1555. (setq global-mode-string
  1556. (delq 'org-mode-line-string global-mode-string))
  1557. (setq frame-title-format org-frame-title-format-backup)
  1558. (force-mode-line-update)
  1559. (error "No active clock"))
  1560. (save-excursion ; Do not replace this with `with-current-buffer'.
  1561. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1562. (goto-char org-clock-marker)
  1563. (if (looking-back (concat "^[ \t]*" org-clock-string ".*")
  1564. (line-beginning-position))
  1565. (progn (delete-region (1- (point-at-bol)) (point-at-eol))
  1566. (org-remove-empty-drawer-at (point)))
  1567. (message "Clock gone, cancel the timer anyway")
  1568. (sit-for 2)))
  1569. (move-marker org-clock-marker nil)
  1570. (move-marker org-clock-hd-marker nil)
  1571. (setq global-mode-string
  1572. (delq 'org-mode-line-string global-mode-string))
  1573. (setq frame-title-format org-frame-title-format-backup)
  1574. (force-mode-line-update)
  1575. (message "Clock canceled")
  1576. (run-hooks 'org-clock-cancel-hook))
  1577. ;;;###autoload
  1578. (defun org-clock-goto (&optional select)
  1579. "Go to the currently clocked-in entry, or to the most recently clocked one.
  1580. With prefix arg SELECT, offer recently clocked tasks for selection."
  1581. (interactive "@P")
  1582. (let* ((recent nil)
  1583. (m (cond
  1584. (select
  1585. (or (org-clock-select-task "Select task to go to: ")
  1586. (error "No task selected")))
  1587. ((org-clocking-p) org-clock-marker)
  1588. ((and org-clock-goto-may-find-recent-task
  1589. (car org-clock-history)
  1590. (marker-buffer (car org-clock-history)))
  1591. (setq recent t)
  1592. (car org-clock-history))
  1593. (t (error "No active or recent clock task")))))
  1594. (pop-to-buffer-same-window (marker-buffer m))
  1595. (if (or (< m (point-min)) (> m (point-max))) (widen))
  1596. (goto-char m)
  1597. (org-show-entry)
  1598. (org-back-to-heading t)
  1599. (recenter org-clock-goto-before-context)
  1600. (org-reveal)
  1601. (if recent
  1602. (message "No running clock, this is the most recently clocked task"))
  1603. (run-hooks 'org-clock-goto-hook)))
  1604. (defvar-local org-clock-file-total-minutes nil
  1605. "Holds the file total time in minutes, after a call to `org-clock-sum'.")
  1606. ;;;###autoload
  1607. (defun org-clock-sum-today (&optional headline-filter)
  1608. "Sum the times for each subtree for today."
  1609. (let ((range (org-clock-special-range 'today)))
  1610. (org-clock-sum (car range) (cadr range)
  1611. headline-filter :org-clock-minutes-today)))
  1612. (defun org-clock-sum-custom (&optional headline-filter range propname)
  1613. "Sum the times for each subtree for today."
  1614. (let ((r (or (and (symbolp range) (org-clock-special-range range))
  1615. (org-clock-special-range
  1616. (intern (completing-read
  1617. "Range: "
  1618. '("today" "yesterday" "thisweek" "lastweek"
  1619. "thismonth" "lastmonth" "thisyear" "lastyear"
  1620. "interactive")
  1621. nil t))))))
  1622. (org-clock-sum (car r) (cadr r)
  1623. headline-filter (or propname :org-clock-minutes-custom))))
  1624. ;;;###autoload
  1625. (defun org-clock-sum (&optional tstart tend headline-filter propname)
  1626. "Sum the times for each subtree.
  1627. Puts the resulting times in minutes as a text property on each headline.
  1628. TSTART and TEND can mark a time range to be considered.
  1629. HEADLINE-FILTER is a zero-arg function that, if specified, is called for
  1630. each headline in the time range with point at the headline. Headlines for
  1631. which HEADLINE-FILTER returns nil are excluded from the clock summation.
  1632. PROPNAME lets you set a custom text property instead of :org-clock-minutes."
  1633. (with-silent-modifications
  1634. (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
  1635. org-clock-string
  1636. "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
  1637. (lmax 30)
  1638. (ltimes (make-vector lmax 0))
  1639. (level 0)
  1640. (tstart (cond ((stringp tstart) (org-time-string-to-seconds tstart))
  1641. ((consp tstart) (float-time tstart))
  1642. (t tstart)))
  1643. (tend (cond ((stringp tend) (org-time-string-to-seconds tend))
  1644. ((consp tend) (float-time tend))
  1645. (t tend)))
  1646. (t1 0)
  1647. time)
  1648. (remove-text-properties (point-min) (point-max)
  1649. `(,(or propname :org-clock-minutes) t
  1650. :org-clock-force-headline-inclusion t))
  1651. (save-excursion
  1652. (goto-char (point-max))
  1653. (while (re-search-backward re nil t)
  1654. (cond
  1655. ((match-end 2)
  1656. ;; Two time stamps.
  1657. (let* ((ts (float-time
  1658. (apply #'encode-time
  1659. (save-match-data
  1660. (org-parse-time-string (match-string 2))))))
  1661. (te (float-time
  1662. (apply #'encode-time
  1663. (org-parse-time-string (match-string 3)))))
  1664. (dt (- (if tend (min te tend) te)
  1665. (if tstart (max ts tstart) ts))))
  1666. (when (> dt 0) (cl-incf t1 (floor dt 60)))))
  1667. ((match-end 4)
  1668. ;; A naked time.
  1669. (setq t1 (+ t1 (string-to-number (match-string 5))
  1670. (* 60 (string-to-number (match-string 4))))))
  1671. (t ;A headline
  1672. ;; Add the currently clocking item time to the total.
  1673. (when (and org-clock-report-include-clocking-task
  1674. (eq (org-clocking-buffer) (current-buffer))
  1675. (eq (marker-position org-clock-hd-marker) (point))
  1676. tstart
  1677. tend
  1678. (>= (float-time org-clock-start-time) tstart)
  1679. (<= (float-time org-clock-start-time) tend))
  1680. (let ((time (floor (org-time-convert-to-integer
  1681. (org-time-since org-clock-start-time))
  1682. 60)))
  1683. (setq t1 (+ t1 time))))
  1684. (let* ((headline-forced
  1685. (get-text-property (point)
  1686. :org-clock-force-headline-inclusion))
  1687. (headline-included
  1688. (or (null headline-filter)
  1689. (save-excursion
  1690. (save-match-data (funcall headline-filter))))))
  1691. (setq level (- (match-end 1) (match-beginning 1)))
  1692. (when (>= level lmax)
  1693. (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
  1694. (when (or (> t1 0) (> (aref ltimes level) 0))
  1695. (when (or headline-included headline-forced)
  1696. (if headline-included
  1697. (cl-loop for l from 0 to level do
  1698. (aset ltimes l (+ (aref ltimes l) t1))))
  1699. (setq time (aref ltimes level))
  1700. (goto-char (match-beginning 0))
  1701. (put-text-property (point) (point-at-eol)
  1702. (or propname :org-clock-minutes) time)
  1703. (when headline-filter
  1704. (save-excursion
  1705. (save-match-data
  1706. (while (org-up-heading-safe)
  1707. (put-text-property
  1708. (point) (line-end-position)
  1709. :org-clock-force-headline-inclusion t))))))
  1710. (setq t1 0)
  1711. (cl-loop for l from level to (1- lmax) do
  1712. (aset ltimes l 0)))))))
  1713. (setq org-clock-file-total-minutes (aref ltimes 0))))))
  1714. (defun org-clock-sum-current-item (&optional tstart)
  1715. "Return time, clocked on current item in total."
  1716. (save-excursion
  1717. (save-restriction
  1718. (org-narrow-to-subtree)
  1719. (org-clock-sum tstart)
  1720. org-clock-file-total-minutes)))
  1721. ;;;###autoload
  1722. (defun org-clock-display (&optional arg)
  1723. "Show subtree times in the entire buffer.
  1724. By default, show the total time for the range defined in
  1725. `org-clock-display-default-range'. With `\\[universal-argument]' \
  1726. prefix, show
  1727. the total time for today instead.
  1728. With `\\[universal-argument] \\[universal-argument]' prefix, \
  1729. use a custom range, entered at prompt.
  1730. With `\\[universal-argument] \ \\[universal-argument] \
  1731. \\[universal-argument]' prefix, display the total time in the
  1732. echo area.
  1733. Use `\\[org-clock-remove-overlays]' to remove the subtree times."
  1734. (interactive "P")
  1735. (org-clock-remove-overlays)
  1736. (let* ((todayp (equal arg '(4)))
  1737. (customp (member arg '((16) today yesterday
  1738. thisweek lastweek thismonth
  1739. lastmonth thisyear lastyear
  1740. untilnow interactive)))
  1741. (prop (cond ((not arg) :org-clock-minutes-default)
  1742. (todayp :org-clock-minutes-today)
  1743. (customp :org-clock-minutes-custom)
  1744. (t :org-clock-minutes))))
  1745. (cond ((not arg) (org-clock-sum-custom
  1746. nil org-clock-display-default-range prop))
  1747. (todayp (org-clock-sum-today))
  1748. (customp (org-clock-sum-custom nil arg))
  1749. (t (org-clock-sum)))
  1750. (unless (equal arg '(64))
  1751. (save-excursion
  1752. (goto-char (point-min))
  1753. (let ((p nil))
  1754. (while (or (and (equal (setq p (point)) (point-min))
  1755. (get-text-property p prop))
  1756. (setq p (next-single-property-change (point) prop)))
  1757. (goto-char p)
  1758. (let ((time (get-text-property p prop)))
  1759. (when time (org-clock-put-overlay time)))))
  1760. ;; Arrange to remove the overlays upon next change.
  1761. (when org-remove-highlights-with-change
  1762. (add-hook 'before-change-functions 'org-clock-remove-overlays
  1763. nil 'local))))
  1764. (let* ((h (/ org-clock-file-total-minutes 60))
  1765. (m (- org-clock-file-total-minutes (* 60 h))))
  1766. (message (cond
  1767. (todayp
  1768. "Total file time for today: %s (%d hours and %d minutes)")
  1769. (customp
  1770. "Total file time (custom): %s (%d hours and %d minutes)")
  1771. (t
  1772. "Total file time: %s (%d hours and %d minutes)"))
  1773. (org-duration-from-minutes org-clock-file-total-minutes)
  1774. h m))))
  1775. (defvar-local org-clock-overlays nil)
  1776. (defun org-clock-put-overlay (time)
  1777. "Put an overlay on the headline at point, displaying TIME.
  1778. Create a new overlay and store it in `org-clock-overlays', so
  1779. that it will be easy to remove. This function assumes point is
  1780. on a headline."
  1781. (org-match-line org-complex-heading-regexp)
  1782. (goto-char (match-beginning 4))
  1783. (let* ((headline (match-string 4))
  1784. (text (concat headline
  1785. (org-add-props
  1786. (make-string
  1787. (max (- (- 60 (current-column))
  1788. (org-string-width headline)
  1789. (length (org-get-at-bol 'line-prefix)))
  1790. 0)
  1791. ?\·)
  1792. '(face shadow))
  1793. (org-add-props
  1794. (format " %9s " (org-duration-from-minutes time))
  1795. '(face org-clock-overlay))))
  1796. (o (make-overlay (point) (line-end-position))))
  1797. (org-overlay-display o text)
  1798. (push o org-clock-overlays)))
  1799. ;;;###autoload
  1800. (defun org-clock-remove-overlays (&optional _beg _end noremove)
  1801. "Remove the occur highlights from the buffer.
  1802. If NOREMOVE is nil, remove this function from the
  1803. `before-change-functions' in the current buffer."
  1804. (interactive)
  1805. (unless org-inhibit-highlight-removal
  1806. (mapc #'delete-overlay org-clock-overlays)
  1807. (setq org-clock-overlays nil)
  1808. (unless noremove
  1809. (remove-hook 'before-change-functions
  1810. 'org-clock-remove-overlays 'local))))
  1811. ;;;###autoload
  1812. (defun org-clock-out-if-current ()
  1813. "Clock out if the current entry contains the running clock.
  1814. This is used to stop the clock after a TODO entry is marked DONE,
  1815. and is only done if the variable `org-clock-out-when-done' is not nil."
  1816. (when (and (org-clocking-p)
  1817. org-clock-out-when-done
  1818. (marker-buffer org-clock-marker)
  1819. (or (and (eq t org-clock-out-when-done)
  1820. (member org-state org-done-keywords))
  1821. (and (listp org-clock-out-when-done)
  1822. (member org-state org-clock-out-when-done)))
  1823. (equal (or (buffer-base-buffer (org-clocking-buffer))
  1824. (org-clocking-buffer))
  1825. (or (buffer-base-buffer (current-buffer))
  1826. (current-buffer)))
  1827. (< (point) org-clock-marker)
  1828. (> (org-with-wide-buffer (org-entry-end-position))
  1829. org-clock-marker))
  1830. ;; Clock out, but don't accept a logging message for this.
  1831. (let ((org-log-note-clock-out nil)
  1832. (org-clock-out-switch-to-state nil))
  1833. (org-clock-out))))
  1834. ;;;###autoload
  1835. (defun org-clock-get-clocktable (&rest props)
  1836. "Get a formatted clocktable with parameters according to PROPS.
  1837. The table is created in a temporary buffer, fully formatted and
  1838. fontified, and then returned."
  1839. ;; Set the defaults
  1840. (setq props (plist-put props :name "clocktable"))
  1841. (unless (plist-member props :maxlevel)
  1842. (setq props (plist-put props :maxlevel 2)))
  1843. (unless (plist-member props :scope)
  1844. (setq props (plist-put props :scope 'agenda)))
  1845. (with-temp-buffer
  1846. (org-mode)
  1847. (org-create-dblock props)
  1848. (org-update-dblock)
  1849. (org-font-lock-ensure)
  1850. (forward-line 2)
  1851. (buffer-substring (point) (progn
  1852. (re-search-forward "^[ \t]*#\\+END" nil t)
  1853. (point-at-bol)))))
  1854. ;;;###autoload
  1855. (defun org-clock-report (&optional arg)
  1856. "Update or create a table containing a report about clocked time.
  1857. If point is inside an existing clocktable block, update it.
  1858. Otherwise, insert a new one.
  1859. The new table inherits its properties from the variable
  1860. `org-clock-clocktable-default-properties'. The scope of the
  1861. clocktable, when not specified in the previous variable, is
  1862. `subtree' when the function is called from within a subtree, and
  1863. `file' elsewhere.
  1864. When called with a prefix argument, move to the first clock table
  1865. in the buffer and update it."
  1866. (interactive "P")
  1867. (org-clock-remove-overlays)
  1868. (when arg
  1869. (org-find-dblock "clocktable")
  1870. (org-show-entry))
  1871. (pcase (org-in-clocktable-p)
  1872. (`nil
  1873. (org-create-dblock
  1874. (org-combine-plists
  1875. (list :scope (if (org-before-first-heading-p) 'file 'subtree))
  1876. org-clock-clocktable-default-properties
  1877. '(:name "clocktable"))))
  1878. (start (goto-char start)))
  1879. (org-update-dblock))
  1880. (defun org-day-of-week (day month year)
  1881. "Return 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. ((or `nil `file `subtree `tree
  2194. (and (pred symbolp)
  2195. (guard (string-match "\\`tree\\([0-9]+\\)\\'"
  2196. (symbol-name scope)))))
  2197. (or (buffer-file-name (buffer-base-buffer))
  2198. (current-buffer)))
  2199. ((pred functionp) (funcall scope))
  2200. ((pred consp) scope)
  2201. (_ (user-error "Unknown scope: %S" scope))))
  2202. (block (plist-get params :block))
  2203. (ts (plist-get params :tstart))
  2204. (te (plist-get params :tend))
  2205. (ws (plist-get params :wstart))
  2206. (ms (plist-get params :mstart))
  2207. (step (plist-get params :step))
  2208. (formatter (or (plist-get params :formatter)
  2209. org-clock-clocktable-formatter
  2210. 'org-clocktable-write-default))
  2211. cc)
  2212. ;; Check if we need to do steps
  2213. (when block
  2214. ;; Get the range text for the header
  2215. (setq cc (org-clock-special-range block nil t ws ms)
  2216. ts (car cc)
  2217. te (nth 1 cc)))
  2218. (when step
  2219. ;; Write many tables, in steps
  2220. (unless (or block (and ts te))
  2221. (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
  2222. (org-clocktable-steps params)
  2223. (throw 'exit nil))
  2224. (org-agenda-prepare-buffers (if (consp files) files (list files)))
  2225. (let ((origin (point))
  2226. (tables
  2227. (if (consp files)
  2228. (mapcar (lambda (file)
  2229. (with-current-buffer (find-buffer-visiting file)
  2230. (save-excursion
  2231. (save-restriction
  2232. (org-clock-get-table-data file params)))))
  2233. files)
  2234. ;; Get the right restriction for the scope.
  2235. (save-restriction
  2236. (cond
  2237. ((not scope)) ;use the restriction as it is now
  2238. ((eq scope 'file) (widen))
  2239. ((eq scope 'subtree) (org-narrow-to-subtree))
  2240. ((eq scope 'tree)
  2241. (while (org-up-heading-safe))
  2242. (org-narrow-to-subtree))
  2243. ((and (symbolp scope)
  2244. (string-match "\\`tree\\([0-9]+\\)\\'"
  2245. (symbol-name scope)))
  2246. (let ((level (string-to-number
  2247. (match-string 1 (symbol-name scope)))))
  2248. (catch 'exit
  2249. (while (org-up-heading-safe)
  2250. (looking-at org-outline-regexp)
  2251. (when (<= (org-reduced-level (funcall outline-level))
  2252. level)
  2253. (throw 'exit nil))))
  2254. (org-narrow-to-subtree))))
  2255. (list (org-clock-get-table-data nil params)))))
  2256. (multifile
  2257. ;; Even though `file-with-archives' can consist of
  2258. ;; multiple files, we consider this is one extended file
  2259. ;; instead.
  2260. (and (consp files) (not (eq scope 'file-with-archives)))))
  2261. (funcall formatter
  2262. origin
  2263. tables
  2264. (org-combine-plists params `(:multifile ,multifile)))))))
  2265. (defun org-clocktable-write-default (ipos tables params)
  2266. "Write out a clock table at position IPOS in the current buffer.
  2267. TABLES is a list of tables with clocking data as produced by
  2268. `org-clock-get-table-data'. PARAMS is the parameter property list obtained
  2269. from the dynamic block definition."
  2270. ;; This function looks quite complicated, mainly because there are a
  2271. ;; lot of options which can add or remove columns. I have massively
  2272. ;; commented this function, the I hope it is understandable. If
  2273. ;; someone wants to write their own special formatter, this maybe
  2274. ;; much easier because there can be a fixed format with a
  2275. ;; well-defined number of columns...
  2276. (let* ((lang (or (plist-get params :lang) "en"))
  2277. (multifile (plist-get params :multifile))
  2278. (block (plist-get params :block))
  2279. (sort (plist-get params :sort))
  2280. (header (plist-get params :header))
  2281. (link (plist-get params :link))
  2282. (maxlevel (or (plist-get params :maxlevel) 3))
  2283. (emph (plist-get params :emphasize))
  2284. (compact? (plist-get params :compact))
  2285. (narrow (or (plist-get params :narrow) (and compact? '40!)))
  2286. (level? (and (not compact?) (plist-get params :level)))
  2287. (timestamp (plist-get params :timestamp))
  2288. (tags (plist-get params :tags))
  2289. (properties (plist-get params :properties))
  2290. (time-columns
  2291. (if (or compact? (< maxlevel 2)) 1
  2292. ;; Deepest headline level is a hard limit for the number
  2293. ;; of time columns.
  2294. (let ((levels
  2295. (cl-mapcan
  2296. (lambda (table)
  2297. (pcase table
  2298. (`(,_ ,(and (pred wholenump) (pred (/= 0))) ,entries)
  2299. (mapcar #'car entries))))
  2300. tables)))
  2301. (min maxlevel
  2302. (or (plist-get params :tcolumns) 100)
  2303. (if (null levels) 1 (apply #'max levels))))))
  2304. (indent (or compact? (plist-get params :indent)))
  2305. (formula (plist-get params :formula))
  2306. (case-fold-search t)
  2307. (total-time (apply #'+ (mapcar #'cadr tables)))
  2308. recalc narrow-cut-p)
  2309. (when (and narrow (integerp narrow) link)
  2310. ;; We cannot have both integer narrow and link.
  2311. (message "Using hard narrowing in clocktable to allow for links")
  2312. (setq narrow (intern (format "%d!" narrow))))
  2313. (pcase narrow
  2314. ((or `nil (pred integerp)) nil) ;nothing to do
  2315. ((and (pred symbolp)
  2316. (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow))))
  2317. (setq narrow-cut-p t)
  2318. (setq narrow (string-to-number (symbol-name narrow))))
  2319. (_ (error "Invalid value %s of :narrow property in clock table" narrow)))
  2320. ;; Now we need to output this table stuff.
  2321. (goto-char ipos)
  2322. ;; Insert the text *before* the actual table.
  2323. (insert-before-markers
  2324. (or header
  2325. ;; Format the standard header.
  2326. (format "#+CAPTION: %s %s%s\n"
  2327. (org-clock--translate "Clock summary at" lang)
  2328. (format-time-string (org-time-stamp-format t t))
  2329. (if block
  2330. (let ((range-text
  2331. (nth 2 (org-clock-special-range
  2332. block nil t
  2333. (plist-get params :wstart)
  2334. (plist-get params :mstart)))))
  2335. (format ", for %s." range-text))
  2336. ""))))
  2337. ;; Insert the narrowing line
  2338. (when (and narrow (integerp narrow) (not narrow-cut-p))
  2339. (insert-before-markers
  2340. "|" ;table line starter
  2341. (if multifile "|" "") ;file column, maybe
  2342. (if level? "|" "") ;level column, maybe
  2343. (if timestamp "|" "") ;timestamp column, maybe
  2344. (if tags "|" "") ;tags columns, maybe
  2345. (if properties ;properties columns, maybe
  2346. (make-string (length properties) ?|)
  2347. "")
  2348. (format "<%d>| |\n" narrow))) ;headline and time columns
  2349. ;; Insert the table header line
  2350. (insert-before-markers
  2351. "|" ;table line starter
  2352. (if multifile ;file column, maybe
  2353. (concat (org-clock--translate "File" lang) "|")
  2354. "")
  2355. (if level? ;level column, maybe
  2356. (concat (org-clock--translate "L" lang) "|")
  2357. "")
  2358. (if timestamp ;timestamp column, maybe
  2359. (concat (org-clock--translate "Timestamp" lang) "|")
  2360. "")
  2361. (if tags "Tags |" "") ;tags columns, maybe
  2362. (if properties ;properties columns, maybe
  2363. (concat (mapconcat #'identity properties "|") "|")
  2364. "")
  2365. (concat (org-clock--translate "Headline" lang)"|")
  2366. (concat (org-clock--translate "Time" lang) "|")
  2367. (make-string (max 0 (1- time-columns)) ?|) ;other time columns
  2368. (if (eq formula '%) "%|\n" "\n"))
  2369. ;; Insert the total time in the table
  2370. (insert-before-markers
  2371. "|-\n" ;a hline
  2372. "|" ;table line starter
  2373. (if multifile (format "| %s " (org-clock--translate "ALL" lang)) "")
  2374. ;file column, maybe
  2375. (if level? "|" "") ;level column, maybe
  2376. (if timestamp "|" "") ;timestamp column, maybe
  2377. (if tags "|" "") ;timestamp column, maybe
  2378. (make-string (length properties) ?|) ;properties columns, maybe
  2379. (concat (format org-clock-total-time-cell-format
  2380. (org-clock--translate "Total time" lang))
  2381. "| ")
  2382. (format org-clock-total-time-cell-format
  2383. (org-duration-from-minutes (or total-time 0))) ;time
  2384. "|"
  2385. (make-string (max 0 (1- time-columns)) ?|)
  2386. (cond ((not (eq formula '%)) "")
  2387. ((or (not total-time) (= total-time 0)) "0.0|")
  2388. (t "100.0|"))
  2389. "\n")
  2390. ;; Now iterate over the tables and insert the data but only if any
  2391. ;; time has been collected.
  2392. (when (and total-time (> total-time 0))
  2393. (pcase-dolist (`(,file-name ,file-time ,entries) tables)
  2394. (when (or (and file-time (> file-time 0))
  2395. (not (plist-get params :fileskip0)))
  2396. (insert-before-markers "|-\n") ;hline at new file
  2397. ;; First the file time, if we have multiple files.
  2398. (when multifile
  2399. ;; Summarize the time collected from this file.
  2400. (insert-before-markers
  2401. (format (concat "| %s %s | %s%s%s"
  2402. (format org-clock-file-time-cell-format
  2403. (org-clock--translate "File time" lang))
  2404. " | *%s*|\n")
  2405. (file-name-nondirectory file-name)
  2406. (if level? "| " "") ;level column, maybe
  2407. (if timestamp "| " "") ;timestamp column, maybe
  2408. (if tags "| " "") ;tags column, maybe
  2409. (if properties ;properties columns, maybe
  2410. (make-string (length properties) ?|)
  2411. "")
  2412. (org-duration-from-minutes file-time)))) ;time
  2413. ;; Get the list of node entries and iterate over it
  2414. (when (> maxlevel 0)
  2415. (pcase-dolist (`(,level ,headline ,tgs ,ts ,time ,props) entries)
  2416. (when narrow-cut-p
  2417. (setq headline
  2418. (if (and (string-match
  2419. (format "\\`%s\\'" org-bracket-link-regexp)
  2420. headline)
  2421. (match-end 3))
  2422. (format "[[%s][%s]]"
  2423. (match-string 1 headline)
  2424. (org-shorten-string (match-string 3 headline)
  2425. narrow))
  2426. (org-shorten-string headline narrow))))
  2427. (cl-flet ((format-field (f) (format (cond ((not emph) "%s |")
  2428. ((= level 1) "*%s* |")
  2429. ((= level 2) "/%s/ |")
  2430. (t "%s |"))
  2431. f)))
  2432. (insert-before-markers
  2433. "|" ;start the table line
  2434. (if multifile "|" "") ;free space for file name column?
  2435. (if level? (format "%d|" level) "") ;level, maybe
  2436. (if timestamp (concat ts "|") "") ;timestamp, maybe
  2437. (if tags (concat (mapconcat #'identity tgs ", ") "|") "") ;tags, maybe
  2438. (if properties ;properties columns, maybe
  2439. (concat (mapconcat (lambda (p) (or (cdr (assoc p props)) ""))
  2440. properties
  2441. "|")
  2442. "|")
  2443. "")
  2444. (if indent ;indentation
  2445. (org-clocktable-indent-string level)
  2446. "")
  2447. (format-field headline)
  2448. ;; Empty fields for higher levels.
  2449. (make-string (max 0 (1- (min time-columns level))) ?|)
  2450. (format-field (org-duration-from-minutes time))
  2451. (make-string (max 0 (- time-columns level)) ?|)
  2452. (if (eq formula '%)
  2453. (format "%.1f |" (* 100 (/ time (float total-time))))
  2454. "")
  2455. "\n")))))))
  2456. (delete-char -1)
  2457. (cond
  2458. ;; Possibly rescue old formula?
  2459. ((or (not formula) (eq formula '%))
  2460. (let ((contents (org-string-nw-p (plist-get params :content))))
  2461. (when (and contents (string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents))
  2462. (setq recalc t)
  2463. (insert "\n" (match-string 1 contents))
  2464. (beginning-of-line 0))))
  2465. ;; Insert specified formula line.
  2466. ((stringp formula)
  2467. (insert "\n#+TBLFM: " formula)
  2468. (setq recalc t))
  2469. (t
  2470. (user-error "Invalid :formula parameter in clocktable")))
  2471. ;; Back to beginning, align the table, recalculate if necessary.
  2472. (goto-char ipos)
  2473. (skip-chars-forward "^|")
  2474. (org-table-align)
  2475. (when org-hide-emphasis-markers
  2476. ;; We need to align a second time.
  2477. (org-table-align))
  2478. (when sort
  2479. (save-excursion
  2480. (org-table-goto-line 3)
  2481. (org-table-goto-column (car sort))
  2482. (org-table-sort-lines nil (cdr sort))))
  2483. (when recalc (org-table-recalculate 'all))
  2484. total-time))
  2485. (defun org-clocktable-indent-string (level)
  2486. "Return indentation string according to LEVEL.
  2487. LEVEL is an integer. Indent by two spaces per level above 1."
  2488. (if (= level 1) ""
  2489. (concat "\\_" (make-string (* 2 (1- level)) ?\s))))
  2490. (defun org-clocktable-increment-day (ts &optional n)
  2491. "Increment day in TS by N (defaulting to 1).
  2492. The TS argument has the same type as the return values of
  2493. `float-time' or `current-time'."
  2494. (let ((tsd (org-decode-time ts)))
  2495. (cl-incf (nth 3 tsd) (or n 1))
  2496. (setf (nth 8 tsd) nil) ; no time zone: increasing day skips one whole day
  2497. (apply 'encode-time tsd)))
  2498. (defun org-clocktable-steps (params)
  2499. "Step through the range to make a number of clock tables."
  2500. (let* ((ts (plist-get params :tstart))
  2501. (te (plist-get params :tend))
  2502. (ws (plist-get params :wstart))
  2503. (ms (plist-get params :mstart))
  2504. (step0 (plist-get params :step))
  2505. (stepskip0 (plist-get params :stepskip0))
  2506. (block (plist-get params :block))
  2507. cc tsb)
  2508. (when block
  2509. (setq cc (org-clock-special-range block nil t ws ms)
  2510. ts (or (car cc)
  2511. ;; The year Org was born.
  2512. "<2003-01-01 Thu 00:00>")
  2513. te (nth 1 cc)))
  2514. (cond
  2515. ((numberp ts)
  2516. ;; If ts is a number, it's an absolute day number from
  2517. ;; org-agenda.
  2518. (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute ts)))
  2519. (setq ts (float-time (encode-time 0 0 0 day month year)))))
  2520. (ts (setq ts (org-matcher-time ts))))
  2521. (cond
  2522. ((numberp te)
  2523. ;; Likewise for te.
  2524. (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute te)))
  2525. (setq te (float-time (encode-time 0 0 0 day month year)))))
  2526. (te (setq te (org-matcher-time te))))
  2527. (setq tsb
  2528. (if (eq step0 'week)
  2529. (let ((dow (nth 6 (org-decode-time ts))))
  2530. (if (<= dow ws) ts
  2531. (float-time (org-clocktable-increment-day ts ; decrement
  2532. (- ws dow)))))
  2533. ts))
  2534. (while (< tsb te)
  2535. (unless (bolp) (insert "\n"))
  2536. (let* ((start-time (max tsb ts))
  2537. (dow (nth 6 (org-decode-time tsb)))
  2538. (days-to-skip (cond ((eq step0 'day) 1)
  2539. ;; else 'week:
  2540. ((= dow ws) 7)
  2541. (t (- ws dow)))))
  2542. (setq tsb (float-time (org-clocktable-increment-day tsb days-to-skip)))
  2543. (insert "\n"
  2544. (if (eq step0 'day) "Daily report: "
  2545. "Weekly report starting on: ")
  2546. (org-format-time-string (org-time-stamp-format nil t) start-time)
  2547. "\n")
  2548. (let ((table-begin (line-beginning-position 0))
  2549. (step-time
  2550. (org-dblock-write:clocktable
  2551. (org-combine-plists
  2552. params
  2553. (list
  2554. :header "" :step nil :block nil
  2555. :tstart (org-format-time-string (org-time-stamp-format t t)
  2556. start-time)
  2557. :tend (org-format-time-string (org-time-stamp-format t t)
  2558. (min te tsb)))))))
  2559. (re-search-forward "^[ \t]*#\\+END:")
  2560. (when (and stepskip0 (equal step-time 0))
  2561. ;; Remove the empty table
  2562. (delete-region (line-beginning-position) table-begin))))
  2563. (end-of-line 0))))
  2564. (defun org-clock-get-table-data (file params)
  2565. "Get the clocktable data for file FILE, with parameters PARAMS.
  2566. FILE is only for identification - this function assumes that
  2567. the correct buffer is current, and that the wanted restriction is
  2568. in place.
  2569. The return value will be a list with the file name and the total
  2570. file time (in minutes) as 1st and 2nd elements. The third element
  2571. of this list will be a list of headline entries. Each entry has the
  2572. following structure:
  2573. (LEVEL HEADLINE TAGS TIMESTAMP TIME PROPERTIES)
  2574. LEVEL: The level of the headline, as an integer. This will be
  2575. the reduced level, so 1,2,3,... even if only odd levels
  2576. are being used.
  2577. HEADLINE: The text of the headline. Depending on PARAMS, this may
  2578. already be formatted like a link.
  2579. TAGS: The list of tags of the headline.
  2580. TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
  2581. entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
  2582. in this sequence.
  2583. TIME: The sum of all time spend in this tree, in minutes. This time
  2584. will of cause be restricted to the time block and tags match
  2585. specified in PARAMS.
  2586. PROPERTIES: The list properties specified in the `:properties' parameter
  2587. along with their value, as an alist following the pattern
  2588. (NAME . VALUE)."
  2589. (let* ((maxlevel (or (plist-get params :maxlevel) 3))
  2590. (timestamp (plist-get params :timestamp))
  2591. (ts (plist-get params :tstart))
  2592. (te (plist-get params :tend))
  2593. (ws (plist-get params :wstart))
  2594. (ms (plist-get params :mstart))
  2595. (block (plist-get params :block))
  2596. (link (plist-get params :link))
  2597. (tags (plist-get params :tags))
  2598. (match (plist-get params :match))
  2599. (properties (plist-get params :properties))
  2600. (inherit-property-p (plist-get params :inherit-props))
  2601. (matcher (and match (cdr (org-make-tags-matcher match))))
  2602. cc st p tbl)
  2603. (setq org-clock-file-total-minutes nil)
  2604. (when block
  2605. (setq cc (org-clock-special-range block nil t ws ms)
  2606. ts (car cc)
  2607. te (nth 1 cc)))
  2608. (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
  2609. (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
  2610. (when (and ts (listp ts))
  2611. (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
  2612. (when (and te (listp te))
  2613. (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
  2614. ;; Now the times are strings we can parse.
  2615. (if ts (setq ts (org-matcher-time ts)))
  2616. (if te (setq te (org-matcher-time te)))
  2617. (save-excursion
  2618. (org-clock-sum ts te
  2619. (when matcher
  2620. `(lambda ()
  2621. (let* ((todo (org-get-todo-state))
  2622. (tags-list (org-get-tags))
  2623. (org-scanner-tags tags-list)
  2624. (org-trust-scanner-tags t))
  2625. (funcall ,matcher todo tags-list nil)))))
  2626. (goto-char (point-min))
  2627. (setq st t)
  2628. (while (or (and (bobp) (prog1 st (setq st nil))
  2629. (get-text-property (point) :org-clock-minutes)
  2630. (setq p (point-min)))
  2631. (setq p (next-single-property-change
  2632. (point) :org-clock-minutes)))
  2633. (goto-char p)
  2634. (let ((time (get-text-property p :org-clock-minutes)))
  2635. (when (and time (> time 0) (org-at-heading-p))
  2636. (let ((level (org-reduced-level (org-current-level))))
  2637. (when (<= level maxlevel)
  2638. (let* ((headline (org-get-heading t t t t))
  2639. (hdl
  2640. (if (not link) headline
  2641. (let ((search
  2642. (org-make-org-heading-search-string headline)))
  2643. (org-make-link-string
  2644. (if (not (buffer-file-name)) search
  2645. (format "file:%s::%s" (buffer-file-name) search))
  2646. ;; Prune statistics cookies. Replace
  2647. ;; links with their description, or
  2648. ;; a plain link if there is none.
  2649. (org-trim
  2650. (org-link-display-format
  2651. (replace-regexp-in-string
  2652. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  2653. headline)))))))
  2654. (tgs (and tags (org-get-tags)))
  2655. (tsp
  2656. (and timestamp
  2657. (cl-some (lambda (p) (org-entry-get (point) p))
  2658. '("SCHEDULED" "DEADLINE" "TIMESTAMP"
  2659. "TIMESTAMP_IA"))))
  2660. (props
  2661. (and properties
  2662. (delq nil
  2663. (mapcar
  2664. (lambda (p)
  2665. (let ((v (org-entry-get
  2666. (point) p inherit-property-p)))
  2667. (and v (cons p v))))
  2668. properties)))))
  2669. (push (list level hdl tgs tsp time props) tbl)))))))
  2670. (list file org-clock-file-total-minutes (nreverse tbl)))))
  2671. ;; Saving and loading the clock
  2672. (defvar org-clock-loaded nil
  2673. "Was the clock file loaded?")
  2674. ;;;###autoload
  2675. (defun org-clock-update-time-maybe ()
  2676. "If this is a CLOCK line, update it and return t.
  2677. Otherwise, return nil."
  2678. (interactive)
  2679. (save-excursion
  2680. (beginning-of-line 1)
  2681. (skip-chars-forward " \t")
  2682. (when (looking-at org-clock-string)
  2683. (let ((re (concat "[ \t]*" org-clock-string
  2684. " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
  2685. "\\([ \t]*=>.*\\)?\\)?"))
  2686. ts te h m s neg)
  2687. (cond
  2688. ((not (looking-at re))
  2689. nil)
  2690. ((not (match-end 2))
  2691. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  2692. (> org-clock-marker (point))
  2693. (<= org-clock-marker (point-at-eol)))
  2694. ;; The clock is running here
  2695. (setq org-clock-start-time
  2696. (org-time-string-to-time (match-string 1)))
  2697. (org-clock-update-mode-line)))
  2698. (t
  2699. (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
  2700. (end-of-line 1)
  2701. (setq ts (match-string 1)
  2702. te (match-string 3))
  2703. (setq s (- (float-time
  2704. (apply #'encode-time (org-parse-time-string te)))
  2705. (float-time
  2706. (apply #'encode-time (org-parse-time-string ts))))
  2707. neg (< s 0)
  2708. s (abs s)
  2709. h (floor (/ s 3600))
  2710. s (- s (* 3600 h))
  2711. m (floor (/ s 60))
  2712. s (- s (* 60 s)))
  2713. (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
  2714. t))))))
  2715. (defun org-clock-save ()
  2716. "Persist various clock-related data to disk.
  2717. The details of what will be saved are regulated by the variable
  2718. `org-clock-persist'."
  2719. (when (and org-clock-persist
  2720. (or org-clock-loaded
  2721. org-clock-has-been-used
  2722. (not (file-exists-p org-clock-persist-file))))
  2723. (with-temp-file org-clock-persist-file
  2724. (insert (format ";; %s - %s at %s\n"
  2725. (file-name-nondirectory org-clock-persist-file)
  2726. (system-name)
  2727. (format-time-string (org-time-stamp-format t))))
  2728. ;; Store clock to be resumed.
  2729. (when (and (memq org-clock-persist '(t clock))
  2730. (let ((b (org-base-buffer (org-clocking-buffer))))
  2731. (and (buffer-live-p b)
  2732. (buffer-file-name b)
  2733. (or (not org-clock-persist-query-save)
  2734. (y-or-n-p (format "Save current clock (%s) "
  2735. org-clock-heading))))))
  2736. (insert
  2737. (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
  2738. (buffer-file-name (org-base-buffer (org-clocking-buffer)))
  2739. (marker-position org-clock-marker))))
  2740. ;; Store clocked task history. Tasks are stored reversed to
  2741. ;; make reading simpler.
  2742. (when (and (memq org-clock-persist '(t history))
  2743. org-clock-history)
  2744. (insert
  2745. (format "(setq org-clock-stored-history '(%s))\n"
  2746. (mapconcat
  2747. (lambda (m)
  2748. (let ((b (org-base-buffer (marker-buffer m))))
  2749. (when (and (buffer-live-p b)
  2750. (buffer-file-name b))
  2751. (format "(%S . %d)"
  2752. (buffer-file-name b)
  2753. (marker-position m)))))
  2754. (reverse org-clock-history)
  2755. " ")))))))
  2756. (defun org-clock-load ()
  2757. "Load clock-related data from disk, maybe resuming a stored clock."
  2758. (when (and org-clock-persist (not org-clock-loaded))
  2759. (if (not (file-readable-p org-clock-persist-file))
  2760. (message "Not restoring clock data; %S not found" org-clock-persist-file)
  2761. (message "Restoring clock data")
  2762. ;; Load history.
  2763. (load-file org-clock-persist-file)
  2764. (setq org-clock-loaded t)
  2765. (pcase-dolist (`(,(and file (pred file-exists-p)) . ,position)
  2766. org-clock-stored-history)
  2767. (org-clock-history-push position (find-file-noselect file)))
  2768. ;; Resume clock.
  2769. (pcase org-clock-stored-resume-clock
  2770. (`(,(and file (pred file-exists-p)) . ,position)
  2771. (with-current-buffer (find-file-noselect file)
  2772. (when (or (not org-clock-persist-query-resume)
  2773. (y-or-n-p (format "Resume clock (%s) "
  2774. (save-excursion
  2775. (goto-char position)
  2776. (org-get-heading t t)))))
  2777. (goto-char position)
  2778. (let ((org-clock-in-resume 'auto-restart)
  2779. (org-clock-auto-clock-resolution nil))
  2780. (org-clock-in)
  2781. (when (org-invisible-p) (org-show-context))))))
  2782. (_ nil)))))
  2783. ;; Suggested bindings
  2784. (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
  2785. (provide 'org-clock)
  2786. ;; Local variables:
  2787. ;; generated-autoload-file: "org-loaddefs.el"
  2788. ;; coding: utf-8
  2789. ;; End:
  2790. ;;; org-clock.el ends here