org-clock.el 107 KB

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