org-clock.el 106 KB

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