org-clock.el 108 KB

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