org-clock.el 108 KB

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