org-clock.el 103 KB

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