org-clock.el 101 KB

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