org-clock.el 106 KB

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