org-clock.el 109 KB

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