org-clock.el 109 KB

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