org-clock.el 103 KB

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