org-clock.el 109 KB

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