org-clock.el 109 KB

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