org-clock.el 109 KB

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