org-clock.el 108 KB

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