org-clock.el 102 KB

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