view lisp/battery.el @ 98644:e1cc41b9282d

2008-10-12 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-edit-fixed-width-region): Exclude final newline from picture area. * org-export-latex.el (org-export-latex-subcontent): Add labels to sections, to make internal links work. (org-export-latex-fontify-headline): Do not remove all text properties, to make sure that target properties survive this process. * org-exp.el (org-export-preprocess-string): Change sequence of modifications, to make sure links are prepared before the LaTeX conversions do happen. * org-attach.el (org-attach-delete-all): Renamed from `org-attch-delete'. Add a security query before deleting the entire directory. New optional argument FORCE can overrule the security query. (org-attach-delete-one): New command. * org-attach.el (org-attach-file-list): Fix bug with directory. * org.el (org-apps-regexp-alist): New function. (org-file-apps): Add auto-mode to the default value. (org-open-file): Use the new structure of org-file-apps. * org-attach.el (org-attach): Support the new keys. (org-attach-method): New option. * org-bbdb.el (org-bbdb-anniversaries): Fix but with 29 Feb/1 March. * org.el (org-remove-uniherited-tags): Fix reverse interpretation of the list value o `org-use-tag-inheritance'. * org-attach.el (org-attach-auto-tag): New option. (org-attach-tag, org-attach-untag): New functions. (org-attach-attach, org-attach-new, org-attach-sync): Call `org-attach-tag'. (org-attach-delete): Call `org-attach-untag'. * org-attach.el: New file. * org-table.el (orgtbl-self-insert-command): Make this work for the keypad as well. * org.el (org-add-log-setup): Limit searc for drawers to entry text, not to subtree. * org-clock.el (org-clock-heading-for-remember): New variable. (org-clock-in): Set `org-clock-heading-for-remember'. 2008-10-12 James TD Smith <ahktenzero@mohorovi.cc> * org-remember.el (org-remember-apply-template): Add new expansions: %k, %K for currently clocked task and a link to the currently clocked task, and %< to file notes in the currently clocked task. 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-export-latex.el (org-export-latex-make-header): Also insert the content of the property :latex-header-extra. * org-exp.el (org-infile-export-plist): Put the content of #+LATEX_HEADER: into the property :latex-header-extra. * org-colview.el (org-columns-get-format-and-top-level): Remove resetting the marker. * org-colview-xemacs.el (org-columns-get-format-and-top-level): Remove resetting the marker. * org.el (org-entry-property-inherited-from): Improve docstring. (org-entry-get-with-inheritance): Reset marker before starting the search. * org-exp.el (org-infile-export-plist): Allow multiple STYLE lines. * org.el (org-entry-get-multivalued-property) (org-entry-protect-space, org-entry-restore-space): New functions. (org-file-apps-defaults-macosx): Let postscript files be opened by preview. (org-time-stamp-inactive): Call `org-time-stamp'. (org-time-stamp): New argument `inactive'. Also edit inacive stamps. Convert time stamp type. (org-open-file): Interpret the `default' value for the `command' in `org-file-apps'. * org-id.el (org-id-int-to-b36-one-digit) (org-id-b36-to-int-one-digit, org-id-int-to-b36) (org-id-b36-to-int, org-id-time-to-b36): Modified from b62 to b36. * org-id.el (org-id-reverse-string): New function. (org-id-new): Use `org-id-reverse-string' to make sure the beginning chars of the ID are mutating fast. This allows to use a directory structure to spread things better. (org-id-prefix): Changed default to nil. * org-list.el (org-move-item-down, org-move-item-up): Remember and restore the column of the cursor position. * org-remember.el (org-remember-apply-template): Remove properties from `initial'. * org-wl.el (org-wl-open): Remove useless call to `wl-thread-open-all'. * org-remember.el (org-remember-handler): Fix bug with `bottom' location. * org-bbdb.el (org-bbdb-anniversaries): Require bbdb in `org-bbdb-anniversaries'. * org.el (org-get-next-sibling, org-forward-same-level): New functions, similar to the outline versions, but invisible headings are OK. 2008-10-12 Bastien Guerry <bzg@altern.org> * org.el (org-auto-repeat-maybe): Insert a space between the timestamp's type and the timestamp itself. 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-table.el (org-table-sum): Do not format the result with %g, it does rounding when there are too many digits. * org.el (org-map-entries): Protect the keyword-selecting variables. 2008-10-12 Bastien Guerry <bzg@altern.org> * org-agenda.el (org-agenda-to-appt): Make sure the function check against all agenda files. 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-list.el: New file, aggregating list functions from org.el and org-export-latex.el. * org.el (org-edit-src-region-extra): New option. * org-agenda.el (org-agenda-to-appt): Fix bug with appointment time before 1am. 2008-10-12 Bastien Guerry <bzg@altern.org> * org-export-latex.el (org-export-latex-keywords-maybe): Bug fix. 2008-10-12 James TA Smith <ahktenzero@mohorovi.cc> * org-plot.el (org-plot/gnuplot): Make tables starting with a hline work correctly. (org-plot/gnuplot-script): Put commas at the end of each script line. * org.el (org-get-refile-targets): Replace links with their descriptions (org-imenu-get-tree): Replace links with their descriptions. * org-remember.el (org-remember-apply-template): Add a new expansion for adding properties to remember items. * org.el (org-add-log-setup): Skip over drawers (properties, clocks etc) when adding notes. * org-agenda.el (org-agenda-get-closed): show durations of clocked items as well as the start and end times. * org-compat.el (org-get-x-clipboard-compat): Add a compat function for fetching the X clipboard on XEmacs and GNU Emacs 21. * org-remember.el (org-get-x-clipboard): Use the compat function to get clipboard values when x-selection-value is unavailable. Use substring-no-properties instead of set-text-properties to remove text properties from the clipboard value. * lisp/org-clock.el (org-update-mode-line): Support limiting the modeline clock string, and display the full todo value in the tooltip. Set a local keymap so mouse-3 on the clock string goes to the currently clocked task. (org-clock-string-limit): Add a custom value for the maximum length of the clock string in the modeline. (org-clock-mode-map): Add a keymap for the modeline string 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-compat.el (org-propertize): New function. 2008-10-12 Bastien Guerry <bzg@altern.org> * org-export-latex.el (org-export-latex-tables): protect exported tables from further special chars conversion. (org-export-latex-preprocess): Preserve LaTeX environments. (org-list-parse-list): Parse descriptive lists. (org-list-to-generic, org-list-to-latex, org-list-to-html) (org-list-to-texinfo): Export descriptive lists. (org-quote-chars): Remove. (org-export-latex-keywords-maybe): Use `replace-regexp-in-string'. (org-export-latex-list-beginning-re): Rename to `org-list-beginning-re' (org-list-item-begin): Rename to `org-list-item-beginning' 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org.el (org-refile): Allow refiling to the last entry in the buffer. (org-get-tags-at): Fix bug when inheritance is turned off. * org.el (org-indent-line-function): No longer check for src regions, this is too much overhead. * org-agenda.el (org-agenda-highlight-todo): Fix bugs with keyword matching. * org.el (org-scan-tags): Make sure that tags matching is not case sensitive. TODO keyword matching is case sensitive, however, to avoid confusion with similar words that are not meant to be keywords. * org.el (org-get-local-tags-at): New function. (org-get-local-tags): New function. * org-exp.el (org-export-get-categories): New function. * org-agenda.el (org-sorting-choice) (org-agenda-sorting-strategy, org-agenda-get-todos) (org-agenda-get-timestamps, org-agenda-get-deadlines) (org-agenda-get-scheduled, org-agenda-get-blocks) (org-entries-lessp): Implement sorting by TODO state. (org-cmp-todo-state): New defsubst. * org-colview.el (org-colview-construct-allowed-dates): New function. (org-columns-next-allowed-value): Use `org-colview-construct-allowed-dates'. * org-colview-xemacs.el (org-colview-construct-allowed-dates): New function. (org-columns-next-allowed-value): Use `org-colview-construct-allowed-dates'. * org.el (org-protect-slash): New function. (org-get-refile-targets): Use `org-protect-slash'. * org-agenda.el (org-global-tags-completion-table): New variable. * org-exp.el (org-export-handle-export-tags): New function. (org-export-preprocess-string): Call `org-export-handle-export-tags'. * org-plot.el: New file. * org-publish.el (org-publish-expand-components): Function removed. (org-publish-expand-projects): Allow components to have components. * org.el (org-indent-line-function): Do not indent in regions that are external source code. (org-yank-and-fold-if-subtree): New function. * org-agenda.el (org-agenda-todayp): New function. (org-agenda-get-deadlines, org-agenda-get-scheduled): Use `org-agenda-todayp'. * org.el (org-insert-heading-respect-content) (org-insert-todo-heading-respect-content): New commands. (org-insert-heading-respect-content): New option. (org-insert-heading): Respect `org-insert-heading-respect-content'. * org-clock.el (org-clock-find-position): Make sure the note after the clock line gets moved into the new clock drawer. * org-id.el (org-id-new): New option. * org-table.el (org-table-copy-down): Avoid overflow during increment. Use prefix argument 0 to temporarily disable the increment. * org-exp.el (org-export-as-html): Do not turn on the major mode if the buffer will be killed anyway. (org-get-current-options): Exclude the #+TEXT field. (org-export-as-html): Make sure text before the first headline is a paragraph. * org-publish.el (org-publish-org-to): Tell the exporter that this buffer will be killed, so it is not necessary to do major mode initialization. * org-archive.el (org-archive-to-archive-sibling): Show empty lines after folding the archive sibling. * org.el (org-log-note-extra): New variable. 2008-10-12 Bastien Guerry <bzg@altern.org> * org.el (org-additional-option-like-keywords): Added keywords for the _QUOTE, _VERSE and _SRC environments. * org-export-latex.el (org-export-latex-preprocess): Fix bug when exporting _QUOTE and _VERSE environments. 2008-10-12 Carsten Dominik <dominik@science.uva.nl> * org-agenda.el (org-agenda-filter-by-tag): New command. * org-exp.el (org-get-current-options): Remove angular brackets from the date entry. * org.el (org-edit-fixed-width-region): New function. (org-edit-fixed-width-region): Also try `org-edit-fixed-width-region'. (org-edit-fixed-width-region-mode): New option. (org-activate-code): Only interprete lines starting with colon plus a space as example lines. * org-remember.el (org-remember-templates): Add nil instead of empty strings to fix the length of remember templates. * org-table.el (org-calc-default-modes): Fix the time format for calc, from 12 hour to 24 hour clock. * org-agenda.el (org-agenda-get-deadlines) (org-agenda-get-scheduled): Avoid `time-of-day' extraction for entries that are pre-warnings of deadlines or reminders. * org.el (org-sort-entries-or-items): Make numeric and alpha comparisons ignore any TODO keyword and priority cookie. * org-remember.el (org-remember-handler): Reinterpretation of the prefix argument. * org-agenda.el (org-agenda-get-scheduled): Use new `org-scheduled' face. * org-faces.el (org-scheduled): New face. * org-wl.el (org-wl-open): Remove incorrect declaration. * org-gnus.el (org-gnus-store-link): Support for :to information in gnus links. * org-exp.el (org-export-as-html): Fixed typo in creator information. (org-export-protect-examples): New parameter indent. Insert extra spaces only when this parameter is specified. (org-export-preprocess-string): Call `org-export-protect-examples' with an indentation parameter when exporting to ASCII. * org-remember.el (org-remember-templates) (org-remember-apply-template): Allow the file component to be a function. * org.el (org-goto-local-search-headings): Renamed from `org-goto-local-search-forward-headings'. Added the possibility to search backwards. * org-export-latex.el (org-export-latex): New customization group. * org-agenda.el (org-write-agenda): Erase buffer for txt export. * org-exp.el (org-html-do-expand): Allow {} to terminate tex macro * org.el (org-buffer-list): Select buffers based on major mode, not on file name. * org-agenda.el (org-agenda-align-tags): Fix bug with malformed face property. * org-colview.el (org-columns-display-here): Use `org-columns-modify-value-for-display-function'. * org-colview-xemacs.el (org-columns-display-here): Use `org-columns-modify-value-for-display-function'. * org.el (org-columns-modify-value-for-display-function): New option. * org-publish.el (org-publish-file): Make sure the directory match for the publishing directory works correctly. * org-agenda.el (org-agenda-execute-calendar-command) (org-agenda-diary-entry): Additional optional argument.
author Carsten Dominik <dominik@science.uva.nl>
date Sun, 12 Oct 2008 06:12:44 +0000
parents a7ddf766669d
children d42aff5ca541
line wrap: on
line source

;;; battery.el --- display battery status information  -*- coding: iso-8859-1 -*-

;; Copyright (C) 1997, 1998, 2000, 2001, 2002, 2003, 2004,
;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.

;; Author: Ralph Schleicher <rs@nunatak.allgaeu.org>
;; Keywords: hardware

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; There is at present support for GNU/Linux, OS X and Windows.  This
;; library supports both the `/proc/apm' file format of Linux version
;; 1.3.58 or newer and the `/proc/acpi/' directory structure of Linux
;; 2.4.20 and 2.6.  Darwin (OS X) is supported by using the `pmset'
;; program.  Windows is supported by the GetSystemPowerStatus API call.

;;; Code:

(require 'timer)
(eval-when-compile (require 'cl))


(defgroup battery nil
  "Display battery status information."
  :prefix "battery-"
  :group 'hardware)

(defcustom battery-status-function
  (cond ((and (eq system-type 'gnu/linux)
	      (file-readable-p "/proc/apm"))
	 'battery-linux-proc-apm)
	((and (eq system-type 'gnu/linux)
	      (file-directory-p "/proc/acpi/battery"))
	 'battery-linux-proc-acpi)
	((and (eq system-type 'gnu/linux)
	      (file-directory-p "/sys/class/power_supply/")
	      (directory-files "/sys/class/power_supply/" nil "BAT[0-9]$"))
	 'battery-linux-sysfs)
	((and (eq system-type 'darwin)
	      (condition-case nil
		  (with-temp-buffer
		    (and (eq (call-process "pmset" nil t nil "-g" "ps") 0)
			 (> (buffer-size) 0)))
		(error nil)))
	 'battery-pmset)
	((eq system-type 'windows-nt)
	 'w32-battery-status))
  "*Function for getting battery status information.
The function has to return an alist of conversion definitions.
Its cons cells are of the form

    (CONVERSION . REPLACEMENT-TEXT)

CONVERSION is the character code of a \"conversion specification\"
introduced by a `%' character in a control string."
  :type '(choice (const nil) function)
  :group 'battery)

(defcustom battery-echo-area-format
  (cond ((eq battery-status-function 'battery-linux-proc-acpi)
	 "Power %L, battery %B at %r (%p%% load, remaining time %t)")
	((eq battery-status-function 'battery-linux-sysfs)
	 "Power %L, battery %B (%p%% load)")
	((eq battery-status-function 'battery-pmset)
	 "%L power, battery %B (%p%% load, remaining time %t)")
	(battery-status-function
	 "Power %L, battery %B (%p%% load, remaining time %t)"))
  "*Control string formatting the string to display in the echo area.
Ordinary characters in the control string are printed as-is, while
conversion specifications introduced by a `%' character in the control
string are substituted as defined by the current value of the variable
`battery-status-function'.  Here are the ones generally available:
%c Current capacity (mAh or mWh)
%r Current rate of charge or discharge
%B Battery status (verbose)
%b Battery status: empty means high, `-' means low,
   `!' means critical, and `+' means charging
%d Temperature (in degrees Celsius)
%L AC line status (verbose)
%p Battery load percentage
%m Remaining time (to charge or discharge) in minutes
%h Remaining time (to charge or discharge) in hours
%t Remaining time (to charge or discharge) in the form `h:min'"
  :type '(choice string (const nil))
  :group 'battery)

(defvar battery-mode-line-string nil
  "String to display in the mode line.")
;;;###autoload (put 'battery-mode-line-string 'risky-local-variable t)

(defcustom battery-mode-line-format
  (cond ((eq battery-status-function 'battery-linux-proc-acpi)
	 "[%b%p%%,%d°C]")
	(battery-status-function
	 "[%b%p%%]"))
  "*Control string formatting the string to display in the mode line.
Ordinary characters in the control string are printed as-is, while
conversion specifications introduced by a `%' character in the control
string are substituted as defined by the current value of the variable
`battery-status-function'.  Here are the ones generally available:
%c Current capacity (mAh or mWh)
%r Current rate of charge or discharge
%B Battery status (verbose)
%b Battery status: empty means high, `-' means low,
   `!' means critical, and `+' means charging
%d Temperature (in degrees Celsius)
%L AC line status (verbose)
%p Battery load percentage
%m Remaining time (to charge or discharge) in minutes
%h Remaining time (to charge or discharge) in hours
%t Remaining time (to charge or discharge) in the form `h:min'"
  :type '(choice string (const nil))
  :group 'battery)

(defcustom battery-update-interval 60
  "*Seconds after which the battery status will be updated."
  :type 'integer
  :group 'battery)

(defcustom battery-load-low 25
  "*Upper bound of low battery load percentage.
A battery load percentage below this number is considered low."
  :type 'integer
  :group 'battery)

(defcustom battery-load-critical 10
  "*Upper bound of critical battery load percentage.
A battery load percentage below this number is considered critical."
  :type 'integer
  :group 'battery)

(defvar battery-update-timer nil
  "Interval timer object.")

;;;###autoload
(defun battery ()
  "Display battery status information in the echo area.
The text being displayed in the echo area is controlled by the variables
`battery-echo-area-format' and `battery-status-function'."
  (interactive)
  (message "%s" (if (and battery-echo-area-format battery-status-function)
		    (battery-format battery-echo-area-format
				    (funcall battery-status-function))
		  "Battery status not available")))

;;;###autoload
(define-minor-mode display-battery-mode
  "Display battery status information in the mode line.
The text being displayed in the mode line is controlled by the variables
`battery-mode-line-format' and `battery-status-function'.
The mode line will be updated automatically every `battery-update-interval'
seconds."
  :global t :group 'battery
  (setq battery-mode-line-string "")
  (or global-mode-string (setq global-mode-string '("")))
  (and battery-update-timer (cancel-timer battery-update-timer))
  (if (not display-battery-mode)
      (setq global-mode-string
	    (delq 'battery-mode-line-string global-mode-string))
    (add-to-list 'global-mode-string 'battery-mode-line-string t)
    (setq battery-update-timer (run-at-time nil battery-update-interval
					    'battery-update-handler))
    (battery-update)))

(defun battery-update-handler ()
  (battery-update)
  (sit-for 0))

(defun battery-update ()
  "Update battery status information in the mode line."
  (setq battery-mode-line-string
	(propertize (if (and battery-mode-line-format
			     battery-status-function)
			(battery-format
			 battery-mode-line-format
			 (funcall battery-status-function))
		      "")
		    'help-echo "Battery status information"))
  (force-mode-line-update))


;;; `/proc/apm' interface for Linux.

(defconst battery-linux-proc-apm-regexp
  (concat "^\\([^ ]+\\)"		; Driver version.
	  " \\([^ ]+\\)"		; APM BIOS version.
	  " 0x\\([0-9a-f]+\\)"		; APM BIOS flags.
	  " 0x\\([0-9a-f]+\\)"		; AC line status.
	  " 0x\\([0-9a-f]+\\)"		; Battery status.
	  " 0x\\([0-9a-f]+\\)"		; Battery flags.
	  " \\(-?[0-9]+\\)%"		; Load percentage.
	  " \\(-?[0-9]+\\)"		; Remaining time.
	  " \\(.*\\)"			; Time unit.
	  "$")
  "Regular expression matching contents of `/proc/apm'.")

(defun battery-linux-proc-apm ()
  "Get APM status information from Linux kernel.
This function works only with the new `/proc/apm' format introduced
in Linux version 1.3.58.

The following %-sequences are provided:
%v Linux driver version
%V APM BIOS version
%I APM BIOS status (verbose)
%L AC line status (verbose)
%B Battery status (verbose)
%b Battery status, empty means high, `-' means low,
   `!' means critical, and `+' means charging
%p Battery load percentage
%s Remaining time (to charge or discharge) in seconds
%m Remaining time (to charge or discharge) in minutes
%h Remaining time (to charge or discharge) in hours
%t Remaining time (to charge or discharge) in the form `h:min'"
  (let (driver-version bios-version bios-interface line-status
	battery-status battery-status-symbol load-percentage
	seconds minutes hours remaining-time tem)
    (with-temp-buffer
      (ignore-errors (insert-file-contents "/proc/apm"))
      (when (re-search-forward battery-linux-proc-apm-regexp)
	(setq driver-version (match-string 1))
	(setq bios-version (match-string 2))
	(setq tem (string-to-number (match-string 3) 16))
	(if (not (logand tem 2))
	    (setq bios-interface "not supported")
	  (setq bios-interface "enabled")
	  (cond ((logand tem 16) (setq bios-interface "disabled"))
		((logand tem 32) (setq bios-interface "disengaged")))
	  (setq tem (string-to-number (match-string 4) 16))
	  (cond ((= tem 0) (setq line-status "off-line"))
		((= tem 1) (setq line-status "on-line"))
		((= tem 2) (setq line-status "on backup")))
	  (setq tem (string-to-number (match-string 6) 16))
	  (if (= tem 255)
	      (setq battery-status "N/A")
	    (setq tem (string-to-number (match-string 5) 16))
	    (cond ((= tem 0) (setq battery-status "high"
				   battery-status-symbol ""))
		  ((= tem 1) (setq battery-status "low"
				   battery-status-symbol "-"))
		  ((= tem 2) (setq battery-status "critical"
				   battery-status-symbol "!"))
		  ((= tem 3) (setq battery-status "charging"
				   battery-status-symbol "+")))
	    (setq load-percentage (match-string 7))
	    (setq seconds (string-to-number (match-string 8)))
	    (and (string-equal (match-string 9) "min")
		 (setq seconds (* 60 seconds)))
	    (setq minutes (/ seconds 60)
		  hours (/ seconds 3600))
	    (setq remaining-time
		  (format "%d:%02d" hours (- minutes (* 60 hours))))))))
    (list (cons ?v (or driver-version "N/A"))
	  (cons ?V (or bios-version "N/A"))
	  (cons ?I (or bios-interface "N/A"))
	  (cons ?L (or line-status "N/A"))
	  (cons ?B (or battery-status "N/A"))
	  (cons ?b (or battery-status-symbol ""))
	  (cons ?p (or load-percentage "N/A"))
	  (cons ?s (or (and seconds (number-to-string seconds)) "N/A"))
	  (cons ?m (or (and minutes (number-to-string minutes)) "N/A"))
	  (cons ?h (or (and hours (number-to-string hours)) "N/A"))
	  (cons ?t (or remaining-time "N/A")))))


;;; `/proc/acpi/' interface for Linux.

(defun battery-linux-proc-acpi ()
  "Get ACPI status information from Linux kernel.
This function works only with the `/proc/acpi/' format introduced
in Linux version 2.4.20 and 2.6.0.

The following %-sequences are provided:
%c Current capacity (mAh)
%r Current rate
%B Battery status (verbose)
%b Battery status, empty means high, `-' means low,
   `!' means critical, and `+' means charging
%d Temperature (in degrees Celsius)
%L AC line status (verbose)
%p Battery load percentage
%m Remaining time (to charge or discharge) in minutes
%h Remaining time (to charge or discharge) in hours
%t Remaining time (to charge or discharge) in the form `h:min'"
  (let ((design-capacity 0)
	(last-full-capacity 0)
	full-capacity
	(warn 0)
	(low 0)
	capacity rate rate-type charging-state minutes hours)
    ;; ACPI provides information about each battery present in the system in
    ;; a separate subdirectory.  We are going to merge the available
    ;; information together since displaying for a variable amount of
    ;; batteries seems overkill for format-strings.
    (with-temp-buffer
      (dolist (dir (ignore-errors (directory-files "/proc/acpi/battery/"
						   t "\\`[^.]")))
	(erase-buffer)
	(ignore-errors (insert-file-contents (expand-file-name "state" dir)))
	(when (re-search-forward "present: +yes$" nil t)
	  (and (re-search-forward "charging state: +\\(.*\\)$" nil t)
	       (member charging-state '("unknown" "charged" nil))
	       ;; On most multi-battery systems, most of the time only one
	       ;; battery is "charging"/"discharging", the others are
	       ;; "unknown".
	       (setq charging-state (match-string 1)))
	  (when (re-search-forward "present rate: +\\([0-9]+\\) \\(m[AW]\\)$"
				   nil t)
	    (setq rate (+ (or rate 0) (string-to-number (match-string 1)))
		  rate-type (or (and rate-type
				     (if (string= rate-type (match-string 2))
					 rate-type
				       (error
					"Inconsistent rate types (%s vs. %s)"
					rate-type (match-string 2))))
				(match-string 2))))
	  (when (re-search-forward "remaining capacity: +\\([0-9]+\\) m[AW]h$"
				   nil t)
	    (setq capacity
		  (+ (or capacity 0) (string-to-number (match-string 1))))))
	(goto-char (point-max))
	(ignore-errors (insert-file-contents (expand-file-name "info" dir)))
	(when (re-search-forward "present: +yes$" nil t)
	  (when (re-search-forward "design capacity: +\\([0-9]+\\) m[AW]h$"
				   nil t)
	    (incf design-capacity (string-to-number (match-string 1))))
	  (when (re-search-forward "last full capacity: +\\([0-9]+\\) m[AW]h$"
				   nil t)
	    (incf last-full-capacity (string-to-number (match-string 1))))
	  (when (re-search-forward
		 "design capacity warning: +\\([0-9]+\\) m[AW]h$" nil t)
	    (incf warn (string-to-number (match-string 1))))
	  (when (re-search-forward "design capacity low: +\\([0-9]+\\) m[AW]h$"
				   nil t)
	    (incf low (string-to-number (match-string 1)))))))
    (setq full-capacity (if (> last-full-capacity 0)
			    last-full-capacity design-capacity))
    (and capacity rate
	 (setq minutes (if (zerop rate) 0
			 (floor (* (/ (float (if (string= charging-state
							  "charging")
						 (- full-capacity capacity)
					       capacity))
				      rate)
				   60)))
	       hours (/ minutes 60)))
    (list (cons ?c (or (and capacity (number-to-string capacity)) "N/A"))
	  (cons ?L (or (battery-search-for-one-match-in-files
			(mapcar (lambda (e) (concat e "/state"))
				(ignore-errors
				  (directory-files "/proc/acpi/ac_adapter/"
						   t "\\`[^.]")))
			"state: +\\(.*\\)$" 1)

		       "N/A"))
	  (cons ?d (or (battery-search-for-one-match-in-files
			(mapcar (lambda (e) (concat e "/temperature"))
				(ignore-errors
				  (directory-files "/proc/acpi/thermal_zone/"
						   t "\\`[^.]")))
			"temperature: +\\([0-9]+\\) C$" 1)

		       "N/A"))
	  (cons ?r (or (and rate (concat (number-to-string rate) " "
					 rate-type)) "N/A"))
	  (cons ?B (or charging-state "N/A"))
	  (cons ?b (or (and (string= charging-state "charging") "+")
		       (and capacity (< capacity low) "!")
		       (and capacity (< capacity warn) "-")
		       ""))
	  (cons ?h (or (and hours (number-to-string hours)) "N/A"))
	  (cons ?m (or (and minutes (number-to-string minutes)) "N/A"))
	  (cons ?t (or (and minutes
			    (format "%d:%02d" hours (- minutes (* 60 hours))))
		       "N/A"))
	  (cons ?p (or (and full-capacity capacity
			    (> full-capacity 0)
			    (number-to-string
			     (floor (/ capacity
				       (/ (float full-capacity) 100)))))
		       "N/A")))))


;;; `/sys/class/power_supply/BATN' interface for Linux.

(defun battery-linux-sysfs ()
  "Get ACPI status information from Linux kernel.
This function works only with the new `/sys/class/power_supply/'
format introduced in Linux version 2.4.25.

The following %-sequences are provided:
%c Current capacity (mAh or mWh)
%B Battery status (verbose)
%p Battery load percentage
%L AC line status (verbose)"
  (let (charging-state
	(charge-full 0.0)
	(charge-now 0.0)
	(energy-full 0.0)
	(energy-now 0.0))
    ;; SysFS provides information about each battery present in the
    ;; system in a separate subdirectory.  We are going to merge the
    ;; available information together.
    (with-temp-buffer
      (dolist (dir (ignore-errors
		    (directory-files
		     "/sys/class/power_supply/" t "BAT[0-9]$")))
	(erase-buffer)
	(ignore-errors (insert-file-contents
			(expand-file-name "uevent" dir)))
	(when (re-search-forward "POWER_SUPPLY_PRESENT=1$" nil t)
	  (goto-char (point-min))
	  (and (re-search-forward "POWER_SUPPLY_STATUS=\\(.*\\)$" nil t)
	       (member charging-state '("Unknown" "Full" nil))
	       (setq charging-state (match-string 1)))
	  (let (full-string now-string)
	    ;; Sysfs may list either charge (mAh) or energy (mWh).
	    ;; Keep track of both, and choose which to report later.
	    (cond ((and (re-search-forward
			 "POWER_SUPPLY_CHARGE_FULL=\\([0-9]*\\)$" nil t)
			(setq full-string (match-string 1))
			(re-search-forward
			 "POWER_SUPPLY_CHARGE_NOW=\\([0-9]*\\)$" nil t)
			(setq now-string (match-string 1)))
		   (setq charge-full (+ charge-full
					(string-to-number full-string))
			 charge-now  (+ charge-now
					(string-to-number now-string))))
		  ((and (re-search-forward
			 "POWER_SUPPLY_ENERGY_FULL=\\([0-9]*\\)$" nil t)
			(setq full-string (match-string 1))
			(re-search-forward
			 "POWER_SUPPLY_ENERGY_NOW=\\([0-9]*\\)$" nil t)
			(setq now-string (match-string 1)))
		   (setq energy-full (+ energy-full
					(string-to-number full-string))
			 energy-now  (+ energy-now
					(string-to-number now-string)))))))))
    (list (cons ?c (cond ((or (> charge-full 0) (> charge-now 0))
			  (number-to-string charge-now))
			 ((or (> energy-full 0) (> energy-now 0))
			  (number-to-string energy-now))
			 (t "N/A")))
	  (cons ?B (or charging-state "N/A"))
	  (cons ?p (cond ((> charge-full 0)
			  (format "%.1f"
				  (/ (* 100 charge-now) charge-full)))
			 ((> energy-full 0)
			  (format "%.1f"
				  (/ (* 100 energy-now) energy-full)))
			 (t "N/A")))
	  (cons ?L (if (file-readable-p "/sys/class/power_supply/AC/online")
		       (if (battery-search-for-one-match-in-files
			    (list "/sys/class/power_supply/AC/online"
				  "/sys/class/power_supply/ACAD/online")
			    "1" 0)
			   "AC"
			 "BAT")
		     "N/A")))))



;;; `pmset' interface for Darwin (OS X).

(defun battery-pmset ()
  "Get battery status information using `pmset'.

The following %-sequences are provided:
%L Power source (verbose)
%B Battery status (verbose)
%b Battery status, empty means high, `-' means low,
   `!' means critical, and `+' means charging
%p Battery load percentage
%h Remaining time in hours
%m Remaining time in minutes
%t Remaining time in the form `h:min'"
  (let (power-source load-percentage battery-status battery-status-symbol
	remaining-time hours minutes)
    (with-temp-buffer
      (ignore-errors (call-process "pmset" nil t nil "-g" "ps"))
      (goto-char (point-min))
      (when (re-search-forward "Currentl?y drawing from '\\(AC\\|Battery\\) Power'" nil t)
	(setq power-source (match-string 1))
	(when (re-search-forward "^ -InternalBattery-0[ \t]+" nil t)
	  (when (looking-at "\\([0-9]\\{1,3\\}\\)%")
	    (setq load-percentage (match-string 1))
	    (goto-char (match-end 0))
	    (cond ((looking-at "; charging")
		   (setq battery-status "charging"
			 battery-status-symbol "+"))
		  ((< (string-to-number load-percentage) battery-load-low)
		   (setq battery-status "low"
			 battery-status-symbol "-"))
		  ((< (string-to-number load-percentage) battery-load-critical)
		   (setq battery-status "critical"
			 battery-status-symbol "!"))
		  (t
		   (setq battery-status "high"
			 battery-status-symbol "")))
	    (when (re-search-forward "\\(\\([0-9]+\\):\\([0-9]+\\)\\) remaining"  nil t)
	      (setq remaining-time (match-string 1))
	      (let ((h (string-to-number (match-string 2)))
		    (m (string-to-number (match-string 3))))
		(setq hours (number-to-string (+ h (if (< m 30) 0 1)))
		      minutes (number-to-string (+ (* h 60) m)))))))))
    (list (cons ?L (or power-source "N/A"))
	  (cons ?p (or load-percentage "N/A"))
	  (cons ?B (or battery-status "N/A"))
	  (cons ?b (or battery-status-symbol ""))
	  (cons ?h (or hours "N/A"))
	  (cons ?m (or minutes "N/A"))
	  (cons ?t (or remaining-time "N/A")))))


;;; Private functions.

(defun battery-format (format alist)
  "Substitute %-sequences in FORMAT."
  (replace-regexp-in-string
   "%."
   (lambda (str)
     (let ((char (aref str 1)))
       (if (eq char ?%) "%"
	 (or (cdr (assoc char alist)) ""))))
   format t t))

(defun battery-search-for-one-match-in-files (files regexp match-num)
  "Search REGEXP in the content of the files listed in FILES.
If a match occurred, return the parenthesized expression numbered by
MATCH-NUM in the match.  Otherwise, return nil."
  (with-temp-buffer
    (catch 'found
      (dolist (file files)
	(and (ignore-errors (insert-file-contents file nil nil nil 'replace))
	     (re-search-forward regexp nil t)
	     (throw 'found (match-string match-num)))))))


(provide 'battery)

;; arch-tag: 65916f50-4754-4b6b-ac21-0b510f545a37
;;; battery.el ends here