org-clock.el 108 KB

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