org-clock.el 107 KB

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