Merge with mpm
authorBryan O'Sullivan <bos@serpentine.com>
Thu, 06 Aug 2009 18:48:00 -0700
changeset 9325 74e717a21779
parent 9315 fb66a7d3f28f (current diff)
parent 9248 ac02b43bc08a (diff)
child 9327 9a69ab6d7cf7
Merge with mpm
hgext/mq.py
hgext/notify.py
mercurial/help.py
mercurial/lsprof.py
tests/test-mq-qimport.out
--- a/Makefile	Wed Aug 05 17:19:37 2009 +0200
+++ b/Makefile	Thu Aug 06 18:48:00 2009 -0700
@@ -89,7 +89,7 @@
         # Extracting with an explicit encoding of ISO-8859-1 will make
         # xgettext "parse" and ignore them.
 	echo $^ | xargs \
-	  xgettext --package-name "Mercurial" \
+	  xgettext --width 82 --package-name "Mercurial" \
 	  --msgid-bugs-address "<mercurial-devel@selenic.com>" \
 	  --copyright-holder "Matt Mackall <mpm@selenic.com> and others" \
 	  --from-code ISO-8859-1 --join --sort-by-file \
--- a/contrib/hgdiff	Wed Aug 05 17:19:37 2009 +0200
+++ b/contrib/hgdiff	Thu Aug 06 18:48:00 2009 -0700
@@ -38,13 +38,13 @@
 
 def diff_files(file1, file2):
     if file1 is None:
-        b = file(file2).read().splitlines(1)
+        b = file(file2).read().splitlines(True)
         l1 = "--- %s\n" % (file2)
         l2 = "+++ %s\n" % (file2)
         l3 = "@@ -0,0 +1,%d @@\n" % len(b)
         l = [l1, l2, l3] + ["+" + e for e in b]
     elif file2 is None:
-        a = file(file1).read().splitlines(1)
+        a = file(file1).read().splitlines(True)
         l1 = "--- %s\n" % (file1)
         l2 = "+++ %s\n" % (file1)
         l3 = "@@ -1,%d +0,0 @@\n" % len(a)
@@ -52,8 +52,8 @@
     else:
         t1 = file(file1).read()
         t2 = file(file2).read()
-        l1 = t1.splitlines(1)
-        l2 = t2.splitlines(1)
+        l1 = t1.splitlines(True)
+        l2 = t2.splitlines(True)
         if options.difflib:
             l = difflib.unified_diff(l1, l2, file1, file2)
         else:
--- a/contrib/perf.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/contrib/perf.py	Thu Aug 06 18:48:00 2009 -0700
@@ -51,7 +51,7 @@
     def t():
         repo.changelog = mercurial.changelog.changelog(repo.sopener)
         repo.manifest = mercurial.manifest.manifest(repo.sopener)
-        repo.tagscache = None
+        repo._tags = None
         return len(repo.tags())
     timer(t)
 
--- a/contrib/win32/win32-build.txt	Wed Aug 05 17:19:37 2009 +0200
+++ b/contrib/win32/win32-build.txt	Thu Aug 06 18:48:00 2009 -0700
@@ -33,8 +33,8 @@
   add_path (you need only add_path.exe in the zip file)
       http://www.barisione.org/apps.html#add_path
 
-  Asciidoc - optional
-      http://www.methods.co.nz/asciidoc/
+  Docutils
+      http://docutils.sourceforge.net/
 
 And, of course, Mercurial itself.
 
@@ -79,11 +79,16 @@
     Microsoft.VC90.MFC.manifest)
 
 Before building the installer, you have to build Mercurial HTML documentation 
-(or fix mercurial.iss to not reference the doc directory). Assuming you have an
-"asciidoc.bat" batch file somewhere in your PATH:
+(or fix mercurial.iss to not reference the doc directory). Docutils does not
+come with a ready-made script for rst2html.py, so you will have to write your
+own and put it in %PATH% like:
+
+  @python c:\pythonXX\scripts\rst2html.py %*
+
+Then build the documentation with:
 
   cd doc
-  mingw32-make ASCIIDOC=asciidoc.bat html
+  mingw32-make RST2HTML=rst2html.bat html
   cd ..
 
 If you use ISTool, you open the C:\hg\hg-release\contrib\win32\mercurial.iss
@@ -102,7 +107,7 @@
   echo compiler=mingw32 >> setup.cfg
   python setup.py py2exe -b 1
   cd doc
-  mingw32-make ASCIIDOC=asciidoc.bat html
+  mingw32-make RST2HTML=rst2html.bat html
   cd ..
   iscc contrib\win32\mercurial.iss
 
--- a/doc/Makefile	Wed Aug 05 17:19:37 2009 +0200
+++ b/doc/Makefile	Thu Aug 06 18:48:00 2009 -0700
@@ -5,7 +5,8 @@
 MANDIR=$(PREFIX)/share/man
 INSTALL=install -c -m 644
 PYTHON=python
-ASCIIDOC=asciidoc
+RST2HTML=rst2html
+RST2MAN=rst2man
 
 all: man html
 
@@ -16,19 +17,18 @@
 hg.1.txt: hg.1.gendoc.txt
 	touch hg.1.txt
 
-hg.1.gendoc.txt: ../mercurial/commands.py ../mercurial/help.py
+hg.1.gendoc.txt: gendoc.py ../mercurial/commands.py ../mercurial/help.py
 	${PYTHON} gendoc.py > $@
 
-%: %.xml
-	xmlto man $*.xml && \
-	sed -e 's/^\.hg/\\\&.hg/' $* > $*~ && \
-	mv $*~ $*
+%: %.txt common.txt
+	# add newline after all literal blocks and fix backslash escape
+	$(RST2MAN) $*.txt \
+	  | sed -e 's/^\.fi$$/.fi\n/' \
+	  | sed -e 's/\\fB\\\\fP/\\fB\\e\\fP/' \
+	  > $*
 
-%.xml: %.txt
-	$(ASCIIDOC) -d manpage -b docbook $*.txt
-
-%.html: %.txt
-	$(ASCIIDOC) -b html4 $*.txt || $(ASCIIDOC) -b html $*.txt
+%.html: %.txt common.txt
+	$(RST2HTML) $*.txt > $*.html
 
 MANIFEST: man html
 	# tracked files are already in the main MANIFEST
@@ -45,4 +45,4 @@
 	done
 
 clean:
-	$(RM) $(MAN) $(MAN:%=%.xml) $(MAN:%=%.html) *.[0-9].gendoc.txt MANIFEST
+	$(RM) $(MAN) $(MAN:%=%.html) *.[0-9].gendoc.txt MANIFEST
--- a/doc/README	Wed Aug 05 17:19:37 2009 +0200
+++ b/doc/README	Thu Aug 06 18:48:00 2009 -0700
@@ -1,23 +1,17 @@
-Mercurial's documentation is currently kept in ASCIIDOC format, which
-is a simple plain text format that's easy to read and edit. It's also
-convertible to a variety of other formats including standard UNIX man
-page format and HTML.
+Mercurial's documentation is kept in reStructuredText format, which is
+a simple plain text format that's easy to read and edit:
 
-To do this, you'll need to install ASCIIDOC:
+  http://docutils.sourceforge.net/rst.html
 
- http://www.methods.co.nz/asciidoc/
-
-To generate the man page:
+It's also convertible to a variety of other formats including standard
+UNIX man page format and HTML.
 
- asciidoc -d manpage -b docbook hg.1.txt
- xmlto man hg.1.xml
+To do this, you'll need to install the rst2html and rst2man tools,
+which are part of Docutils:
 
-To display:
+  http://docutils.sourceforge.net/
 
- groff -mandoc -Tascii hg.1 | more
-
-To create the html page (without stylesheets):
+The rst2man tool is still in their so-called "sandbox". The above page
+has links to tarballs of both Docutils and their sandbox.
 
- asciidoc -b html4 hg.1.txt
-
-(older asciidoc may want html instead of html4 above)
+Use the Makefile in this directory to generate the man and HTML pages.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/doc/common.txt	Thu Aug 06 18:48:00 2009 -0700
@@ -0,0 +1,8 @@
+.. Common link and substitution definitions.
+
+.. |hg(1)| replace:: **hg**\ (1)
+.. _hg(1): hg.1.html
+.. |hgrc(5)| replace:: **hgrc**\ (5)
+.. _hgrc(5): hgrc.5.html
+.. |hgignore(5)| replace:: **hgignore**\ (5)
+.. _hgignore(5): hgignore.5.html
--- a/doc/gendoc.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/doc/gendoc.py	Thu Aug 06 18:48:00 2009 -0700
@@ -62,7 +62,7 @@
     # print options
     underlined(_("OPTIONS"))
     for optstr, desc in get_opts(globalopts):
-        ui.write("%s::\n    %s\n\n" % (optstr, desc))
+        ui.write("%s\n    %s\n\n" % (optstr, desc))
 
     # print cmds
     underlined(_("COMMANDS"))
@@ -78,15 +78,15 @@
         if f.startswith("debug"): continue
         d = get_cmd(h[f])
         # synopsis
-        ui.write("[[%s]]\n" % d['cmd'])
-        ui.write("%s::\n" % d['synopsis'].replace("hg ","", 1))
+        ui.write(".. _%s:\n\n" % d['cmd'])
+        ui.write("``%s``\n" % d['synopsis'].replace("hg ","", 1))
         # description
         ui.write("%s\n\n" % d['desc'][1])
         # options
         opt_output = list(d['opts'])
         if opt_output:
             opts_len = max([len(line[0]) for line in opt_output])
-            ui.write(_("    options:\n"))
+            ui.write(_("    options:\n\n"))
             for optstr, desc in opt_output:
                 if desc:
                     s = "%-*s  %s" % (opts_len, optstr, desc)
--- a/doc/hg.1.txt	Wed Aug 05 17:19:37 2009 +0200
+++ b/doc/hg.1.txt	Thu Aug 06 18:48:00 2009 -0700
@@ -1,64 +1,70 @@
-HG(1)
-=====
-Matt Mackall <mpm@selenic.com>
-:man source: Mercurial
-:man manual: Mercurial Manual
+====
+ hg
+====
 
-NAME
-----
-hg - Mercurial source code management system
+---------------------------------------
+Mercurial source code management system
+---------------------------------------
+
+:Author:         Matt Mackall <mpm@selenic.com>
+:Organization:   Mercurial
+:Manual section: 1
+:Manual group:   Mercurial Manual
+
 
 SYNOPSIS
 --------
-*hg* 'command' ['option']... ['argument']...
+**hg** *command* [*option*]... [*argument*]...
 
 DESCRIPTION
 -----------
-The *hg* command provides a command line interface to the Mercurial
+The **hg** command provides a command line interface to the Mercurial
 system.
 
 COMMAND ELEMENTS
 ----------------
 
-files ...::
+files...
     indicates one or more filename or relative path filenames; see
     "FILE NAME PATTERNS" for information on pattern matching
 
-path::
+path
     indicates a path on the local machine
 
-revision::
+revision
     indicates a changeset which can be specified as a changeset
     revision number, a tag, or a unique substring of the changeset
     hash value
 
-repository path::
+repository path
     either the pathname of a local repository or the URI of a remote
     repository.
 
-include::hg.1.gendoc.txt[]
+.. include:: hg.1.gendoc.txt
 
 FILES
 -----
- `.hgignore`::
+
+``.hgignore``
     This file contains regular expressions (one per line) that
-    describe file names that should be ignored by *hg*. For details,
-    see *hgignore(5)*.
+    describe file names that should be ignored by **hg**. For details,
+    see |hgignore(5)|_.
 
- `.hgtags`::
+``.hgtags``
     This file contains changeset hash values and text tag names (one
     of each separated by spaces) that correspond to tagged versions of
     the repository contents.
 
- `/etc/mercurial/hgrc`, `$HOME/.hgrc`, `.hg/hgrc`::
-    This file contains defaults and configuration. Values in `.hg/hgrc`
-    override those in `$HOME/.hgrc`, and these override settings made in
-    the global `/etc/mercurial/hgrc` configuration. See *hgrc(5)* for
-    details of the contents and format of these files.
+``/etc/mercurial/hgrc``, ``$HOME/.hgrc``, ``.hg/hgrc``
+    This file contains defaults and configuration. Values in
+    ``.hg/hgrc`` override those in ``$HOME/.hgrc``, and these override
+    settings made in the global ``/etc/mercurial/hgrc`` configuration.
+    See |hgrc(5)|_ for details of the contents and format of these
+    files.
 
-Some commands (e.g. revert) produce backup files ending in `.orig`, if
-the `.orig` file already exists and is not tracked by Mercurial, it will
-be overwritten.
+Some commands (e.g. revert) produce backup files ending in ``.orig``,
+if the ``.orig`` file already exists and is not tracked by Mercurial,
+it will be overwritten.
 
 BUGS
 ----
@@ -67,7 +73,7 @@
 
 SEE ALSO
 --------
-*hgignore(5)*, *hgrc(5)*
+|hgignore(5)|_, |hgrc(5)|_
 
 AUTHOR
 ------
@@ -75,14 +81,16 @@
 
 RESOURCES
 ---------
-http://mercurial.selenic.com/[Main Web Site]
+Main Web Site: http://mercurial.selenic.com/
 
-http://selenic.com/hg[Source code repository]
+Source code repository: http://selenic.com/hg
 
-http://selenic.com/mailman/listinfo/mercurial[Mailing list]
+Mailing list: http://selenic.com/mailman/listinfo/mercurial
 
 COPYING
 -------
 Copyright \(C) 2005-2009 Matt Mackall.
 Free use of this software is granted under the terms of the GNU General
 Public License (GPL).
+
+.. include:: common.txt
--- a/doc/hgignore.5.txt	Wed Aug 05 17:19:37 2009 +0200
+++ b/doc/hgignore.5.txt	Thu Aug 06 18:48:00 2009 -0700
@@ -1,17 +1,20 @@
-HGIGNORE(5)
-===========
-Vadim Gelfer <vadim.gelfer@gmail.com>
-:man source: Mercurial
-:man manual: Mercurial Manual
+==========
+ hgignore
+==========
 
-NAME
-----
-hgignore - syntax for Mercurial ignore files
+---------------------------------
+syntax for Mercurial ignore files
+---------------------------------
+
+:Author:         Vadim Gelfer <vadim.gelfer@gmail.com>
+:Organization:   Mercurial
+:Manual section: 5
+:Manual group:   Mercurial Manual
 
 SYNOPSIS
 --------
 
-The Mercurial system uses a file called `.hgignore` in the root
+The Mercurial system uses a file called ``.hgignore`` in the root
 directory of a repository to control its behavior when it searches
 for files that it is not currently tracking.
 
@@ -21,61 +24,61 @@
 The working directory of a Mercurial repository will often contain
 files that should not be tracked by Mercurial. These include backup
 files created by editors and build products created by compilers.
-These files can be ignored by listing them in a `.hgignore` file in
-the root of the working directory. The `.hgignore` file must be
+These files can be ignored by listing them in a ``.hgignore`` file in
+the root of the working directory. The ``.hgignore`` file must be
 created manually. It is typically put under version control, so that
 the settings will propagate to other repositories with push and pull.
 
 An untracked file is ignored if its path relative to the repository
 root directory, or any prefix path of that path, is matched against
-any pattern in `.hgignore`.
+any pattern in ``.hgignore``.
 
-For example, say we have an an untracked file, `file.c`, at 
-`a/b/file.c` inside our repository. Mercurial will ignore `file.c` if
-any pattern in `.hgignore` matches `a/b/file.c`, `a/b` or `a`.
+For example, say we have an an untracked file, ``file.c``, at
+``a/b/file.c`` inside our repository. Mercurial will ignore ``file.c``
+if any pattern in ``.hgignore`` matches ``a/b/file.c``, ``a/b`` or ``a``.
 
 In addition, a Mercurial configuration file can reference a set of
-per-user or global ignore files. See the hgrc(5) man page for details
+per-user or global ignore files. See the |hgrc(5)|_ man page for details
 of how to configure these files. Look for the "ignore" entry in the
 "ui" section.
 
 To control Mercurial's handling of files that it manages, see the
-hg(1) man page. Look for the "-I" and "-X" options.
+|hg(1)|_ man page. Look for the "``-I``" and "``-X``" options.
 
 SYNTAX
 ------
 
 An ignore file is a plain text file consisting of a list of patterns,
-with one pattern per line. Empty lines are skipped. The "`#`"
-character is treated as a comment character, and the "`\`" character
+with one pattern per line. Empty lines are skipped. The "``#``"
+character is treated as a comment character, and the "``\``" character
 is treated as an escape character.
 
 Mercurial supports several pattern syntaxes. The default syntax used
 is Python/Perl-style regular expressions.
 
-To change the syntax used, use a line of the following form:
+To change the syntax used, use a line of the following form::
 
-syntax: NAME
+  syntax: NAME
 
-where NAME is one of the following:
+where ``NAME`` is one of the following:
 
-regexp::
+``regexp``
   Regular expression, Python/Perl syntax.
-glob::
+``glob``
   Shell-style glob.
 
 The chosen syntax stays in effect when parsing all patterns that
 follow, until another syntax is selected.
 
 Neither glob nor regexp patterns are rooted. A glob-syntax pattern of
-the form "`*.c`" will match a file ending in "`.c`" in any directory,
-and a regexp pattern of the form "`\.c$`" will do the same. To root a
-regexp pattern, start it with "`^`".
+the form "``*.c``" will match a file ending in "``.c``" in any directory,
+and a regexp pattern of the form "``\.c$``" will do the same. To root a
+regexp pattern, start it with "``^``".
 
 EXAMPLE
 -------
 
-Here is an example ignore file.
+Here is an example ignore file. ::
 
   # use glob syntax.
   syntax: glob
@@ -96,7 +99,7 @@
 
 SEE ALSO
 --------
-hg(1), hgrc(5)
+|hg(1)|_, |hgrc(5)|_
 
 COPYING
 -------
@@ -104,3 +107,5 @@
 Mercurial is copyright 2005-2009 Matt Mackall.
 Free use of this software is granted under the terms of the GNU General
 Public License (GPL).
+
+.. include:: common.txt
--- a/doc/hgrc.5.txt	Wed Aug 05 17:19:37 2009 +0200
+++ b/doc/hgrc.5.txt	Thu Aug 06 18:48:00 2009 -0700
@@ -1,12 +1,16 @@
-HGRC(5)
-=======
-Bryan O'Sullivan <bos@serpentine.com>
-:man source: Mercurial
-:man manual: Mercurial Manual
+======
+ hgrc
+======
 
-NAME
-----
-hgrc - configuration files for Mercurial
+---------------------------------
+configuration files for Mercurial
+---------------------------------
+
+:Author:         Bryan O'Sullivan <bos@serpentine.com>
+:Organization:   Mercurial
+:Manual section: 5
+:Manual group:   Mercurial Manual
+
 
 SYNOPSIS
 --------
@@ -19,51 +23,54 @@
 
 Mercurial reads configuration data from several files, if they exist.
 The names of these files depend on the system on which Mercurial is
-installed. `*.rc` files from a single directory are read in
+installed. ``*.rc`` files from a single directory are read in
 alphabetical order, later ones overriding earlier ones. Where multiple
 paths are given below, settings from later paths override earlier
 ones.
 
-(Unix) `<install-root>/etc/mercurial/hgrc.d/*.rc`::
-(Unix) `<install-root>/etc/mercurial/hgrc`::
+| (Unix) ``<install-root>/etc/mercurial/hgrc.d/*.rc``
+| (Unix) ``<install-root>/etc/mercurial/hgrc``
+
     Per-installation configuration files, searched for in the
-    directory where Mercurial is installed. `<install-root>` is the
-    parent directory of the hg executable (or symlink) being run. For
-    example, if installed in `/shared/tools/bin/hg`, Mercurial will look
-    in `/shared/tools/etc/mercurial/hgrc`. Options in these files apply
+    directory where Mercurial is installed. ``<install-root>`` is the
+    parent directory of the **hg** executable (or symlink) being run. For
+    example, if installed in ``/shared/tools/bin/hg``, Mercurial will look
+    in ``/shared/tools/etc/mercurial/hgrc``. Options in these files apply
     to all Mercurial commands executed by any user in any directory.
 
-(Unix) `/etc/mercurial/hgrc.d/*.rc`::
-(Unix) `/etc/mercurial/hgrc`::
+| (Unix) ``/etc/mercurial/hgrc.d/*.rc``
+| (Unix) ``/etc/mercurial/hgrc``
+
     Per-system configuration files, for the system on which Mercurial
     is running. Options in these files apply to all Mercurial commands
     executed by any user in any directory. Options in these files
     override per-installation options.
 
-(Windows) `<install-dir>\Mercurial.ini`::
-  or else::
-(Windows) `HKEY_LOCAL_MACHINE\SOFTWARE\Mercurial`::
-  or else::
-(Windows) `C:\Mercurial\Mercurial.ini`::
+| (Windows) ``<install-dir>\Mercurial.ini`` or else
+| (Windows) ``HKEY_LOCAL_MACHINE\SOFTWARE\Mercurial`` or else
+| (Windows) ``C:\Mercurial\Mercurial.ini``
+
     Per-installation/system configuration files, for the system on
     which Mercurial is running. Options in these files apply to all
     Mercurial commands executed by any user in any directory. Registry
     keys contain PATH-like strings, every part of which must reference
-    a `Mercurial.ini` file or be a directory where `*.rc` files will
+    a ``Mercurial.ini`` file or be a directory where ``*.rc`` files will
     be read.
 
-(Unix) `$HOME/.hgrc`::
-(Windows) `%HOME%\Mercurial.ini`::
-(Windows) `%HOME%\.hgrc`::
-(Windows) `%USERPROFILE%\Mercurial.ini`::
-(Windows) `%USERPROFILE%\.hgrc`::
+| (Unix) ``$HOME/.hgrc``
+| (Windows) ``%HOME%\Mercurial.ini``
+| (Windows) ``%HOME%\.hgrc``
+| (Windows) ``%USERPROFILE%\Mercurial.ini``
+| (Windows) ``%USERPROFILE%\.hgrc``
+
     Per-user configuration file(s), for the user running Mercurial. On
-    Windows 9x, `%HOME%` is replaced by `%APPDATA%`. Options in these
+    Windows 9x, ``%HOME%`` is replaced by ``%APPDATA%``. Options in these
     files apply to all Mercurial commands executed by this user in any
     directory. Options in these files override per-installation and
     per-system options.
 
-(Unix, Windows) `<repo>/.hg/hgrc`::
+| (Unix, Windows) ``<repo>/.hg/hgrc``
+
     Per-repository configuration options that only apply in a
     particular repository. This file is not version-controlled, and
     will not get transferred during a "clone" operation. Options in
@@ -75,8 +82,10 @@
 SYNTAX
 ------
 
-A configuration file consists of sections, led by a "`[section]`" header
-and followed by "`name: value`" entries; "`name=value`" is also accepted.
+A configuration file consists of sections, led by a "``[section]``" header
+and followed by "``name: value``" entries; "``name=value``" is also accepted.
+
+::
 
     [spam]
     eggs=ham
@@ -88,7 +97,7 @@
 
 Leading whitespace is removed from values. Empty lines are skipped.
 
-Lines beginning with "`#`" or "`;`" are ignored and may be used to provide
+Lines beginning with "``#``" or "``;``" are ignored and may be used to provide
 comments.
 
 SECTIONS
@@ -98,41 +107,39 @@
 Mercurial "hgrc" file, the purpose of each section, its possible keys,
 and their possible values.
 
-[[alias]]
-alias::
- Defines command aliases.
-  Aliases allow you to define your own commands in terms of other
-  commands (or aliases), optionally including arguments.
-+
---
-Alias definitions consist of lines of the form:
+``alias``
+"""""""""
+Defines command aliases.
+Aliases allow you to define your own commands in terms of other
+commands (or aliases), optionally including arguments.
+
+Alias definitions consist of lines of the form::
 
     <alias> = <command> [<argument]...
 
-For example, this definition:
+For example, this definition::
 
     latest = log --limit 5
 
-creates a new command `latest` that shows only the five most recent
-changesets. You can define subsequent aliases using earlier ones:
+creates a new command ``latest`` that shows only the five most recent
+changesets. You can define subsequent aliases using earlier ones::
 
     stable5 = latest -b stable
 
 NOTE: It is possible to create aliases with the same names as existing
 commands, which will then override the original definitions. This is
 almost always a bad idea!
---
+
 
-[[auth]]
-auth::
+``auth``
+""""""""
 Authentication credentials for HTTP authentication. Each line has
-the following format:
+the following format::
 
     <name>.<argument> = <value>
-+
---
+
 where <name> is used to group arguments into authentication entries.
-Example:
+Example::
 
     foo.prefix = hg.intevation.org/mercurial
     foo.username = foo
@@ -146,26 +153,26 @@
 
 Supported arguments:
 
-  prefix;;
-    Either "\*" or a URI prefix with or without the scheme part.
+``prefix``
+    Either "``*``" or a URI prefix with or without the scheme part.
     The authentication entry with the longest matching prefix is used
-    (where "*" matches everything and counts as a match of length
+    (where "``*``" matches everything and counts as a match of length
     1). If the prefix doesn't include a scheme, the match is performed
     against the URI with its scheme stripped as well, and the schemes
     argument, q.v., is then subsequently consulted.
-  username;;
+``username``
     Optional. Username to authenticate with. If not given, and the
     remote site requires basic or digest authentication, the user
     will be prompted for it.
-  password;;
+``password``
     Optional. Password to authenticate with. If not given, and the
     remote site requires basic or digest authentication, the user
     will be prompted for it.
-  key;;
+``key``
     Optional. PEM encoded client certificate key file.
-  cert;;
+``cert``
     Optional. PEM encoded client certificate chain file.
-  schemes;;
+``schemes``
     Optional. Space separated list of URI schemes to use this
     authentication entry with. Only used if the prefix doesn't include
     a scheme. Supported schemes are http and https. They will match
@@ -174,20 +181,19 @@
 
 If no suitable authentication entry is found, the user is prompted
 for credentials as usual if required by the remote.
---
+
 
-[[decode]]
-decode/encode::
-  Filters for transforming files on checkout/checkin. This would
-  typically be used for newline processing or other
-  localization/canonicalization of files.
-+
---
+``decode/encode``
+"""""""""""""""""
+Filters for transforming files on checkout/checkin. This would
+typically be used for newline processing or other
+localization/canonicalization of files.
+
 Filters consist of a filter pattern followed by a filter command.
 Filter patterns are globs by default, rooted at the repository root.
-For example, to match any file ending in "`.txt`" in the root
-directory only, use the pattern "\*.txt". To match any file ending
-in "`.c`" anywhere in the repository, use the pattern "**`.c`".
+For example, to match any file ending in "``.txt``" in the root
+directory only, use the pattern "``*.txt``". To match any file ending
+in "``.c``" anywhere in the repository, use the pattern "``**.c``".
 
 The filter command can start with a specifier, either "pipe:" or
 "tempfile:". If no specifier is given, "pipe:" is used by default.
@@ -195,7 +201,7 @@
 A "pipe:" command must accept data on stdin and return the transformed
 data on stdout.
 
-Pipe example:
+Pipe example::
 
   [encode]
   # uncompress gzip files on checkin to improve delta compression
@@ -218,7 +224,7 @@
 effects and may corrupt the contents of your files.
 
 The most common usage is for LF <-> CRLF translation on Windows. For
-this, use the "smart" converters which check for binary files:
+this, use the "smart" converters which check for binary files::
 
   [extensions]
   hgext.win32text =
@@ -227,7 +233,7 @@
   [decode]
   ** = cleverdecode:
 
-or if you only want to translate certain files:
+or if you only want to translate certain files::
 
   [extensions]
   hgext.win32text =
@@ -235,16 +241,16 @@
   **.txt = dumbencode:
   [decode]
   **.txt = dumbdecode:
---
+
+
+``defaults``
+""""""""""""
 
-[[defaults]]
-defaults::
-  Use the [defaults] section to define command defaults, i.e. the
-  default options/arguments to pass to the specified commands.
-+
---
+Use the [defaults] section to define command defaults, i.e. the
+default options/arguments to pass to the specified commands.
+
 The following example makes 'hg log' run in verbose mode, and 'hg
-status' show only the modified files, by default.
+status' show only the modified files, by default::
 
   [defaults]
   log = -v
@@ -253,57 +259,59 @@
 The actual commands, instead of their aliases, must be used when
 defining command defaults. The command defaults will also be applied
 to the aliases of the commands defined.
---
+
+
+``diff``
+""""""""
 
-[[diff]]
-diff::
-  Settings used when displaying diffs. They are all Boolean and
-  defaults to False.
-  git;;
+Settings used when displaying diffs. They are all Boolean and
+defaults to False.
+
+``git``
     Use git extended diff format.
-  nodates;;
+``nodates``
     Don't include dates in diff headers.
-  showfunc;;
+``showfunc``
     Show which function each change is in.
-  ignorews;;
+``ignorews``
     Ignore white space when comparing lines.
-  ignorewsamount;;
+``ignorewsamount``
     Ignore changes in the amount of white space.
-  ignoreblanklines;;
+``ignoreblanklines``
     Ignore changes whose lines are all blank.
 
-[[email]]
-email::
-  Settings for extensions that send email messages.
-  from;;
+``email``
+"""""""""
+Settings for extensions that send email messages.
+
+``from``
     Optional. Email address to use in "From" header and SMTP envelope
     of outgoing messages.
-  to;;
+``to``
     Optional. Comma-separated list of recipients' email addresses.
-  cc;;
+``cc``
     Optional. Comma-separated list of carbon copy recipients'
     email addresses.
-  bcc;;
+``bcc``
     Optional. Comma-separated list of blind carbon copy recipients'
     email addresses. Cannot be set interactively.
-  method;;
+``method``
     Optional. Method to use to send email messages. If value is "smtp"
     (default), use SMTP (see section "[smtp]" for configuration).
     Otherwise, use as name of program to run that acts like sendmail
     (takes "-f" option for sender, list of recipients on command line,
     message on stdin). Normally, setting this to "sendmail" or
     "/usr/sbin/sendmail" is enough to use sendmail to send messages.
-  charsets;;
+``charsets``
     Optional. Comma-separated list of character sets considered
     convenient for recipients. Addresses, headers, and parts not
     containing patches of outgoing messages will be encoded in the
     first character set to which conversion from local encoding
-    (`$HGENCODING`, `ui.fallbackencoding`) succeeds. If correct
+    (``$HGENCODING``, ``ui.fallbackencoding``) succeeds. If correct
     conversion fails, the text in question is sent as is. Defaults to
     empty (explicit) list.
-+
---
-Order of outgoing email character sets:
+
+Order of outgoing email character sets::
 
   us-ascii             always first, regardless of settings
   email.charsets       in order given by user
@@ -311,7 +319,7 @@
   $HGENCODING          if not in email.charsets
   utf-8                always last, regardless of settings
 
-Email example:
+Email example::
 
   [email]
   from = Joseph User <joe.user@example.com>
@@ -319,40 +327,40 @@
   # charsets for western Europeans
   # us-ascii, utf-8 omitted, as they are tried first and last
   charsets = iso-8859-1, iso-8859-15, windows-1252
---
+
+
+``extensions``
+""""""""""""""
 
-[[extensions]]
-extensions::
-  Mercurial has an extension mechanism for adding new features. To
-  enable an extension, create an entry for it in this section.
-+
---
+Mercurial has an extension mechanism for adding new features. To
+enable an extension, create an entry for it in this section.
+
 If you know that the extension is already in Python's search path,
-you can give the name of the module, followed by "`=`", with nothing
-after the "`=`".
+you can give the name of the module, followed by "``=``", with nothing
+after the "``=``".
 
-Otherwise, give a name that you choose, followed by "`=`", followed by
-the path to the "`.py`" file (including the file name extension) that
+Otherwise, give a name that you choose, followed by "``=``", followed by
+the path to the "``.py``" file (including the file name extension) that
 defines the extension.
 
 To explicitly disable an extension that is enabled in an hgrc of
-broader scope, prepend its path with "`!`", as in
-"`hgext.foo = !/ext/path`" or "`hgext.foo = !`"  when path is not
+broader scope, prepend its path with "``!``", as in
+"``hgext.foo = !/ext/path``" or "``hgext.foo = !``"  when path is not
 supplied.
 
-Example for `~/.hgrc`:
+Example for ``~/.hgrc``::
 
   [extensions]
   # (the mq extension will get loaded from Mercurial's path)
   hgext.mq =
   # (this extension will get loaded from the file specified)
   myfeature = ~/.hgext/myfeature.py
---
+
 
-[[format]]
-format::
+``format``
+""""""""""
 
-  usestore;;
+``usestore``
     Enable or disable the "store" repository format which improves
     compatibility with systems that fold case or otherwise mangle
     filenames. Enabled by default. Disabling this option will allow
@@ -360,7 +368,7 @@
     compatibility and ensures that the on-disk format of newly created
     repositories will be compatible with Mercurial before version 0.9.4.
 
-  usefncache;;
+``usefncache``
     Enable or disable the "fncache" repository format which enhances
     the "store" repository format (which has to be enabled to use
     fncache) to allow longer filenames and avoids using Windows
@@ -368,26 +376,27 @@
     option ensures that the on-disk format of newly created
     repositories will be compatible with Mercurial before version 1.1.
 
-[[merge-patterns]]
-merge-patterns::
-  This section specifies merge tools to associate with particular file
-  patterns. Tools matched here will take precedence over the default
-  merge tool. Patterns are globs by default, rooted at the repository
-  root.
-+
-Example:
-+
+``merge-patterns``
+""""""""""""""""""
+
+This section specifies merge tools to associate with particular file
+patterns. Tools matched here will take precedence over the default
+merge tool. Patterns are globs by default, rooted at the repository
+root.
+
+Example::
+
   [merge-patterns]
   **.c = kdiff3
   **.jpg = myimgmerge
 
-[[merge-tools]]
-merge-tools::
-  This section configures external merge tools to use for file-level
-  merges.
-+
---
-Example `~/.hgrc`:
+``merge-tools``
+"""""""""""""""
+
+This section configures external merge tools to use for file-level
+merges.
+
+Example ``~/.hgrc``::
 
   [merge-tools]
   # Override stock tool location
@@ -404,64 +413,63 @@
 
 Supported arguments:
 
-priority;;
+``priority``
   The priority in which to evaluate this tool.
   Default: 0.
-executable;;
+``executable``
   Either just the name of the executable or its pathname.
   Default: the tool name.
-args;;
+``args``
   The arguments to pass to the tool executable. You can refer to the
   files being merged as well as the output file through these
-  variables: `$base`, `$local`, `$other`, `$output`.
-  Default: `$local $base $other`
-premerge;;
+  variables: ``$base``, ``$local``, ``$other``, ``$output``.
+  Default: ``$local $base $other``
+``premerge``
   Attempt to run internal non-interactive 3-way merge tool before
   launching external tool.
   Default: True
-binary;;
+``binary``
   This tool can merge binary files. Defaults to False, unless tool
   was selected by file pattern match.
-symlink;;
+``symlink``
   This tool can merge symlinks. Defaults to False, even if tool was
   selected by file pattern match.
-checkconflicts;;
+``checkconflicts``
   Check whether there are conflicts even though the tool reported
   success.
   Default: False
-checkchanged;;
+``checkchanged``
   Check whether outputs were written even though the tool reported
   success.
   Default: False
-fixeol;;
+``fixeol``
   Attempt to fix up EOL changes caused by the merge tool.
   Default: False
-gui;;
+``gui``
   This tool requires a graphical interface to run. Default: False
-regkey;;
+``regkey``
   Windows registry key which describes install location of this
   tool. Mercurial will search for this key first under
-  `HKEY_CURRENT_USER` and then under `HKEY_LOCAL_MACHINE`.
+  ``HKEY_CURRENT_USER`` and then under ``HKEY_LOCAL_MACHINE``.
   Default: None
-regname;;
+``regname``
   Name of value to read from specified registry key. Defaults to the
   unnamed (default) value.
-regappend;;
+``regappend``
   String to append to the value read from the registry, typically
   the executable name of the tool.
   Default: None
---
+
 
-[[hooks]]
-hooks::
-  Commands or Python functions that get automatically executed by
-  various actions such as starting or finishing a commit. Multiple
-  hooks can be run for the same action by appending a suffix to the
-  action. Overriding a site-wide hook can be done by changing its
-  value or setting it to an empty string.
-+
---
-Example `.hg/hgrc`:
+``hooks``
+"""""""""
+Commands or Python functions that get automatically executed by
+various actions such as starting or finishing a commit. Multiple
+hooks can be run for the same action by appending a suffix to the
+action. Overriding a site-wide hook can be done by changing its
+value or setting it to an empty string.
+
+Example ``.hg/hgrc``::
 
   [hooks]
   # do not use the site-wide hook
@@ -473,84 +481,84 @@
 additional information. For each hook below, the environment
 variables it is passed are listed with names of the form "$HG_foo".
 
-changegroup;;
+``changegroup``
   Run after a changegroup has been added via push, pull or unbundle.
-  ID of the first new changeset is in `$HG_NODE`. URL from which
-  changes came is in `$HG_URL`.
-commit;;
+  ID of the first new changeset is in ``$HG_NODE``. URL from which
+  changes came is in ``$HG_URL``.
+``commit``
   Run after a changeset has been created in the local repository. ID
-  of the newly created changeset is in `$HG_NODE`. Parent changeset
-  IDs are in `$HG_PARENT1` and `$HG_PARENT2`.
-incoming;;
+  of the newly created changeset is in ``$HG_NODE``. Parent changeset
+  IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
+``incoming``
   Run after a changeset has been pulled, pushed, or unbundled into
   the local repository. The ID of the newly arrived changeset is in
-  `$HG_NODE`. URL that was source of changes came is in `$HG_URL`.
-outgoing;;
+  ``$HG_NODE``. URL that was source of changes came is in ``$HG_URL``.
+``outgoing``
   Run after sending changes from local repository to another. ID of
-  first changeset sent is in `$HG_NODE`. Source of operation is in
-  `$HG_SOURCE`; see "preoutgoing" hook for description.
-post-<command>;;
+  first changeset sent is in ``$HG_NODE``. Source of operation is in
+  ``$HG_SOURCE``; see "preoutgoing" hook for description.
+``post-<command>``
   Run after successful invocations of the associated command. The
-  contents of the command line are passed as `$HG_ARGS` and the result
-  code in `$HG_RESULT`. Hook failure is ignored.
-pre-<command>;;
+  contents of the command line are passed as ``$HG_ARGS`` and the result
+  code in ``$HG_RESULT``. Hook failure is ignored.
+``pre-<command>``
   Run before executing the associated command. The contents of the
-  command line are passed as `$HG_ARGS`. If the hook returns failure,
+  command line are passed as ``$HG_ARGS``. If the hook returns failure,
   the command doesn't execute and Mercurial returns the failure
   code.
-prechangegroup;;
+``prechangegroup``
   Run before a changegroup is added via push, pull or unbundle. Exit
   status 0 allows the changegroup to proceed. Non-zero status will
   cause the push, pull or unbundle to fail. URL from which changes
-  will come is in `$HG_URL`.
-precommit;;
+  will come is in ``$HG_URL``.
+``precommit``
   Run before starting a local commit. Exit status 0 allows the
   commit to proceed. Non-zero status will cause the commit to fail.
-  Parent changeset IDs are in `$HG_PARENT1` and `$HG_PARENT2`.
-preoutgoing;;
+  Parent changeset IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
+``preoutgoing``
   Run before collecting changes to send from the local repository to
   another. Non-zero status will cause failure. This lets you prevent
   pull over HTTP or SSH. Also prevents against local pull, push
   (outbound) or bundle commands, but not effective, since you can
   just copy files instead then. Source of operation is in
-  `$HG_SOURCE`. If "serve", operation is happening on behalf of remote
+  ``$HG_SOURCE``. If "serve", operation is happening on behalf of remote
   SSH or HTTP repository. If "push", "pull" or "bundle", operation
   is happening on behalf of repository on same system.
-pretag;;
+``pretag``
   Run before creating a tag. Exit status 0 allows the tag to be
   created. Non-zero status will cause the tag to fail. ID of
-  changeset to tag is in `$HG_NODE`. Name of tag is in `$HG_TAG`. Tag is
-  local if `$HG_LOCAL=1`, in repository if `$HG_LOCAL=0`.
-pretxnchangegroup;;
+  changeset to tag is in ``$HG_NODE``. Name of tag is in ``$HG_TAG``. Tag is
+  local if ``$HG_LOCAL=1``, in repository if ``$HG_LOCAL=0``.
+``pretxnchangegroup``
   Run after a changegroup has been added via push, pull or unbundle,
   but before the transaction has been committed. Changegroup is
   visible to hook program. This lets you validate incoming changes
   before accepting them. Passed the ID of the first new changeset in
-  `$HG_NODE`. Exit status 0 allows the transaction to commit. Non-zero
+  ``$HG_NODE``. Exit status 0 allows the transaction to commit. Non-zero
   status will cause the transaction to be rolled back and the push,
   pull or unbundle will fail. URL that was source of changes is in
-  `$HG_URL`.
-pretxncommit;;
+  ``$HG_URL``.
+``pretxncommit``
   Run after a changeset has been created but the transaction not yet
   committed. Changeset is visible to hook program. This lets you
   validate commit message and changes. Exit status 0 allows the
   commit to proceed. Non-zero status will cause the transaction to
-  be rolled back. ID of changeset is in `$HG_NODE`. Parent changeset
-  IDs are in `$HG_PARENT1` and `$HG_PARENT2`.
-preupdate;;
+  be rolled back. ID of changeset is in ``$HG_NODE``. Parent changeset
+  IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
+``preupdate``
   Run before updating the working directory. Exit status 0 allows
   the update to proceed. Non-zero status will prevent the update.
-  Changeset ID of first new parent is in `$HG_PARENT1`. If merge, ID
-  of second new parent is in `$HG_PARENT2`.
-tag;;
-  Run after a tag is created. ID of tagged changeset is in `$HG_NODE`.
-  Name of tag is in `$HG_TAG`. Tag is local if `$HG_LOCAL=1`, in
-  repository if `$HG_LOCAL=0`.
-update;;
+  Changeset ID of first new parent is in ``$HG_PARENT1``. If merge, ID
+  of second new parent is in ``$HG_PARENT2``.
+``tag``
+  Run after a tag is created. ID of tagged changeset is in ``$HG_NODE``.
+  Name of tag is in ``$HG_TAG``. Tag is local if ``$HG_LOCAL=1``, in
+  repository if ``$HG_LOCAL=0``.
+``update``
   Run after updating the working directory. Changeset ID of first
-  new parent is in `$HG_PARENT1`. If merge, ID of second new parent is
-  in `$HG_PARENT2`. If the update succeeded, `$HG_ERROR=0`. If the
-  update failed (e.g. because conflicts not resolved), `$HG_ERROR=1`.
+  new parent is in ``$HG_PARENT1``. If merge, ID of second new parent is
+  in ``$HG_PARENT2``. If the update succeeded, ``$HG_ERROR=0``. If the
+  update failed (e.g. because conflicts not resolved), ``$HG_ERROR=1``.
 
 NOTE: it is generally better to use standard hooks rather than the
 generic pre- and post- command hooks as they are guaranteed to be
@@ -559,11 +567,11 @@
 generate a commit (e.g. tag) and not just the commit command.
 
 NOTE: Environment variables with empty values may not be passed to
-hooks on platforms such as Windows. As an example, `$HG_PARENT2` will
+hooks on platforms such as Windows. As an example, ``$HG_PARENT2`` will
 have an empty value under Unix-like platforms for non-merge
 changesets, while it will not be available at all under Windows.
 
-The syntax for Python hooks is as follows:
+The syntax for Python hooks is as follows::
 
   hookname = python:modulename.submodule.callable
   hookname = python:/path/to/python/module.py:callable
@@ -573,101 +581,111 @@
 "ui"), a repository object (keyword "repo"), and a "hooktype"
 keyword that tells what kind of hook is used. Arguments listed as
 environment variables above are passed as keyword arguments, with no
-"HG_" prefix, and names in lower case.
+"``HG_``" prefix, and names in lower case.
 
 If a Python hook returns a "true" value or raises an exception, this
 is treated as a failure.
---
+
 
-[[http_proxy]]
-http_proxy::
-  Used to access web-based Mercurial repositories through a HTTP
-  proxy.
-  host;;
+``http_proxy``
+""""""""""""""
+Used to access web-based Mercurial repositories through a HTTP
+proxy.
+
+``host``
     Host name and (optional) port of the proxy server, for example
     "myproxy:8000".
-  no;;
+``no``
     Optional. Comma-separated list of host names that should bypass
     the proxy.
-  passwd;;
+``passwd``
     Optional. Password to authenticate with at the proxy server.
-  user;;
+``user``
     Optional. User name to authenticate with at the proxy server.
 
-[[smtp]]
-smtp::
-  Configuration for extensions that need to send email messages.
-  host;;
+``smtp``
+""""""""
+Configuration for extensions that need to send email messages.
+
+``host``
     Host name of mail server, e.g. "mail.example.com".
-  port;;
+``port``
     Optional. Port to connect to on mail server. Default: 25.
-  tls;;
+``tls``
     Optional. Whether to connect to mail server using TLS. True or
     False. Default: False.
-  username;;
+``username``
     Optional. User name to authenticate to SMTP server with. If
     username is specified, password must also be specified.
     Default: none.
-  password;;
+``password``
     Optional. Password to authenticate to SMTP server with. If
     username is specified, password must also be specified.
     Default: none.
-  local_hostname;;
+``local_hostname``
     Optional. It's the hostname that the sender can use to identify
     itself to the MTA.
 
-[[patch]]
-patch::
-  Settings used when applying patches, for instance through the 'import'
-  command or with Mercurial Queues extension.
-  eol;;
+
+``patch``
+"""""""""
+Settings used when applying patches, for instance through the 'import'
+command or with Mercurial Queues extension.
+
+``eol``
     When set to 'strict' patch content and patched files end of lines
     are preserved. When set to 'lf' or 'crlf', both files end of lines
     are ignored when patching and the result line endings are
     normalized to either LF (Unix) or CRLF (Windows).
     Default: strict.
 
-[[paths]]
-paths::
-  Assigns symbolic names to repositories. The left side is the
-  symbolic name, and the right gives the directory or URL that is the
-  location of the repository. Default paths can be declared by setting
-  the following entries.
-  default;;
+
+``paths``
+"""""""""
+Assigns symbolic names to repositories. The left side is the
+symbolic name, and the right gives the directory or URL that is the
+location of the repository. Default paths can be declared by setting
+the following entries.
+
+``default``
     Directory or URL to use when pulling if no source is specified.
     Default is set to repository from which the current repository was
     cloned.
-  default-push;;
+``default-push``
     Optional. Directory or URL to use when pushing if no destination
     is specified.
 
-[[profiling]]
-profiling::
-  Specifies profiling format and file output. In this section
-  description, 'profiling data' stands for the raw data collected
-  during profiling, while 'profiling report' stands for a statistical
-  text report generated from the profiling data. The profiling is done
-  using lsprof.
-  format;;
+
+``profiling``
+"""""""""""""
+Specifies profiling format and file output. In this section
+description, 'profiling data' stands for the raw data collected
+during profiling, while 'profiling report' stands for a statistical
+text report generated from the profiling data. The profiling is done
+using lsprof.
+
+``format``
     Profiling format.
     Default: text.
-    text;;
+
+    ``text``
       Generate a profiling report. When saving to a file, it should be
       noted that only the report is saved, and the profiling data is
       not kept.
-    kcachegrind;;
+    ``kcachegrind``
       Format profiling data for kcachegrind use: when saving to a
       file, the generated file can directly be loaded into
       kcachegrind.
-  output;;
+``output``
     File path where profiling data or report should be saved. If the
     file exists, it is replaced. Default: None, data is printed on
     stderr
 
-[[server]]
-server::
-  Controls generic server settings.
-  uncompressed;;
+``server``
+""""""""""
+Controls generic server settings.
+
+``uncompressed``
     Whether to allow clients to clone a repository using the
     uncompressed streaming protocol. This transfers about 40% more
     data than a regular clone, but uses less memory and CPU on both
@@ -677,174 +695,175 @@
     about 6 Mbps), uncompressed streaming is slower, because of the
     extra data transfer overhead. Default is False.
 
-[[trusted]]
-trusted::
-  For security reasons, Mercurial will not use the settings in the
-  `.hg/hgrc` file from a repository if it doesn't belong to a trusted
-  user or to a trusted group. The main exception is the web interface,
-  which automatically uses some safe settings, since it's common to
-  serve repositories from different users.
-+
---
+
+``trusted``
+"""""""""""
+For security reasons, Mercurial will not use the settings in the
+``.hg/hgrc`` file from a repository if it doesn't belong to a trusted
+user or to a trusted group. The main exception is the web interface,
+which automatically uses some safe settings, since it's common to
+serve repositories from different users.
+
 This section specifies what users and groups are trusted. The
 current user is always trusted. To trust everybody, list a user or a
-group with name "`*`".
+group with name "``*``".
 
-users;;
+``users``
   Comma-separated list of trusted users.
-groups;;
+``groups``
   Comma-separated list of trusted groups.
---
+
 
-[[ui]]
-ui::
-  User interface controls.
-+
---
-  archivemeta;;
+``ui``
+""""""
+
+User interface controls.
+
+``archivemeta``
     Whether to include the .hg_archival.txt file containing meta data
     (hashes for the repository base and for tip) in archives created
     by the hg archive command or downloaded via hgweb.
     Default is true.
-  askusername;;
+``askusername``
     Whether to prompt for a username when committing. If True, and
-    neither `$HGUSER` nor `$EMAIL` has been specified, then the user will
+    neither ``$HGUSER`` nor ``$EMAIL`` has been specified, then the user will
     be prompted to enter a username. If no username is entered, the
     default USER@HOST is used instead.
     Default is False.
-  debug;;
+``debug``
     Print debugging information. True or False. Default is False.
-  editor;;
-    The editor to use during a commit. Default is `$EDITOR` or "vi".
-  fallbackencoding;;
+``editor``
+    The editor to use during a commit. Default is ``$EDITOR`` or "vi".
+``fallbackencoding``
     Encoding to try if it's not possible to decode the changelog using
     UTF-8. Default is ISO-8859-1.
-  ignore;;
+``ignore``
     A file to read per-user ignore patterns from. This file should be
     in the same format as a repository-wide .hgignore file. This
     option supports hook syntax, so if you want to specify multiple
     ignore files, you can do so by setting something like
-    "ignore.other = ~/.hgignore2". For details of the ignore file
-    format, see the hgignore(5) man page.
-  interactive;;
+    "``ignore.other = ~/.hgignore2``". For details of the ignore file
+    format, see the |hgignore(5)|_ man page.
+``interactive``
     Allow to prompt the user. True or False. Default is True.
-  logtemplate;;
+``logtemplate``
     Template string for commands that print changesets.
-  merge;;
+``merge``
     The conflict resolution program to use during a manual merge.
     There are some internal tools available:
-+
-      internal:local;;
+
+    ``internal:local``
         keep the local version
-      internal:other;;
+    ``internal:other``
         use the other version
-      internal:merge;;
+    ``internal:merge``
         use the internal non-interactive merge tool
-      internal:fail;;
+    ``internal:fail``
         fail to merge
-+
+
 For more information on configuring merge tools see the
 merge-tools section.
 
-  patch;;
+``patch``
     command to use to apply patches. Look for 'gpatch' or 'patch' in
     PATH if unset.
-  quiet;;
+``quiet``
     Reduce the amount of output printed. True or False. Default is False.
-  remotecmd;;
+``remotecmd``
     remote command to use for clone/push/pull operations. Default is 'hg'.
-  report_untrusted;;
-    Warn if a `.hg/hgrc` file is ignored due to not being owned by a
+``report_untrusted``
+    Warn if a ``.hg/hgrc`` file is ignored due to not being owned by a
     trusted user or group. True or False. Default is True.
-  slash;;
-    Display paths using a slash ("`/`") as the path separator. This
+``slash``
+    Display paths using a slash ("``/``") as the path separator. This
     only makes a difference on systems where the default path
     separator is not the slash character (e.g. Windows uses the
-    backslash character ("`\`")).
+    backslash character ("``\``")).
     Default is False.
-  ssh;;
+``ssh``
     command to use for SSH connections. Default is 'ssh'.
-  strict;;
+``strict``
     Require exact command names, instead of allowing unambiguous
     abbreviations. True or False. Default is False.
-  style;;
+``style``
     Name of style to use for command output.
-  timeout;;
+``timeout``
     The timeout used when a lock is held (in seconds), a negative value
     means no timeout. Default is 600.
-  username;;
+``username``
     The committer of a changeset created when running "commit".
     Typically a person's name and email address, e.g. "Fred Widget
-    <fred@example.com>". Default is `$EMAIL` or username@hostname. If
+    <fred@example.com>". Default is ``$EMAIL`` or username@hostname. If
     the username in hgrc is empty, it has to be specified manually or
-    in a different hgrc file (e.g. `$HOME/.hgrc`, if the admin set
+    in a different hgrc file (e.g. ``$HOME/.hgrc``, if the admin set
     "username =" in the system hgrc).
-  verbose;;
+``verbose``
     Increase the amount of output printed. True or False. Default is False.
---
+
 
-[[web]]
-web::
-  Web interface configuration.
-  accesslog;;
+``web``
+"""""""
+Web interface configuration.
+
+``accesslog``
     Where to output the access log. Default is stdout.
-  address;;
+``address``
     Interface address to bind to. Default is all.
-  allow_archive;;
+``allow_archive``
     List of archive format (bz2, gz, zip) allowed for downloading.
     Default is empty.
-  allowbz2;;
+``allowbz2``
     (DEPRECATED) Whether to allow .tar.bz2 downloading of repository
     revisions.
     Default is false.
-  allowgz;;
+``allowgz``
     (DEPRECATED) Whether to allow .tar.gz downloading of repository
     revisions.
     Default is false.
-  allowpull;;
+``allowpull``
     Whether to allow pulling from the repository. Default is true.
-  allow_push;;
+``allow_push``
     Whether to allow pushing to the repository. If empty or not set,
-    push is not allowed. If the special value "`*`", any remote user can
+    push is not allowed. If the special value "``*``", any remote user can
     push, including unauthenticated users. Otherwise, the remote user
     must have been authenticated, and the authenticated user name must
     be present in this list (separated by whitespace or ","). The
     contents of the allow_push list are examined after the deny_push
     list.
-  allow_read;;
+``allow_read``
     If the user has not already been denied repository access due to
     the contents of deny_read, this list determines whether to grant
     repository access to the user. If this list is not empty, and the
     user is unauthenticated or not present in the list (separated by
     whitespace or ","), then access is denied for the user. If the
     list is empty or not set, then access is permitted to all users by
-    default. Setting allow_read to the special value "`*`" is equivalent
+    default. Setting allow_read to the special value "``*``" is equivalent
     to it not being set (i.e. access is permitted to all users). The
     contents of the allow_read list are examined after the deny_read
     list.
-  allowzip;;
+``allowzip``
     (DEPRECATED) Whether to allow .zip downloading of repository
     revisions. Default is false. This feature creates temporary files.
-  baseurl;;
+``baseurl``
     Base URL to use when publishing URLs in other locations, so
     third-party tools like email notification hooks can construct
     URLs. Example: "http://hgserver/repos/"
-  contact;;
+``contact``
     Name or email address of the person in charge of the repository.
-    Defaults to ui.username or `$EMAIL` or "unknown" if unset or empty.
-  deny_push;;
+    Defaults to ui.username or ``$EMAIL`` or "unknown" if unset or empty.
+``deny_push``
     Whether to deny pushing to the repository. If empty or not set,
-    push is not denied. If the special value "`*`", all remote users are
+    push is not denied. If the special value "``*``", all remote users are
     denied push. Otherwise, unauthenticated users are all denied, and
     any authenticated user name present in this list (separated by
     whitespace or ",") is also denied. The contents of the deny_push
     list are examined before the allow_push list.
-  deny_read;;
+``deny_read``
     Whether to deny reading/viewing of the repository. If this list is
     not empty, unauthenticated users are all denied, and any
     authenticated user name present in this list (separated by
     whitespace or ",") is also denied access to the repository. If set
-    to the special value "`*`", all remote users are denied access
+    to the special value "``*``", all remote users are denied access
     (rarely needed ;). If deny_read is empty or not set, the
     determination of repository access depends on the presence and
     content of the allow_read list (see description). If both
@@ -854,44 +873,44 @@
     the list of repositories. The contents of the deny_read list have
     priority over (are examined before) the contents of the allow_read
     list.
-  description;;
+``description``
     Textual description of the repository's purpose or contents.
     Default is "unknown".
-  encoding;;
+``encoding``
     Character encoding name.
     Example: "UTF-8"
-  errorlog;;
+``errorlog``
     Where to output the error log. Default is stderr.
-  hidden;;
+``hidden``
     Whether to hide the repository in the hgwebdir index.
     Default is false.
-  ipv6;;
+``ipv6``
     Whether to use IPv6. Default is false.
-  name;;
+``name``
     Repository name to use in the web interface. Default is current
     working directory.
-  maxchanges;;
+``maxchanges``
     Maximum number of changes to list on the changelog. Default is 10.
-  maxfiles;;
+``maxfiles``
     Maximum number of files to list per changeset. Default is 10.
-  port;;
+``port``
     Port to listen on. Default is 8000.
-  prefix;;
+``prefix``
     Prefix path to serve from. Default is '' (server root).
-  push_ssl;;
+``push_ssl``
     Whether to require that inbound pushes be transported over SSL to
     prevent password sniffing. Default is true.
-  staticurl;;
+``staticurl``
     Base URL to use for static files. If unset, static files (e.g. the
     hgicon.png favicon) will be served by the CGI script itself. Use
     this setting to serve them directly with the HTTP server.
     Example: "http://hgserver/static/"
-  stripes;;
+``stripes``
     How many lines a "zebra stripe" should span in multiline output.
     Default is 1; set to 0 to disable.
-  style;;
+``style``
     Which template map style to use.
-  templates;;
+``templates``
     Where to find the HTML templates. Default is install path.
 
 
@@ -903,7 +922,7 @@
 
 SEE ALSO
 --------
-hg(1), hgignore(5)
+|hg(1)|_, |hgignore(5)|_
 
 COPYING
 -------
@@ -911,3 +930,5 @@
 Mercurial is copyright 2005-2009 Matt Mackall.
 Free use of this software is granted under the terms of the GNU General
 Public License (GPL).
+
+.. include:: common.txt
--- a/hgext/acl.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/acl.py	Thu Aug 06 18:48:00 2009 -0700
@@ -8,21 +8,20 @@
 
 '''hooks for controlling repository access
 
-This hook makes it possible to allow or deny write access to portions
-of a repository when receiving incoming changesets.
+This hook makes it possible to allow or deny write access to portions of a
+repository when receiving incoming changesets.
 
-The authorization is matched based on the local user name on the
-system where the hook runs, and not the committer of the original
-changeset (since the latter is merely informative).
+The authorization is matched based on the local user name on the system where
+the hook runs, and not the committer of the original changeset (since the
+latter is merely informative).
 
-The acl hook is best used along with a restricted shell like hgsh,
-preventing authenticating users from doing anything other than
-pushing or pulling. The hook is not safe to use if users have
-interactive shell access, as they can then disable the hook.
-Nor is it safe if remote users share an account, because then there
-is no way to distinguish them.
+The acl hook is best used along with a restricted shell like hgsh, preventing
+authenticating users from doing anything other than pushing or pulling. The
+hook is not safe to use if users have interactive shell access, as they can
+then disable the hook. Nor is it safe if remote users share an account,
+because then there is no way to distinguish them.
 
-To use this hook, configure the acl extension in your hgrc like this:
+To use this hook, configure the acl extension in your hgrc like this::
 
   [extensions]
   hgext.acl =
@@ -35,10 +34,9 @@
   # ("serve" == ssh or http, "push", "pull", "bundle")
   sources = serve
 
-The allow and deny sections take a subtree pattern as key (with a
-glob syntax by default), and a comma separated list of users as
-the corresponding value. The deny list is checked before the allow
-list is.
+The allow and deny sections take a subtree pattern as key (with a glob syntax
+by default), and a comma separated list of users as the corresponding value.
+The deny list is checked before the allow list is. ::
 
   [acl.allow]
   # If acl.allow is not present, all users are allowed by default.
--- a/hgext/bookmarks.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/bookmarks.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,25 +7,22 @@
 
 '''track a line of development with movable markers
 
-Bookmarks are local movable markers to changesets. Every bookmark
-points to a changeset identified by its hash. If you commit a
-changeset that is based on a changeset that has a bookmark on it,
-the bookmark shifts to the new changeset.
+Bookmarks are local movable markers to changesets. Every bookmark points to a
+changeset identified by its hash. If you commit a changeset that is based on a
+changeset that has a bookmark on it, the bookmark shifts to the new changeset.
 
-It is possible to use bookmark names in every revision lookup
-(e.g. hg merge, hg update).
+It is possible to use bookmark names in every revision lookup (e.g. hg merge,
+hg update).
 
-By default, when several bookmarks point to the same changeset, they
-will all move forward together. It is possible to obtain a more
-git-like experience by adding the following configuration option to
-your .hgrc:
+By default, when several bookmarks point to the same changeset, they will all
+move forward together. It is possible to obtain a more git-like experience by
+adding the following configuration option to your .hgrc::
 
   [bookmarks]
   track.current = True
 
-This will cause Mercurial to track the bookmark that you are currently
-using, and only update it. This is similar to git's approach to
-branching.
+This will cause Mercurial to track the bookmark that you are currently using,
+and only update it. This is similar to git's approach to branching.
 '''
 
 from mercurial.i18n import _
@@ -124,15 +121,15 @@
 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False, rename=None):
     '''track a line of development with movable markers
 
-    Bookmarks are pointers to certain commits that move when
-    committing. Bookmarks are local. They can be renamed, copied and
-    deleted. It is possible to use bookmark names in 'hg merge' and
-    'hg update' to merge and update respectively to a given bookmark.
+    Bookmarks are pointers to certain commits that move when committing.
+    Bookmarks are local. They can be renamed, copied and deleted. It is
+    possible to use bookmark names in 'hg merge' and 'hg update' to merge and
+    update respectively to a given bookmark.
 
     You can use 'hg bookmark NAME' to set a bookmark on the working
-    directory's parent revision with the given name. If you specify
-    a revision using -r REV (where REV may be an existing bookmark),
-    the bookmark is assigned to that revision.
+    directory's parent revision with the given name. If you specify a revision
+    using -r REV (where REV may be an existing bookmark), the bookmark is
+    assigned to that revision.
     '''
     hexfn = ui.debugflag and hex or short
     marks = parse(repo)
@@ -249,12 +246,12 @@
                 key = self._bookmarks[key]
             return super(bookmark_repo, self).lookup(key)
 
-        def commit(self, *k, **kw):
+        def commitctx(self, ctx, error=False):
             """Add a revision to the repository and
             move the bookmark"""
             wlock = self.wlock() # do both commit and bookmark with lock held
             try:
-                node  = super(bookmark_repo, self).commit(*k, **kw)
+                node  = super(bookmark_repo, self).commitctx(ctx, error)
                 if node is None:
                     return None
                 parents = self.changelog.parents(node)
@@ -262,12 +259,13 @@
                     parents = (parents[0],)
                 marks = parse(self)
                 update = False
-                for mark, n in marks.items():
-                    if ui.configbool('bookmarks', 'track.current'):
-                        if mark == current(self) and n in parents:
-                            marks[mark] = node
-                            update = True
-                    else:
+                if ui.configbool('bookmarks', 'track.current'):
+                    mark = current(self)
+                    if mark and marks[mark] in parents:
+                        marks[mark] = node
+                        update = True
+                else:
+                    for mark, n in marks.items():
                         if n in parents:
                             marks[mark] = node
                             update = True
@@ -288,22 +286,25 @@
             node = self.changelog.tip()
             marks = parse(self)
             update = False
-            for mark, n in marks.items():
-                if n in parents:
+            if ui.configbool('bookmarks', 'track.current'):
+                mark = current(self)
+                if mark and marks[mark] in parents:
                     marks[mark] = node
                     update = True
+            else:
+                for mark, n in marks.items():
+                    if n in parents:
+                        marks[mark] = node
+                        update = True
             if update:
                 write(self, marks)
             return result
 
-        def tags(self):
+        def _findtags(self):
             """Merge bookmarks with normal tags"""
-            if self.tagscache:
-                return self.tagscache
-
-            tagscache = super(bookmark_repo, self).tags()
-            tagscache.update(parse(self))
-            return tagscache
+            (tags, tagtypes) = super(bookmark_repo, self)._findtags()
+            tags.update(parse(self))
+            return (tags, tagtypes)
 
     repo.__class__ = bookmark_repo
 
--- a/hgext/bugzilla.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/bugzilla.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,79 +7,95 @@
 
 '''hooks for integrating with the Bugzilla bug tracker
 
-This hook extension adds comments on bugs in Bugzilla when changesets
-that refer to bugs by Bugzilla ID are seen. The hook does not change
-bug status.
+This hook extension adds comments on bugs in Bugzilla when changesets that
+refer to bugs by Bugzilla ID are seen. The hook does not change bug status.
+
+The hook updates the Bugzilla database directly. Only Bugzilla installations
+using MySQL are supported.
 
-The hook updates the Bugzilla database directly. Only Bugzilla
-installations using MySQL are supported.
+The hook relies on a Bugzilla script to send bug change notification emails.
+That script changes between Bugzilla versions; the 'processmail' script used
+prior to 2.18 is replaced in 2.18 and subsequent versions by
+'config/sendbugmail.pl'. Note that these will be run by Mercurial as the user
+pushing the change; you will need to ensure the Bugzilla install file
+permissions are set appropriately.
+
+The extension is configured through three different configuration sections.
+These keys are recognized in the [bugzilla] section:
+
+host
+  Hostname of the MySQL server holding the Bugzilla database.
 
-The hook relies on a Bugzilla script to send bug change notification
-emails. That script changes between Bugzilla versions; the
-'processmail' script used prior to 2.18 is replaced in 2.18 and
-subsequent versions by 'config/sendbugmail.pl'. Note that these will
-be run by Mercurial as the user pushing the change; you will need to
-ensure the Bugzilla install file permissions are set appropriately.
+db
+  Name of the Bugzilla database in MySQL. Default 'bugs'.
+
+user
+  Username to use to access MySQL server. Default 'bugs'.
+
+password
+  Password to use to access MySQL server.
+
+timeout
+  Database connection timeout (seconds). Default 5.
 
-Configuring the extension:
+version
+  Bugzilla version. Specify '3.0' for Bugzilla versions 3.0 and later, '2.18'
+  for Bugzilla versions from 2.18 and '2.16' for versions prior to 2.18.
 
-    [bugzilla]
+bzuser
+  Fallback Bugzilla user name to record comments with, if changeset committer
+  cannot be found as a Bugzilla user.
+
+bzdir
+   Bugzilla install directory. Used by default notify. Default
+   '/var/www/html/bugzilla'.
 
-    host       Hostname of the MySQL server holding the Bugzilla
-               database.
-    db         Name of the Bugzilla database in MySQL. Default 'bugs'.
-    user       Username to use to access MySQL server. Default 'bugs'.
-    password   Password to use to access MySQL server.
-    timeout    Database connection timeout (seconds). Default 5.
-    version    Bugzilla version. Specify '3.0' for Bugzilla versions
-               3.0 and later, '2.18' for Bugzilla versions from 2.18
-               and '2.16' for versions prior to 2.18.
-    bzuser     Fallback Bugzilla user name to record comments with, if
-               changeset committer cannot be found as a Bugzilla user.
-    bzdir      Bugzilla install directory. Used by default notify.
-               Default '/var/www/html/bugzilla'.
-    notify     The command to run to get Bugzilla to send bug change
-               notification emails. Substitutes from a map with 3
-               keys, 'bzdir', 'id' (bug id) and 'user' (committer
-               bugzilla email). Default depends on version; from 2.18
-               it is "cd %(bzdir)s && perl -T contrib/sendbugmail.pl
-               %(id)s %(user)s".
-    regexp     Regular expression to match bug IDs in changeset commit
-               message. Must contain one "()" group. The default
-               expression matches 'Bug 1234', 'Bug no. 1234', 'Bug
-               number 1234', 'Bugs 1234,5678', 'Bug 1234 and 5678' and
-               variations thereof. Matching is case insensitive.
-    style      The style file to use when formatting comments.
-    template   Template to use when formatting comments. Overrides
-               style if specified. In addition to the usual Mercurial
-               keywords, the extension specifies:
-                   {bug}       The Bugzilla bug ID.
-                   {root}      The full pathname of the Mercurial
-                               repository.
-                   {webroot}   Stripped pathname of the Mercurial
-                               repository.
-                   {hgweb}     Base URL for browsing Mercurial
-                               repositories.
-               Default 'changeset {node|short} in repo {root} refers '
-                       'to bug {bug}.\\ndetails:\\n\\t{desc|tabindent}'
-    strip      The number of slashes to strip from the front of {root}
-               to produce {webroot}. Default 0.
-    usermap    Path of file containing Mercurial committer ID to
-               Bugzilla user ID mappings. If specified, the file
-               should contain one mapping per line,
-               "committer"="Bugzilla user". See also the [usermap]
-               section.
+notify
+  The command to run to get Bugzilla to send bug change notification emails.
+  Substitutes from a map with 3 keys, 'bzdir', 'id' (bug id) and 'user'
+  (committer bugzilla email). Default depends on version; from 2.18 it is "cd
+  %(bzdir)s && perl -T contrib/sendbugmail.pl %(id)s %(user)s".
+
+regexp
+  Regular expression to match bug IDs in changeset commit message. Must
+  contain one "()" group. The default expression matches 'Bug 1234', 'Bug no.
+  1234', 'Bug number 1234', 'Bugs 1234,5678', 'Bug 1234 and 5678' and
+  variations thereof. Matching is case insensitive.
+
+style
+  The style file to use when formatting comments.
+
+template
+  Template to use when formatting comments. Overrides style if specified. In
+  addition to the usual Mercurial keywords, the extension specifies::
 
-    [usermap]
-    Any entries in this section specify mappings of Mercurial
-    committer ID to Bugzilla user ID. See also [bugzilla].usermap.
-    "committer"="Bugzilla user"
+    {bug}       The Bugzilla bug ID.
+    {root}      The full pathname of the Mercurial repository.
+    {webroot}   Stripped pathname of the Mercurial repository.
+    {hgweb}     Base URL for browsing Mercurial repositories.
+
+  Default 'changeset {node|short} in repo {root} refers '
+          'to bug {bug}.\\ndetails:\\n\\t{desc|tabindent}'
+
+strip
+  The number of slashes to strip from the front of {root} to produce
+  {webroot}. Default 0.
 
-    [web]
-    baseurl    Base URL for browsing Mercurial repositories. Reference
-               from templates as {hgweb}.
+usermap
+  Path of file containing Mercurial committer ID to Bugzilla user ID mappings.
+  If specified, the file should contain one mapping per line,
+  "committer"="Bugzilla user". See also the [usermap] section.
+
+The [usermap] section is used to specify mappings of Mercurial committer ID to
+Bugzilla user ID. See also [bugzilla].usermap. "committer"="Bugzilla user"
 
-Activating the extension:
+Finally, the [web] section supports one entry:
+
+baseurl
+  Base URL for browsing Mercurial repositories. Reference from templates as
+  {hgweb}.
+
+Activating the extension::
 
     [extensions]
     hgext.bugzilla =
@@ -90,9 +106,9 @@
 
 Example configuration:
 
-This example configuration is for a collection of Mercurial
-repositories in /var/local/hg/repos/ used with a local Bugzilla 3.2
-installation in /opt/bugzilla-3.2.
+This example configuration is for a collection of Mercurial repositories in
+/var/local/hg/repos/ used with a local Bugzilla 3.2 installation in
+/opt/bugzilla-3.2. ::
 
     [bugzilla]
     host=localhost
@@ -100,7 +116,9 @@
     version=3.0
     bzuser=unknown@domain.com
     bzdir=/opt/bugzilla-3.2
-    template=Changeset {node|short} in {root|basename}.\\n{hgweb}/{webroot}/rev/{node|short}\\n\\n{desc}\\n
+    template=Changeset {node|short} in {root|basename}.
+             {hgweb}/{webroot}/rev/{node|short}\\n
+             {desc}\\n
     strip=5
 
     [web]
@@ -109,7 +127,7 @@
     [usermap]
     user@emaildomain.com=user.name@bugzilladomain.com
 
-Commits add a comment to the Bugzilla bug record of the form:
+Commits add a comment to the Bugzilla bug record of the form::
 
     Changeset 3b16791d6642 in repository-name.
     http://dev.domain.com/hg/repository-name/rev/3b16791d6642
--- a/hgext/children.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/children.py	Thu Aug 06 18:48:00 2009 -0700
@@ -18,11 +18,11 @@
 def children(ui, repo, file_=None, **opts):
     """show the children of the given or working directory revision
 
-    Print the children of the working directory's revisions. If a
-    revision is given via -r/--rev, the children of that revision will
-    be printed. If a file argument is given, revision in which the
-    file was last changed (after the working directory revision or the
-    argument to --rev if given) is printed.
+    Print the children of the working directory's revisions. If a revision is
+    given via -r/--rev, the children of that revision will be printed. If a
+    file argument is given, revision in which the file was last changed (after
+    the working directory revision or the argument to --rev if given) is
+    printed.
     """
     rev = opts.get('rev')
     if file_:
--- a/hgext/churn.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/churn.py	Thu Aug 06 18:48:00 2009 -0700
@@ -94,17 +94,15 @@
 def churn(ui, repo, *pats, **opts):
     '''histogram of changes to the repository
 
-    This command will display a histogram representing the number
-    of changed lines or revisions, grouped according to the given
-    template. The default template will group changes by author.
-    The --dateformat option may be used to group the results by
-    date instead.
+    This command will display a histogram representing the number of changed
+    lines or revisions, grouped according to the given template. The default
+    template will group changes by author. The --dateformat option may be used
+    to group the results by date instead.
 
-    Statistics are based on the number of changed lines, or
-    alternatively the number of matching revisions if the
-    --changesets option is specified.
+    Statistics are based on the number of changed lines, or alternatively the
+    number of matching revisions if the --changesets option is specified.
 
-    Examples:
+    Examples::
 
       # display count of changed lines for every committer
       hg churn -t '{author|email}'
@@ -118,10 +116,10 @@
       # display count of lines changed in every year
       hg churn -f '%Y' -s
 
-    It is possible to map alternate email addresses to a main address
-    by providing a file using the following format:
+    It is possible to map alternate email addresses to a main address by
+    providing a file using the following format::
 
-    <alias email> <actual email>
+      <alias email> <actual email>
 
     Such a file may be specified with the --aliases option, otherwise a
     .hgchurn file will be looked for in the working directory root.
@@ -143,8 +141,8 @@
     if not rate:
         return
 
-    sortfn = ((not opts.get('sort')) and (lambda a, b: cmp(b[1], a[1])) or None)
-    rate.sort(sortfn)
+    sortkey = ((not opts.get('sort')) and (lambda x: -x[1]) or None)
+    rate.sort(key=sortkey)
 
     maxcount = float(max([v for k, v in rate]))
     maxname = max([len(k) for k, v in rate])
--- a/hgext/color.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/color.py	Thu Aug 06 18:48:00 2009 -0700
@@ -18,44 +18,43 @@
 
 '''colorize output from some commands
 
-This extension modifies the status command to add color to its output
-to reflect file status, the qseries command to add color to reflect
-patch status (applied, unapplied, missing), and to diff-related
-commands to highlight additions, removals, diff headers, and trailing
-whitespace.
+This extension modifies the status command to add color to its output to
+reflect file status, the qseries command to add color to reflect patch status
+(applied, unapplied, missing), and to diff-related commands to highlight
+additions, removals, diff headers, and trailing whitespace.
 
-Other effects in addition to color, like bold and underlined text, are
-also available. Effects are rendered with the ECMA-48 SGR control
-function (aka ANSI escape codes). This module also provides the
-render_text function, which can be used to add effects to any text.
+Other effects in addition to color, like bold and underlined text, are also
+available. Effects are rendered with the ECMA-48 SGR control function (aka
+ANSI escape codes). This module also provides the render_text function, which
+can be used to add effects to any text.
 
-Default effects may be overridden from the .hgrc file:
+Default effects may be overridden from the .hgrc file::
 
-[color]
-status.modified = blue bold underline red_background
-status.added = green bold
-status.removed = red bold blue_background
-status.deleted = cyan bold underline
-status.unknown = magenta bold underline
-status.ignored = black bold
+  [color]
+  status.modified = blue bold underline red_background
+  status.added = green bold
+  status.removed = red bold blue_background
+  status.deleted = cyan bold underline
+  status.unknown = magenta bold underline
+  status.ignored = black bold
 
-# 'none' turns off all effects
-status.clean = none
-status.copied = none
+  # 'none' turns off all effects
+  status.clean = none
+  status.copied = none
 
-qseries.applied = blue bold underline
-qseries.unapplied = black bold
-qseries.missing = red bold
+  qseries.applied = blue bold underline
+  qseries.unapplied = black bold
+  qseries.missing = red bold
 
-diff.diffline = bold
-diff.extended = cyan bold
-diff.file_a = red bold
-diff.file_b = green bold
-diff.hunk = magenta
-diff.deleted = red
-diff.inserted = green
-diff.changed = white
-diff.trailingwhitespace = bold red_background
+  diff.diffline = bold
+  diff.extended = cyan bold
+  diff.file_a = red bold
+  diff.file_b = green bold
+  diff.hunk = magenta
+  diff.deleted = red
+  diff.inserted = green
+  diff.changed = white
+  diff.trailingwhitespace = bold red_background
 '''
 
 import os, sys
@@ -146,9 +145,9 @@
     for patch in patches:
         patchname = patch
         if opts['summary']:
-            patchname = patchname.split(': ')[0]
+            patchname = patchname.split(': ', 1)[0]
         if ui.verbose:
-            patchname = patchname.split(' ', 2)[-1]
+            patchname = patchname.lstrip().split(' ', 2)[-1]
 
         if opts['missing']:
             effects = _patch_effects['missing']
@@ -158,7 +157,9 @@
             effects = _patch_effects['applied']
         else:
             effects = _patch_effects['unapplied']
-        ui.write(render_effects(patch, effects) + '\n')
+
+        patch = patch.replace(patchname, render_effects(patchname, effects), 1)
+        ui.write(patch + '\n')
     return retval
 
 _patch_effects = { 'applied': ['blue', 'bold', 'underline'],
--- a/hgext/convert/__init__.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/convert/__init__.py	Thu Aug 06 18:48:00 2009 -0700
@@ -19,6 +19,7 @@
     """convert a foreign SCM repository to a Mercurial one.
 
     Accepted source formats [identifiers]:
+
     - Mercurial [hg]
     - CVS [cvs]
     - Darcs [darcs]
@@ -30,48 +31,52 @@
     - Perforce [p4]
 
     Accepted destination formats [identifiers]:
+
     - Mercurial [hg]
     - Subversion [svn] (history on branches is not preserved)
 
-    If no revision is given, all revisions will be converted.
-    Otherwise, convert will only import up to the named revision
-    (given in a format understood by the source).
+    If no revision is given, all revisions will be converted. Otherwise,
+    convert will only import up to the named revision (given in a format
+    understood by the source).
 
-    If no destination directory name is specified, it defaults to the
-    basename of the source with '-hg' appended. If the destination
-    repository doesn't exist, it will be created.
+    If no destination directory name is specified, it defaults to the basename
+    of the source with '-hg' appended. If the destination repository doesn't
+    exist, it will be created.
 
-    By default, all sources except Mercurial will use
-    --branchsort. Mercurial uses --sourcesort to preserve original
-    revision numbers order. Sort modes have the following effects:
-      --branchsort: convert from parent to child revision when
-        possible, which means branches are usually converted one after
-        the other. It generates more compact repositories.
-      --datesort: sort revisions by date. Converted repositories have
-        good-looking changelogs but are often an order of magnitude
-        larger than the same ones generated by --branchsort.
-      --sourcesort: try to preserve source revisions order, only
-        supported by Mercurial sources.
+    By default, all sources except Mercurial will use --branchsort. Mercurial
+    uses --sourcesort to preserve original revision numbers order. Sort modes
+    have the following effects:
+
+    --branchsort  convert from parent to child revision when possible, which
+                  means branches are usually converted one after the other. It
+                  generates more compact repositories.
+
+    --datesort    sort revisions by date. Converted repositories have
+                  good-looking changelogs but are often an order of magnitude
+                  larger than the same ones generated by --branchsort.
+
+    --sourcesort  try to preserve source revisions order, only supported by
+                  Mercurial sources.
 
     If <REVMAP> isn't given, it will be put in a default location
-    (<dest>/.hg/shamap by default). The <REVMAP> is a simple text file
-    that maps each source commit ID to the destination ID for that
-    revision, like so:
-    <source ID> <destination ID>
+    (<dest>/.hg/shamap by default). The <REVMAP> is a simple text file that
+    maps each source commit ID to the destination ID for that revision, like
+    so::
 
-    If the file doesn't exist, it's automatically created. It's
-    updated on each commit copied, so convert-repo can be interrupted
-    and can be run repeatedly to copy new commits.
+      <source ID> <destination ID>
 
-    The [username mapping] file is a simple text file that maps each
-    source commit author to a destination commit author. It is handy
-    for source SCMs that use unix logins to identify authors (eg:
-    CVS). One line per author mapping and the line format is:
-    srcauthor=whatever string you want
+    If the file doesn't exist, it's automatically created. It's updated on
+    each commit copied, so convert-repo can be interrupted and can be run
+    repeatedly to copy new commits.
 
-    The filemap is a file that allows filtering and remapping of files
-    and directories. Comment lines start with '#'. Each line can
-    contain one of the following directives:
+    The [username mapping] file is a simple text file that maps each source
+    commit author to a destination commit author. It is handy for source SCMs
+    that use unix logins to identify authors (eg: CVS). One line per author
+    mapping and the line format is: srcauthor=whatever string you want
+
+    The filemap is a file that allows filtering and remapping of files and
+    directories. Comment lines start with '#'. Each line can contain one of
+    the following directives::
 
       include path/to/file
 
@@ -79,113 +84,109 @@
 
       rename from/file to/file
 
-    The 'include' directive causes a file, or all files under a
-    directory, to be included in the destination repository, and the
-    exclusion of all other files and directories not explicitly included.
-    The 'exclude' directive causes files or directories to be omitted.
-    The 'rename' directive renames a file or directory. To rename from
-    a subdirectory into the root of the repository, use '.' as the
-    path to rename to.
+    The 'include' directive causes a file, or all files under a directory, to
+    be included in the destination repository, and the exclusion of all other
+    files and directories not explicitly included. The 'exclude' directive
+    causes files or directories to be omitted. The 'rename' directive renames
+    a file or directory. To rename from a subdirectory into the root of the
+    repository, use '.' as the path to rename to.
 
-    The splicemap is a file that allows insertion of synthetic
-    history, letting you specify the parents of a revision. This is
-    useful if you want to e.g. give a Subversion merge two parents, or
-    graft two disconnected series of history together. Each entry
-    contains a key, followed by a space, followed by one or two
-    comma-separated values. The key is the revision ID in the source
-    revision control system whose parents should be modified (same
-    format as a key in .hg/shamap). The values are the revision IDs
-    (in either the source or destination revision control system) that
+    The splicemap is a file that allows insertion of synthetic history,
+    letting you specify the parents of a revision. This is useful if you want
+    to e.g. give a Subversion merge two parents, or graft two disconnected
+    series of history together. Each entry contains a key, followed by a
+    space, followed by one or two comma-separated values. The key is the
+    revision ID in the source revision control system whose parents should be
+    modified (same format as a key in .hg/shamap). The values are the revision
+    IDs (in either the source or destination revision control system) that
     should be used as the new parents for that node.
 
     The branchmap is a file that allows you to rename a branch when it is
     being brought in from whatever external repository. When used in
-    conjunction with a splicemap, it allows for a powerful combination
-    to help fix even the most badly mismanaged repositories and turn them
-    into nicely structured Mercurial repositories. The branchmap contains
-    lines of the form "original_branch_name new_branch_name".
-    "original_branch_name" is the name of the branch in the source
-    repository, and "new_branch_name" is the name of the branch is the
-    destination repository. This can be used to (for instance) move code
-    in one repository from "default" to a named branch.
+    conjunction with a splicemap, it allows for a powerful combination to help
+    fix even the most badly mismanaged repositories and turn them into nicely
+    structured Mercurial repositories. The branchmap contains lines of the
+    form "original_branch_name new_branch_name". "original_branch_name" is the
+    name of the branch in the source repository, and "new_branch_name" is the
+    name of the branch is the destination repository. This can be used to (for
+    instance) move code in one repository from "default" to a named branch.
 
     Mercurial Source
-    -----------------
+    ----------------
 
     --config convert.hg.ignoreerrors=False    (boolean)
         ignore integrity errors when reading. Use it to fix Mercurial
         repositories with missing revlogs, by converting from and to
         Mercurial.
     --config convert.hg.saverev=False         (boolean)
-        store original revision ID in changeset (forces target IDs to
-        change)
+        store original revision ID in changeset (forces target IDs to change)
     --config convert.hg.startrev=0            (hg revision identifier)
         convert start revision and its descendants
 
     CVS Source
     ----------
 
-    CVS source will use a sandbox (i.e. a checked-out copy) from CVS
-    to indicate the starting point of what will be converted. Direct
-    access to the repository files is not needed, unless of course the
-    repository is :local:. The conversion uses the top level directory
-    in the sandbox to find the CVS repository, and then uses CVS rlog
-    commands to find files to convert. This means that unless a
-    filemap is given, all files under the starting directory will be
-    converted, and that any directory reorganization in the CVS
-    sandbox is ignored.
+    CVS source will use a sandbox (i.e. a checked-out copy) from CVS to
+    indicate the starting point of what will be converted. Direct access to
+    the repository files is not needed, unless of course the repository is
+    :local:. The conversion uses the top level directory in the sandbox to
+    find the CVS repository, and then uses CVS rlog commands to find files to
+    convert. This means that unless a filemap is given, all files under the
+    starting directory will be converted, and that any directory
+    reorganization in the CVS sandbox is ignored.
 
     Because CVS does not have changesets, it is necessary to collect
-    individual commits to CVS and merge them into changesets. CVS
-    source uses its internal changeset merging code by default but can
-    be configured to call the external 'cvsps' program by setting:
-        --config convert.cvsps='cvsps -A -u --cvs-direct -q'
+    individual commits to CVS and merge them into changesets. CVS source uses
+    its internal changeset merging code by default but can be configured to
+    call the external 'cvsps' program by setting::
+
+      --config convert.cvsps='cvsps -A -u --cvs-direct -q'
+
     This option is deprecated and will be removed in Mercurial 1.4.
 
     The options shown are the defaults.
 
-    Internal cvsps is selected by setting
-        --config convert.cvsps=builtin
+    Internal cvsps is selected by setting ::
+
+      --config convert.cvsps=builtin
+
     and has a few more configurable options:
-        --config convert.cvsps.cache=True     (boolean)
-            Set to False to disable remote log caching, for testing and
-            debugging purposes.
-        --config convert.cvsps.fuzz=60        (integer)
-            Specify the maximum time (in seconds) that is allowed
-            between commits with identical user and log message in a
-            single changeset. When very large files were checked in as
-            part of a changeset then the default may not be long
-            enough.
-        --config convert.cvsps.mergeto='{{mergetobranch ([-\\w]+)}}'
-            Specify a regular expression to which commit log messages
-            are matched. If a match occurs, then the conversion
-            process will insert a dummy revision merging the branch on
-            which this log message occurs to the branch indicated in
-            the regex.
-        --config convert.cvsps.mergefrom='{{mergefrombranch ([-\\w]+)}}'
-            Specify a regular expression to which commit log messages
-            are matched. If a match occurs, then the conversion
-            process will add the most recent revision on the branch
-            indicated in the regex as the second parent of the
-            changeset.
 
-    The hgext/convert/cvsps wrapper script allows the builtin
-    changeset merging code to be run without doing a conversion. Its
-    parameters and output are similar to that of cvsps 2.1.
+    --config convert.cvsps.cache=True         (boolean)
+        Set to False to disable remote log caching, for testing and debugging
+        purposes.
+    --config convert.cvsps.fuzz=60            (integer)
+        Specify the maximum time (in seconds) that is allowed between commits
+        with identical user and log message in a single changeset. When very
+        large files were checked in as part of a changeset then the default
+        may not be long enough.
+    --config convert.cvsps.mergeto='{{mergetobranch ([-\\w]+)}}'
+        Specify a regular expression to which commit log messages are matched.
+        If a match occurs, then the conversion process will insert a dummy
+        revision merging the branch on which this log message occurs to the
+        branch indicated in the regex.
+    --config convert.cvsps.mergefrom='{{mergefrombranch ([-\\w]+)}}'
+        Specify a regular expression to which commit log messages are matched.
+        If a match occurs, then the conversion process will add the most
+        recent revision on the branch indicated in the regex as the second
+        parent of the changeset.
+
+    The hgext/convert/cvsps wrapper script allows the builtin changeset
+    merging code to be run without doing a conversion. Its parameters and
+    output are similar to that of cvsps 2.1.
 
     Subversion Source
     -----------------
 
-    Subversion source detects classical trunk/branches/tags layouts.
-    By default, the supplied "svn://repo/path/" source URL is
-    converted as a single branch. If "svn://repo/path/trunk" exists it
-    replaces the default branch. If "svn://repo/path/branches" exists,
-    its subdirectories are listed as possible branches. If
-    "svn://repo/path/tags" exists, it is looked for tags referencing
-    converted branches. Default "trunk", "branches" and "tags" values
-    can be overridden with following options. Set them to paths
-    relative to the source URL, or leave them blank to disable auto
-    detection.
+    Subversion source detects classical trunk/branches/tags layouts. By
+    default, the supplied "svn://repo/path/" source URL is converted as a
+    single branch. If "svn://repo/path/trunk" exists it replaces the default
+    branch. If "svn://repo/path/branches" exists, its subdirectories are
+    listed as possible branches. If "svn://repo/path/tags" exists, it is
+    looked for tags referencing converted branches. Default "trunk",
+    "branches" and "tags" values can be overridden with following options. Set
+    them to paths relative to the source URL, or leave them blank to disable
+    auto detection.
 
     --config convert.svn.branches=branches    (directory name)
         specify the directory containing branches
@@ -194,9 +195,9 @@
     --config convert.svn.trunk=trunk          (directory name)
         specify the name of the trunk branch
 
-    Source history can be retrieved starting at a specific revision,
-    instead of being integrally converted. Only single branch
-    conversions are supported.
+    Source history can be retrieved starting at a specific revision, instead
+    of being integrally converted. Only single branch conversions are
+    supported.
 
     --config convert.svn.startrev=0           (svn revision number)
         specify start Subversion revision.
@@ -204,20 +205,18 @@
     Perforce Source
     ---------------
 
-    The Perforce (P4) importer can be given a p4 depot path or a
-    client specification as source. It will convert all files in the
-    source to a flat Mercurial repository, ignoring labels, branches
-    and integrations. Note that when a depot path is given you then
-    usually should specify a target directory, because otherwise the
-    target may be named ...-hg.
+    The Perforce (P4) importer can be given a p4 depot path or a client
+    specification as source. It will convert all files in the source to a flat
+    Mercurial repository, ignoring labels, branches and integrations. Note
+    that when a depot path is given you then usually should specify a target
+    directory, because otherwise the target may be named ...-hg.
 
-    It is possible to limit the amount of source history to be
-    converted by specifying an initial Perforce revision.
+    It is possible to limit the amount of source history to be converted by
+    specifying an initial Perforce revision.
 
     --config convert.p4.startrev=0            (perforce changelist number)
         specify initial Perforce revision.
 
-
     Mercurial Destination
     ---------------------
 
@@ -237,14 +236,13 @@
 def debugcvsps(ui, *args, **opts):
     '''create changeset information from CVS
 
-    This command is intended as a debugging tool for the CVS to
-    Mercurial converter, and can be used as a direct replacement for
-    cvsps.
+    This command is intended as a debugging tool for the CVS to Mercurial
+    converter, and can be used as a direct replacement for cvsps.
 
-    Hg debugcvsps reads the CVS rlog for current directory (or any
-    named directory) in the CVS repository, and converts the log to a
-    series of changesets based on matching commit log entries and
-    dates.'''
+    Hg debugcvsps reads the CVS rlog for current directory (or any named
+    directory) in the CVS repository, and converts the log to a series of
+    changesets based on matching commit log entries and dates.
+    '''
     return cvsps.debugcvsps(ui, *args, **opts)
 
 commands.norepo += " convert debugsvnlog debugcvsps"
--- a/hgext/convert/cvs.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/convert/cvs.py	Thu Aug 06 18:48:00 2009 -0700
@@ -38,8 +38,8 @@
         self.lastbranch = {}
         self.parent = {}
         self.socket = None
-        self.cvsroot = file(os.path.join(cvs, "Root")).read()[:-1]
-        self.cvsrepo = file(os.path.join(cvs, "Repository")).read()[:-1]
+        self.cvsroot = open(os.path.join(cvs, "Root")).read()[:-1]
+        self.cvsrepo = open(os.path.join(cvs, "Repository")).read()[:-1]
         self.encoding = locale.getpreferredencoding()
 
         self._connect()
--- a/hgext/convert/cvsps.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/convert/cvsps.py	Thu Aug 06 18:48:00 2009 -0700
@@ -12,13 +12,6 @@
 from mercurial import util
 from mercurial.i18n import _
 
-def listsort(list, key):
-    "helper to sort by key in Python 2.3"
-    try:
-        list.sort(key=key)
-    except TypeError:
-        list.sort(lambda l, r: cmp(key(l), key(r)))
-
 class logentry(object):
     '''Class logentry has the following attributes:
         .author    - author name as CVS knows it
@@ -130,7 +123,7 @@
 
         # Get the real directory in the repository
         try:
-            prefix = file(os.path.join('CVS','Repository')).read().strip()
+            prefix = open(os.path.join('CVS','Repository')).read().strip()
             if prefix == ".":
                 prefix = ""
             directory = prefix
@@ -142,7 +135,7 @@
 
         # Use the Root file in the sandbox, if it exists
         try:
-            root = file(os.path.join('CVS','Root')).read().strip()
+            root = open(os.path.join('CVS','Root')).read().strip()
         except IOError:
             pass
 
@@ -175,7 +168,7 @@
     if cache == 'update':
         try:
             ui.note(_('reading cvs log cache %s\n') % cachefile)
-            oldlog = pickle.load(file(cachefile))
+            oldlog = pickle.load(open(cachefile))
             ui.note(_('cache has %d log entries\n') % len(oldlog))
         except Exception, e:
             ui.note(_('error reading cache: %r\n') % e)
@@ -419,7 +412,7 @@
             if len(log) % 100 == 0:
                 ui.status(util.ellipsis('%d %s' % (len(log), e.file), 80)+'\n')
 
-    listsort(log, key=lambda x:(x.rcs, x.revision))
+    log.sort(key=lambda x: (x.rcs, x.revision))
 
     # find parent revisions of individual files
     versions = {}
@@ -435,7 +428,7 @@
     if cache:
         if log:
             # join up the old and new logs
-            listsort(log, key=lambda x:x.date)
+            log.sort(key=lambda x: x.date)
 
             if oldlog and oldlog[-1].date >= log[0].date:
                 raise logerror('Log cache overlaps with new log entries,'
@@ -445,7 +438,7 @@
 
             # write the new cachefile
             ui.note(_('writing cvs log cache %s\n') % cachefile)
-            pickle.dump(log, file(cachefile, 'w'))
+            pickle.dump(log, open(cachefile, 'w'))
         else:
             log = oldlog
 
@@ -484,7 +477,7 @@
 
     # Merge changesets
 
-    listsort(log, key=lambda x:(x.comment, x.author, x.branch, x.date))
+    log.sort(key=lambda x: (x.comment, x.author, x.branch, x.date))
 
     changesets = []
     files = set()
--- a/hgext/convert/hg.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/convert/hg.py	Thu Aug 06 18:48:00 2009 -0700
@@ -183,7 +183,7 @@
             tagparent = nullid
 
         try:
-            oldlines = sorted(parentctx['.hgtags'].data().splitlines(1))
+            oldlines = sorted(parentctx['.hgtags'].data().splitlines(True))
         except:
             oldlines = []
 
--- a/hgext/convert/p4.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/convert/p4.py	Thu Aug 06 18:48:00 2009 -0700
@@ -92,7 +92,7 @@
 
         # list with depot pathnames, longest first
         vieworder = views.keys()
-        vieworder.sort(key=lambda x: -len(x))
+        vieworder.sort(key=len, reverse=True)
 
         # handle revision limiting
         startrev = self.ui.config('convert', 'p4.startrev', default=0)
--- a/hgext/convert/subversion.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/convert/subversion.py	Thu Aug 06 18:48:00 2009 -0700
@@ -2,7 +2,6 @@
 #
 # Copyright(C) 2007 Daniel Holth et al
 
-import locale
 import os
 import re
 import sys
--- a/hgext/extdiff.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/extdiff.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,14 +7,13 @@
 
 '''command to allow external programs to compare revisions
 
-The `extdiff' Mercurial extension allows you to use external programs
-to compare revisions, or revision with working directory. The external diff
-programs are called with a configurable set of options and two
-non-option arguments: paths to directories containing snapshots of
-files to compare.
+The `extdiff' Mercurial extension allows you to use external programs to
+compare revisions, or revision with working directory. The external diff
+programs are called with a configurable set of options and two non-option
+arguments: paths to directories containing snapshots of files to compare.
 
-The `extdiff' extension also allows to configure new diff commands, so
-you do not need to type "hg extdiff -p kdiff3" always.
+The `extdiff' extension also allows to configure new diff commands, so you do
+not need to type "hg extdiff -p kdiff3" always. ::
 
   [extdiff]
   # add new command that runs GNU diff(1) in 'context diff' mode
@@ -29,16 +28,15 @@
   # add new command called meld, runs meld (no need to name twice)
   meld =
 
-  # add new command called vimdiff, runs gvimdiff with DirDiff plugin
-  # (see http://www.vim.org/scripts/script.php?script_id=102)
-  # Non English user, be sure to put "let g:DirDiffDynamicDiffText = 1" in
-  # your .vimrc
+  # add new command called vimdiff, runs gvimdiff with DirDiff plugin (see
+  # http://www.vim.org/scripts/script.php?script_id=102) Non English user, be
+  # sure to put "let g:DirDiffDynamicDiffText = 1" in your .vimrc
   vimdiff = gvim -f '+next' '+execute "DirDiff" argv(0) argv(1)'
 
-You can use -I/-X and list of file or directory names like normal "hg
-diff" command. The `extdiff' extension makes snapshots of only needed
-files, so running the external diff program will actually be pretty
-fast (at least faster than having to compare the entire tree).
+You can use -I/-X and list of file or directory names like normal "hg diff"
+command. The `extdiff' extension makes snapshots of only needed files, so
+running the external diff program will actually be pretty fast (at least
+faster than having to compare the entire tree).
 '''
 
 from mercurial.i18n import _
@@ -159,20 +157,20 @@
 def extdiff(ui, repo, *pats, **opts):
     '''use external program to diff repository (or selected files)
 
-    Show differences between revisions for the specified files, using
-    an external program. The default program used is diff, with
-    default options "-Npru".
+    Show differences between revisions for the specified files, using an
+    external program. The default program used is diff, with default options
+    "-Npru".
 
-    To select a different program, use the -p/--program option. The
-    program will be passed the names of two directories to compare. To
-    pass additional options to the program, use -o/--option. These
-    will be passed before the names of the directories to compare.
+    To select a different program, use the -p/--program option. The program
+    will be passed the names of two directories to compare. To pass additional
+    options to the program, use -o/--option. These will be passed before the
+    names of the directories to compare.
 
-    When two revision arguments are given, then changes are shown
-    between those revisions. If only one revision is specified then
-    that revision is compared to the working directory, and, when no
-    revisions are specified, the working directory files are compared
-    to its parent.'''
+    When two revision arguments are given, then changes are shown between
+    those revisions. If only one revision is specified then that revision is
+    compared to the working directory, and, when no revisions are specified,
+    the working directory files are compared to its parent.
+    '''
     program = opts['program'] or 'diff'
     if opts['program']:
         option = opts['option']
@@ -211,18 +209,17 @@
             '''use closure to save diff command to use'''
             def mydiff(ui, repo, *pats, **opts):
                 return dodiff(ui, repo, path, diffopts, pats, opts)
-            mydiff.__doc__ = '''use %(path)s to diff repository (or selected files)
+            mydiff.__doc__ = _('''\
+use %(path)s to diff repository (or selected files)
 
-            Show differences between revisions for the specified
-            files, using the %(path)s program.
+    Show differences between revisions for the specified files, using the
+    %(path)s program.
 
-            When two revision arguments are given, then changes are
-            shown between those revisions. If only one revision is
-            specified then that revision is compared to the working
-            directory, and, when no revisions are specified, the
-            working directory files are compared to its parent.''' % {
-                'path': util.uirepr(path),
-                }
+    When two revision arguments are given, then changes are shown between
+    those revisions. If only one revision is specified then that revision is
+    compared to the working directory, and, when no revisions are specified,
+    the working directory files are compared to its parent.\
+''') % dict(path=util.uirepr(path))
             return mydiff
         cmdtable[cmd] = (save(cmd, path, diffopts),
                          cmdtable['extdiff'][1][1:],
--- a/hgext/fetch.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/fetch.py	Thu Aug 06 18:48:00 2009 -0700
@@ -15,18 +15,17 @@
 def fetch(ui, repo, source='default', **opts):
     '''pull changes from a remote repository, merge new changes if needed.
 
-    This finds all changes from the repository at the specified path
-    or URL and adds them to the local repository.
+    This finds all changes from the repository at the specified path or URL
+    and adds them to the local repository.
 
-    If the pulled changes add a new branch head, the head is
-    automatically merged, and the result of the merge is committed.
-    Otherwise, the working directory is updated to include the new
-    changes.
+    If the pulled changes add a new branch head, the head is automatically
+    merged, and the result of the merge is committed. Otherwise, the working
+    directory is updated to include the new changes.
 
     When a merge occurs, the newly pulled changes are assumed to be
-    "authoritative". The head of the new changes is used as the first
-    parent, with local changes as the second. To switch the merge
-    order, use --switch-parent.
+    "authoritative". The head of the new changes is used as the first parent,
+    with local changes as the second. To switch the merge order, use
+    --switch-parent.
 
     See 'hg help dates' for a list of formats valid for -d/--date.
     '''
--- a/hgext/graphlog.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/graphlog.py	Thu Aug 06 18:48:00 2009 -0700
@@ -8,8 +8,8 @@
 '''command to view revision graphs from a shell
 
 This extension adds a --graph option to the incoming, outgoing and log
-commands. When this options is given, an ASCII representation of the
-revision graph is also shown.
+commands. When this options is given, an ASCII representation of the revision
+graph is also shown.
 '''
 
 import os, sys
@@ -95,7 +95,7 @@
         else:
             nodeline[2 * end] = "+"
             if start > end:
-                (start, end) = (end,start)
+                (start, end) = (end, start)
             for i in range(2 * start + 1, 2 * end):
                 if nodeline[i] != "+":
                     nodeline[i] = "-"
@@ -238,11 +238,10 @@
 def graphlog(ui, repo, path=None, **opts):
     """show revision history alongside an ASCII revision graph
 
-    Print a revision history alongside a revision graph drawn with
-    ASCII characters.
+    Print a revision history alongside a revision graph drawn with ASCII
+    characters.
 
-    Nodes printed as an @ character are parents of the working
-    directory.
+    Nodes printed as an @ character are parents of the working directory.
     """
 
     check_unsupported_flags(opts)
@@ -300,11 +299,10 @@
 def gincoming(ui, repo, source="default", **opts):
     """show the incoming changesets alongside an ASCII revision graph
 
-    Print the incoming changesets alongside a revision graph drawn with
-    ASCII characters.
+    Print the incoming changesets alongside a revision graph drawn with ASCII
+    characters.
 
-    Nodes printed as an @ character are parents of the working
-    directory.
+    Nodes printed as an @ character are parents of the working directory.
     """
 
     check_unsupported_flags(opts)
--- a/hgext/hgcia.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/hgcia.py	Thu Aug 06 18:48:00 2009 -0700
@@ -3,38 +3,38 @@
 
 """hooks for integrating with the CIA.vc notification service
 
-This is meant to be run as a changegroup or incoming hook.
-To configure it, set the following options in your hgrc:
+This is meant to be run as a changegroup or incoming hook. To configure it,
+set the following options in your hgrc::
 
-[cia]
-# your registered CIA user name
-user = foo
-# the name of the project in CIA
-project = foo
-# the module (subproject) (optional)
-#module = foo
-# Append a diffstat to the log message (optional)
-#diffstat = False
-# Template to use for log messages (optional)
-#template = {desc}\\n{baseurl}/rev/{node}-- {diffstat}
-# Style to use (optional)
-#style = foo
-# The URL of the CIA notification service (optional)
-# You can use mailto: URLs to send by email, eg
-# mailto:cia@cia.vc
-# Make sure to set email.from if you do this.
-#url = http://cia.vc/
-# print message instead of sending it (optional)
-#test = False
+  [cia]
+  # your registered CIA user name
+  user = foo
+  # the name of the project in CIA
+  project = foo
+  # the module (subproject) (optional)
+  #module = foo
+  # Append a diffstat to the log message (optional)
+  #diffstat = False
+  # Template to use for log messages (optional)
+  #template = {desc}\\n{baseurl}/rev/{node}-- {diffstat}
+  # Style to use (optional)
+  #style = foo
+  # The URL of the CIA notification service (optional)
+  # You can use mailto: URLs to send by email, eg
+  # mailto:cia@cia.vc
+  # Make sure to set email.from if you do this.
+  #url = http://cia.vc/
+  # print message instead of sending it (optional)
+  #test = False
 
-[hooks]
-# one of these:
-changegroup.cia = python:hgcia.hook
-#incoming.cia = python:hgcia.hook
+  [hooks]
+  # one of these:
+  changegroup.cia = python:hgcia.hook
+  #incoming.cia = python:hgcia.hook
 
-[web]
-# If you want hyperlinks (optional)
-baseurl = http://server/path/to/repo
+  [web]
+  # If you want hyperlinks (optional)
+  baseurl = http://server/path/to/repo
 """
 
 from mercurial.i18n import _
@@ -205,7 +205,7 @@
         msg['From'] = self.emailfrom
         msg['Subject'] = 'DeliverXML'
         msg['Content-type'] = 'text/xml'
-        msgtext = msg.as_string(0)
+        msgtext = msg.as_string()
 
         self.ui.status(_('hgcia: sending update to %s\n') % address)
         mail.sendmail(self.ui, util.email(self.emailfrom),
--- a/hgext/hgk.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/hgk.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,31 +7,31 @@
 
 '''browse the repository in a graphical way
 
-The hgk extension allows browsing the history of a repository in a
-graphical way. It requires Tcl/Tk version 8.4 or later. (Tcl/Tk is not
-distributed with Mercurial.)
+The hgk extension allows browsing the history of a repository in a graphical
+way. It requires Tcl/Tk version 8.4 or later. (Tcl/Tk is not distributed with
+Mercurial.)
 
-hgk consists of two parts: a Tcl script that does the displaying and
-querying of information, and an extension to Mercurial named hgk.py,
-which provides hooks for hgk to get information. hgk can be found in
-the contrib directory, and the extension is shipped in the hgext
-repository, and needs to be enabled.
+hgk consists of two parts: a Tcl script that does the displaying and querying
+of information, and an extension to Mercurial named hgk.py, which provides
+hooks for hgk to get information. hgk can be found in the contrib directory,
+and the extension is shipped in the hgext repository, and needs to be enabled.
 
-The hg view command will launch the hgk Tcl script. For this command
-to work, hgk must be in your search path. Alternately, you can specify
-the path to hgk in your .hgrc file:
+The hg view command will launch the hgk Tcl script. For this command to work,
+hgk must be in your search path. Alternately, you can specify the path to hgk
+in your .hgrc file::
 
   [hgk]
   path=/location/of/hgk
 
-hgk can make use of the extdiff extension to visualize revisions.
-Assuming you had already configured extdiff vdiff command, just add:
+hgk can make use of the extdiff extension to visualize revisions. Assuming you
+had already configured extdiff vdiff command, just add::
 
   [hgk]
   vdiff=vdiff
 
-Revisions context menu will now display additional entries to fire
-vdiff on hovered and selected revisions.'''
+Revisions context menu will now display additional entries to fire vdiff on
+hovered and selected revisions.
+'''
 
 import os
 from mercurial import commands, util, patch, revlog, cmdutil
--- a/hgext/highlight/__init__.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/highlight/__init__.py	Thu Aug 06 18:48:00 2009 -0700
@@ -10,13 +10,12 @@
 
 """syntax highlighting for hgweb (requires Pygments)
 
-It depends on the Pygments syntax highlighting library:
-http://pygments.org/
+It depends on the Pygments syntax highlighting library: http://pygments.org/
 
-There is a single configuration option:
+There is a single configuration option::
 
-[web]
-pygments_style = <style>
+  [web]
+  pygments_style = <style>
 
 The default is 'colorful'.
 """
--- a/hgext/inotify/server.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/inotify/server.py	Thu Aug 06 18:48:00 2009 -0700
@@ -89,7 +89,11 @@
             yield fullpath, dirs, files
 
         except OSError, err:
-            if err.errno not in walk_ignored_errors:
+            if err.errno == errno.ENOTDIR:
+                # fullpath was a directory, but has since been replaced
+                # by a file.
+                yield fullpath, dirs, files
+            elif err.errno not in walk_ignored_errors:
                 raise
 
     return walkit(root, root == '')
@@ -201,6 +205,92 @@
         return wrapper
     return decorator
 
+class directory(object):
+    """
+    Representing a directory
+
+    * path is the relative path from repo root to this directory
+    * files is a dict listing the files in this directory
+        - keys are file names
+        - values are file status
+    * dirs is a dict listing the subdirectories
+        - key are subdirectories names
+        - values are directory objects
+    """
+    def __init__(self, relpath=''):
+        self.path = relpath
+        self.files = {}
+        self.dirs = {}
+
+    def dir(self, relpath):
+        """
+        Returns the directory contained at the relative path relpath.
+        Creates the intermediate directories if necessary.
+        """
+        if not relpath:
+            return self
+        l = relpath.split('/')
+        ret = self
+        while l:
+            next = l.pop(0)
+            try:
+                ret = ret.dirs[next]
+            except KeyError:
+                d = directory(join(ret.path, next))
+                ret.dirs[next] = d
+                ret = d
+        return ret
+
+    def walk(self, states):
+        """
+        yield (filename, status) pairs for items in the trees
+        that have status in states.
+        filenames are relative to the repo root
+        """
+        for file, st in self.files.iteritems():
+            if st in states:
+                yield join(self.path, file), st
+        for dir in self.dirs.itervalues():
+            for e in dir.walk(states):
+                yield e
+
+    def lookup(self, states, path):
+        """
+        yield root-relative filenames that match path, and whose
+        status are in states:
+        * if path is a file, yield path
+        * if path is a directory, yield directory files
+        * if path is not tracked, yield nothing
+        """
+        if path[-1] == '/':
+            path = path[:-1]
+
+        paths = path.split('/')
+
+        # we need to check separately for last node
+        last = paths.pop()
+
+        tree = self
+        try:
+            for dir in paths:
+                tree = tree.dirs[dir]
+        except KeyError:
+            # path is not tracked
+            return
+
+        try:
+            # if path is a directory, walk it
+            for file, st in tree.dirs[last].walk(states):
+                yield file
+        except KeyError:
+            try:
+                if tree.files[last] in states:
+                    # path is a file
+                    yield path
+            except KeyError:
+                # path is not tracked
+                pass
+
 class repowatcher(pollable):
     """
     Watches inotify events
@@ -231,9 +321,9 @@
         self.threshold = watcher.threshold(self.watcher)
         self.fileno = self.watcher.fileno
 
-        self.tree = {}
+        self.tree = directory()
         self.statcache = {}
-        self.statustrees = dict([(s, {}) for s in self.statuskeys])
+        self.statustrees = dict([(s, directory()) for s in self.statuskeys])
 
         self.last_event = None
 
@@ -288,23 +378,6 @@
         self.add_watch(self.repo.path, inotify.IN_DELETE)
         self.check_dirstate()
 
-    def dir(self, tree, path):
-        if path:
-            for name in path.split('/'):
-                tree = tree.setdefault(name, {})
-        return tree
-
-    def lookup(self, path, tree):
-        if path:
-            try:
-                for name in path.split('/'):
-                    tree = tree[name]
-            except KeyError:
-                return 'x'
-            except TypeError:
-                return 'd'
-        return tree
-
     def filestatus(self, fn, st):
         try:
             type_, mode, size, time = self.repo.dirstate._map[fn][:4]
@@ -350,53 +423,47 @@
 
     def _updatestatus(self, wfn, newstatus):
         '''
-        Update the stored status of a file or directory.
+        Update the stored status of a file.
 
         newstatus: - char in (statuskeys + 'ni'), new status to apply.
                    - or None, to stop tracking wfn
         '''
         root, fn = split(wfn)
-        d = self.dir(self.tree, root)
+        d = self.tree.dir(root)
 
-        oldstatus = d.get(fn)
+        oldstatus = d.files.get(fn)
         # oldstatus can be either:
         # - None : fn is new
         # - a char in statuskeys: fn is a (tracked) file
-        # - a dict: fn is a directory
-        isdir = isinstance(oldstatus, dict)
 
         if self.ui.debugflag and oldstatus != newstatus:
-            if isdir:
-                self.ui.note(_('status: %r dir(%d) -> %s\n') %
-                             (wfn, len(oldstatus), newstatus))
-            else:
-                self.ui.note(_('status: %r %s -> %s\n') %
+            self.ui.note(_('status: %r %s -> %s\n') %
                              (wfn, oldstatus, newstatus))
-        if not isdir:
-            if oldstatus and oldstatus in self.statuskeys \
-                and oldstatus != newstatus:
-                del self.dir(self.statustrees[oldstatus], root)[fn]
-            if newstatus and newstatus != 'i':
-                d[fn] = newstatus
-                if newstatus in self.statuskeys:
-                    dd = self.dir(self.statustrees[newstatus], root)
-                    if oldstatus != newstatus or fn not in dd:
-                        dd[fn] = newstatus
-            else:
-                d.pop(fn, None)
+
+        if oldstatus and oldstatus in self.statuskeys \
+            and oldstatus != newstatus:
+            del self.statustrees[oldstatus].dir(root).files[fn]
+        if newstatus and newstatus != 'i':
+            d.files[fn] = newstatus
+            if newstatus in self.statuskeys:
+                dd = self.statustrees[newstatus].dir(root)
+                if oldstatus != newstatus or fn not in dd.files:
+                    dd.files[fn] = newstatus
+        else:
+            d.files.pop(fn, None)
 
 
     def check_deleted(self, key):
         # Files that had been deleted but were present in the dirstate
         # may have vanished from the dirstate; we must clean them up.
         nuke = []
-        for wfn, ignore in self.walk(key, self.statustrees[key]):
+        for wfn, ignore in self.statustrees[key].walk(key):
             if wfn not in self.repo.dirstate:
                 nuke.append(wfn)
         for wfn in nuke:
             root, fn = split(wfn)
-            del self.dir(self.statustrees[key], root)[fn]
-            del self.dir(self.tree, root)[fn]
+            del self.statustrees[key].dir(root).files[fn]
+            del self.tree.dir(root).files[fn]
 
     def scan(self, topdir=''):
         ds = self.repo.dirstate._map.copy()
@@ -438,18 +505,6 @@
         self.scan()
         self.ui.note(_('%s end dirstate reload\n') % self.event_time())
 
-    def walk(self, states, tree, prefix=''):
-        # This is the "inner loop" when talking to the client.
-
-        for name, val in tree.iteritems():
-            path = join(prefix, name)
-            try:
-                if val in states:
-                    yield path, val
-            except TypeError:
-                for p in self.walk(states, val, path):
-                    yield p
-
     def update_hgignore(self):
         # An update of the ignore file can potentially change the
         # states of all unknown and ignored files.
@@ -537,9 +592,10 @@
                          (self.event_time(), wpath))
 
         if evt.mask & inotify.IN_ISDIR:
-            tree = self.dir(self.tree, wpath).copy()
-            for wfn, ignore in self.walk('?', tree):
-                self.deletefile(join(wpath, wfn), '?')
+            tree = self.tree.dir(wpath)
+            todelete = [wfn for wfn, ignore in tree.walk('?')]
+            for fn in todelete:
+                self.deletefile(fn, '?')
             self.scan(wpath)
         else:
             self.deleted(wpath)
@@ -580,6 +636,12 @@
             assert evt.fullpath.startswith(self.wprefix)
             wpath = evt.fullpath[len(self.wprefix):]
 
+            # paths have been normalized, wpath never ends with a '/'
+
+            if wpath.startswith('.hg/') and evt.mask & inotify.IN_ISDIR:
+                # ignore subdirectories of .hg/ (merge, patches...)
+                continue
+
             if evt.mask & inotify.IN_UNMOUNT:
                 self.process_unmount(wpath, evt)
             elif evt.mask & (inotify.IN_MODIFY | inotify.IN_ATTRIB):
@@ -669,18 +731,13 @@
 
         if not names:
             def genresult(states, tree):
-                for fn, state in self.repowatcher.walk(states, tree):
+                for fn, state in tree.walk(states):
                     yield fn
         else:
             def genresult(states, tree):
                 for fn in names:
-                    l = self.repowatcher.lookup(fn, tree)
-                    try:
-                        if l in states:
-                            yield fn
-                    except TypeError:
-                        for f, s in self.repowatcher.walk(states, l, fn):
-                            yield f
+                    for f in tree.lookup(states, fn):
+                        yield f
 
         return ['\0'.join(r) for r in [
             genresult('l', self.repowatcher.statustrees['l']),
--- a/hgext/interhg.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/interhg.py	Thu Aug 06 18:48:00 2009 -0700
@@ -10,12 +10,12 @@
 
 '''expand expressions into changelog and summaries
 
-This extension allows the use of a special syntax in summaries,
-which will be automatically expanded into links or any other
-arbitrary expression, much like InterWiki does.
+This extension allows the use of a special syntax in summaries, which will be
+automatically expanded into links or any other arbitrary expression, much like
+InterWiki does.
 
-A few example patterns (link to bug tracking, etc.) that may
-be used in your hgrc:
+A few example patterns (link to bug tracking, etc.) that may be used in your
+hgrc::
 
   [interhg]
   issues = s!issue(\\d+)!<a href="http://bts/issue\\1">issue\\1</a>!
--- a/hgext/keyword.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/keyword.py	Thu Aug 06 18:48:00 2009 -0700
@@ -28,57 +28,56 @@
 
 '''expand keywords in tracked files
 
-This extension expands RCS/CVS-like or self-customized $Keywords$ in
-tracked text files selected by your configuration.
+This extension expands RCS/CVS-like or self-customized $Keywords$ in tracked
+text files selected by your configuration.
 
-Keywords are only expanded in local repositories and not stored in the
-change history. The mechanism can be regarded as a convenience for the
-current user or for archive distribution.
+Keywords are only expanded in local repositories and not stored in the change
+history. The mechanism can be regarded as a convenience for the current user
+or for archive distribution.
 
-Configuration is done in the [keyword] and [keywordmaps] sections of
-hgrc files.
+Configuration is done in the [keyword] and [keywordmaps] sections of hgrc
+files.
 
-Example:
+Example::
 
     [keyword]
     # expand keywords in every python file except those matching "x*"
     **.py =
     x*    = ignore
 
-Note: the more specific you are in your filename patterns
-      the less you lose speed in huge repositories.
+NOTE: the more specific you are in your filename patterns the less you lose
+speed in huge repositories.
 
-For [keywordmaps] template mapping and expansion demonstration and
-control run "hg kwdemo".
+For [keywordmaps] template mapping and expansion demonstration and control run
+"hg kwdemo".
 
 An additional date template filter {date|utcdate} is provided.
 
-The default template mappings (view with "hg kwdemo -d") can be
-replaced with customized keywords and templates. Again, run "hg
-kwdemo" to control the results of your config changes.
+The default template mappings (view with "hg kwdemo -d") can be replaced with
+customized keywords and templates. Again, run "hg kwdemo" to control the
+results of your config changes.
 
-Before changing/disabling active keywords, run "hg kwshrink" to avoid
-the risk of inadvertently storing expanded keywords in the change
-history.
+Before changing/disabling active keywords, run "hg kwshrink" to avoid the risk
+of inadvertently storing expanded keywords in the change history.
 
-To force expansion after enabling it, or a configuration change, run
-"hg kwexpand".
+To force expansion after enabling it, or a configuration change, run "hg
+kwexpand".
 
-Also, when committing with the record extension or using mq's qrecord,
-be aware that keywords cannot be updated. Again, run "hg kwexpand" on
-the files in question to update keyword expansions after all changes
-have been checked in.
+Also, when committing with the record extension or using mq's qrecord, be
+aware that keywords cannot be updated. Again, run "hg kwexpand" on the files
+in question to update keyword expansions after all changes have been checked
+in.
 
-Expansions spanning more than one line and incremental expansions,
-like CVS' $Log$, are not supported. A keyword template map
-"Log = {desc}" expands to the first line of the changeset description.
+Expansions spanning more than one line and incremental expansions, like CVS'
+$Log$, are not supported. A keyword template map "Log = {desc}" expands to the
+first line of the changeset description.
 '''
 
 from mercurial import commands, cmdutil, dispatch, filelog, revlog, extensions
 from mercurial import patch, localrepo, templater, templatefilters, util, match
 from mercurial.hgweb import webcommands
 from mercurial.lock import release
-from mercurial.node import nullid, hex
+from mercurial.node import nullid
 from mercurial.i18n import _
 import re, shutil, tempfile, time
 
@@ -125,9 +124,8 @@
 
         kwmaps = self.ui.configitems('keywordmaps')
         if kwmaps: # override default templates
-            kwmaps = [(k, templater.parsestring(v, False))
-                      for (k, v) in kwmaps]
-            self.templates = dict(kwmaps)
+            self.templates = dict((k, templater.parsestring(v, False))
+                                  for k, v in kwmaps)
         escaped = map(re.escape, self.templates.keys())
         kwpat = r'\$(%s)(: [^$\n\r]*? )??\$' % '|'.join(escaped)
         self.re_kw = re.compile(kwpat)
@@ -362,24 +360,24 @@
 def files(ui, repo, *pats, **opts):
     '''show files configured for keyword expansion
 
-    List which files in the working directory are matched by the
-    [keyword] configuration patterns.
+    List which files in the working directory are matched by the [keyword]
+    configuration patterns.
 
-    Useful to prevent inadvertent keyword expansion and to speed up
-    execution by including only files that are actual candidates
-    for expansion.
+    Useful to prevent inadvertent keyword expansion and to speed up execution
+    by including only files that are actual candidates for expansion.
 
-    See "hg help keyword" on how to construct patterns both for
-    inclusion and exclusion of files.
+    See "hg help keyword" on how to construct patterns both for inclusion and
+    exclusion of files.
 
     Use -u/--untracked to list untracked files as well.
 
-    With -a/--all and -v/--verbose the codes used to show the status
-    of files are:
-    K = keyword expansion candidate
-    k = keyword expansion candidate (untracked)
-    I = ignored
-    i = ignored (untracked)
+    With -a/--all and -v/--verbose the codes used to show the status of files
+    are::
+
+      K = keyword expansion candidate
+      k = keyword expansion candidate (untracked)
+      I = ignored
+      i = ignored (untracked)
     '''
     kwt = kwtools['templater']
     status = _status(ui, repo, kwt, opts.get('untracked'), *pats, **opts)
@@ -496,7 +494,8 @@
                 release(lock, wlock)
 
     # monkeypatches
-    def kwpatchfile_init(orig, self, ui, fname, opener, missing=False, eol=None):
+    def kwpatchfile_init(orig, self, ui, fname, opener,
+                         missing=False, eol=None):
         '''Monkeypatch/wrap patch.patchfile.__init__ to avoid
         rejects or conflicts due to expanded keywords in working dir.'''
         orig(self, ui, fname, opener, missing, eol)
--- a/hgext/mq.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/mq.py	Thu Aug 06 18:48:00 2009 -0700
@@ -8,25 +8,25 @@
 '''manage a stack of patches
 
 This extension lets you work with a stack of patches in a Mercurial
-repository. It manages two stacks of patches - all known patches, and
-applied patches (subset of known patches).
+repository. It manages two stacks of patches - all known patches, and applied
+patches (subset of known patches).
 
-Known patches are represented as patch files in the .hg/patches
-directory. Applied patches are both patch files and changesets.
+Known patches are represented as patch files in the .hg/patches directory.
+Applied patches are both patch files and changesets.
 
-Common tasks (use "hg help command" for more details):
+Common tasks (use "hg help command" for more details)::
 
-prepare repository to work with patches   qinit
-create new patch                          qnew
-import existing patch                     qimport
+  prepare repository to work with patches   qinit
+  create new patch                          qnew
+  import existing patch                     qimport
 
-print patch series                        qseries
-print applied patches                     qapplied
-print name of top applied patch           qtop
+  print patch series                        qseries
+  print applied patches                     qapplied
+  print name of top applied patch           qtop
 
-add known patch to applied stack          qpush
-remove patch from applied stack           qpop
-refresh contents of top applied patch     qrefresh
+  add known patch to applied stack          qpush
+  remove patch from applied stack           qpop
+  refresh contents of top applied patch     qrefresh
 '''
 
 from mercurial.i18n import _
@@ -556,7 +556,7 @@
             if not pushable:
                 self.explain_pushable(patchname, all_patches=True)
                 continue
-            self.ui.warn(_("applying %s\n") % patchname)
+            self.ui.status(_("applying %s\n") % patchname)
             pf = os.path.join(patchdir, patchname)
 
             try:
@@ -1081,6 +1081,8 @@
                     except: pass
                     repo.dirstate.forget(f)
                 repo.dirstate.setparents(qp, nullid)
+            for patch in reversed(self.applied[start:end]):
+                self.ui.status(_("popping %s\n") % patch.name)
             del self.applied[start:end]
             self.strip(repo, rev, update=False, backup='strip')
             if len(self.applied):
@@ -1344,19 +1346,24 @@
 
     def qseries(self, repo, missing=None, start=0, length=None, status=None,
                 summary=False):
-        def displayname(patchname):
+        def displayname(pfx, patchname):
             if summary:
                 ph = patchheader(self.join(patchname))
                 msg = ph.message
                 msg = msg and ': ' + msg[0] or ': '
             else:
                 msg = ''
-            return '%s%s' % (patchname, msg)
+            msg = "%s%s%s" % (pfx, patchname, msg)
+            if self.ui.interactive():
+                msg = util.ellipsis(msg, util.termwidth())
+            self.ui.write(msg + '\n')
 
         applied = set([p.name for p in self.applied])
         if length is None:
             length = len(self.series) - start
         if not missing:
+            if self.ui.verbose:
+                idxwidth = len(str(start+length - 1))
             for i in xrange(start, start+length):
                 patch = self.series[i]
                 if patch in applied:
@@ -1367,10 +1374,10 @@
                     stat = 'G'
                 pfx = ''
                 if self.ui.verbose:
-                    pfx = '%d %s ' % (i, stat)
+                    pfx = '%*d %s ' % (idxwidth, i, stat)
                 elif status and status != stat:
                     continue
-                self.ui.write('%s%s\n' % (pfx, displayname(patch)))
+                displayname(pfx, patch)
         else:
             msng_list = []
             for root, dirs, files in os.walk(self.path):
@@ -1384,7 +1391,7 @@
                         msng_list.append(fl)
             for x in sorted(msng_list):
                 pfx = self.ui.verbose and ('D ') or ''
-                self.ui.write("%s%s\n" % (pfx, displayname(x)))
+                displayname(pfx, x)
 
     def issaveline(self, l):
         if l.name == '.hg.patches.save.line':
@@ -1537,7 +1544,7 @@
                 raise util.Abort(_('option "-r" not valid when importing '
                                    'files'))
             rev = cmdutil.revrange(repo, rev)
-            rev.sort(lambda x, y: cmp(y, x))
+            rev.sort(reverse=True)
         if (len(files) > 1 or len(rev) > 1) and patchname:
             raise util.Abort(_('option "-n" not valid when importing multiple '
                                'patches'))
@@ -1677,29 +1684,26 @@
 def qimport(ui, repo, *filename, **opts):
     """import a patch
 
-    The patch is inserted into the series after the last applied
-    patch. If no patches have been applied, qimport prepends the patch
-    to the series.
+    The patch is inserted into the series after the last applied patch. If no
+    patches have been applied, qimport prepends the patch to the series.
 
-    The patch will have the same name as its source file unless you
-    give it a new one with -n/--name.
+    The patch will have the same name as its source file unless you give it a
+    new one with -n/--name.
 
-    You can register an existing patch inside the patch directory with
-    the -e/--existing flag.
+    You can register an existing patch inside the patch directory with the
+    -e/--existing flag.
 
-    With -f/--force, an existing patch of the same name will be
-    overwritten.
+    With -f/--force, an existing patch of the same name will be overwritten.
 
-    An existing changeset may be placed under mq control with -r/--rev
-    (e.g. qimport --rev tip -n patch will place tip under mq control).
-    With -g/--git, patches imported with --rev will use the git diff
-    format. See the diffs help topic for information on why this is
-    important for preserving rename/copy information and permission
-    changes.
+    An existing changeset may be placed under mq control with -r/--rev (e.g.
+    qimport --rev tip -n patch will place tip under mq control). With
+    -g/--git, patches imported with --rev will use the git diff format. See
+    the diffs help topic for information on why this is important for
+    preserving rename/copy information and permission changes.
 
-    To import a patch from standard input, pass - as the patch file.
-    When importing from standard input, a patch name must be specified
-    using the --name flag.
+    To import a patch from standard input, pass - as the patch file. When
+    importing from standard input, a patch name must be specified using the
+    --name flag.
     """
     q = repo.mq
     q.qimport(repo, filename, patchname=opts['name'],
@@ -1714,11 +1718,12 @@
 def init(ui, repo, **opts):
     """init a new queue repository
 
-    The queue repository is unversioned by default. If
-    -c/--create-repo is specified, qinit will create a separate nested
-    repository for patches (qinit -c may also be run later to convert
-    an unversioned patch repository into a versioned one). You can use
-    qcommit to commit changes to this queue repository."""
+    The queue repository is unversioned by default. If -c/--create-repo is
+    specified, qinit will create a separate nested repository for patches
+    (qinit -c may also be run later to convert an unversioned patch repository
+    into a versioned one). You can use qcommit to commit changes to this queue
+    repository.
+    """
     q = repo.mq
     r = q.init(repo, create=opts['create_repo'])
     q.save_dirty()
@@ -1740,17 +1745,16 @@
 def clone(ui, source, dest=None, **opts):
     '''clone main and patch repository at same time
 
-    If source is local, destination will have no patches applied. If
-    source is remote, this command can not check if patches are
-    applied in source, so cannot guarantee that patches are not
-    applied in destination. If you clone remote repository, be sure
-    before that it has no patches applied.
+    If source is local, destination will have no patches applied. If source is
+    remote, this command can not check if patches are applied in source, so
+    cannot guarantee that patches are not applied in destination. If you clone
+    remote repository, be sure before that it has no patches applied.
 
-    Source patch repository is looked for in <src>/.hg/patches by
-    default. Use -p <url> to change.
+    Source patch repository is looked for in <src>/.hg/patches by default. Use
+    -p <url> to change.
 
-    The patch directory must be a nested Mercurial repository, as
-    would be created by qinit -c.
+    The patch directory must be a nested Mercurial repository, as would be
+    created by qinit -c.
     '''
     def patchdir(repo):
         url = repo.url()
@@ -1847,7 +1851,7 @@
                      summary=opts.get('summary'))
 
 def setupheaderopts(ui, opts):
-    def do(opt,val):
+    def do(opt, val):
         if not opts[opt] and opts['current' + opt]:
             opts[opt] = val
     do('user', ui.username())
@@ -1856,26 +1860,24 @@
 def new(ui, repo, patch, *args, **opts):
     """create a new patch
 
-    qnew creates a new patch on top of the currently-applied patch (if
-    any). It will refuse to run if there are any outstanding changes
-    unless -f/--force is specified, in which case the patch will be
-    initialized with them. You may also use -I/--include,
-    -X/--exclude, and/or a list of files after the patch name to add
-    only changes to matching files to the new patch, leaving the rest
-    as uncommitted modifications.
+    qnew creates a new patch on top of the currently-applied patch (if any).
+    It will refuse to run if there are any outstanding changes unless
+    -f/--force is specified, in which case the patch will be initialized with
+    them. You may also use -I/--include, -X/--exclude, and/or a list of files
+    after the patch name to add only changes to matching files to the new
+    patch, leaving the rest as uncommitted modifications.
 
-    -u/--user and -d/--date can be used to set the (given) user and
-    date, respectively. -U/--currentuser and -D/--currentdate set user
-    to current user and date to current date.
+    -u/--user and -d/--date can be used to set the (given) user and date,
+    respectively. -U/--currentuser and -D/--currentdate set user to current
+    user and date to current date.
 
-    -e/--edit, -m/--message or -l/--logfile set the patch header as
-    well as the commit message. If none is specified, the header is
-    empty and the commit message is '[mq]: PATCH'.
+    -e/--edit, -m/--message or -l/--logfile set the patch header as well as
+    the commit message. If none is specified, the header is empty and the
+    commit message is '[mq]: PATCH'.
 
-    Use the -g/--git option to keep the patch in the git extended diff
-    format. Read the diffs help topic for more information on why this
-    is important for preserving permission changes and copy/rename
-    information.
+    Use the -g/--git option to keep the patch in the git extended diff format.
+    Read the diffs help topic for more information on why this is important
+    for preserving permission changes and copy/rename information.
     """
     msg = cmdutil.logmessage(opts)
     def getmsg(): return ui.edit(msg, ui.username())
@@ -1893,17 +1895,16 @@
 def refresh(ui, repo, *pats, **opts):
     """update the current patch
 
-    If any file patterns are provided, the refreshed patch will
-    contain only the modifications that match those patterns; the
-    remaining modifications will remain in the working directory.
+    If any file patterns are provided, the refreshed patch will contain only
+    the modifications that match those patterns; the remaining modifications
+    will remain in the working directory.
 
-    If -s/--short is specified, files currently included in the patch
-    will be refreshed just like matched files and remain in the patch.
+    If -s/--short is specified, files currently included in the patch will be
+    refreshed just like matched files and remain in the patch.
 
-    hg add/remove/copy/rename work as usual, though you might want to
-    use git-style patches (-g/--git or [diff] git=1) to track copies
-    and renames. See the diffs help topic for more information on the
-    git diff format.
+    hg add/remove/copy/rename work as usual, though you might want to use
+    git-style patches (-g/--git or [diff] git=1) to track copies and renames.
+    See the diffs help topic for more information on the git diff format.
     """
     q = repo.mq
     message = cmdutil.logmessage(opts)
@@ -1924,15 +1925,13 @@
 def diff(ui, repo, *pats, **opts):
     """diff of the current patch and subsequent modifications
 
-    Shows a diff which includes the current patch as well as any
-    changes which have been made in the working directory since the
-    last refresh (thus showing what the current patch would become
-    after a qrefresh).
+    Shows a diff which includes the current patch as well as any changes which
+    have been made in the working directory since the last refresh (thus
+    showing what the current patch would become after a qrefresh).
 
-    Use 'hg diff' if you only want to see the changes made since the
-    last qrefresh, or 'hg export qtip' if you want to see changes made
-    by the current patch without including changes made since the
-    qrefresh.
+    Use 'hg diff' if you only want to see the changes made since the last
+    qrefresh, or 'hg export qtip' if you want to see changes made by the
+    current patch without including changes made since the qrefresh.
     """
     repo.mq.diff(repo, pats, opts)
     return 0
@@ -1940,15 +1939,15 @@
 def fold(ui, repo, *files, **opts):
     """fold the named patches into the current patch
 
-    Patches must not yet be applied. Each patch will be successively
-    applied to the current patch in the order given. If all the
-    patches apply successfully, the current patch will be refreshed
-    with the new cumulative patch, and the folded patches will be
-    deleted. With -k/--keep, the folded patch files will not be
-    removed afterwards.
+    Patches must not yet be applied. Each patch will be successively applied
+    to the current patch in the order given. If all the patches apply
+    successfully, the current patch will be refreshed with the new cumulative
+    patch, and the folded patches will be deleted. With -k/--keep, the folded
+    patch files will not be removed afterwards.
 
-    The header for each folded patch will be concatenated with the
-    current patch header, separated by a line of '* * *'."""
+    The header for each folded patch will be concatenated with the current
+    patch header, separated by a line of '* * *'.
+    """
 
     q = repo.mq
 
@@ -2014,14 +2013,13 @@
 def guard(ui, repo, *args, **opts):
     '''set or print guards for a patch
 
-    Guards control whether a patch can be pushed. A patch with no
-    guards is always pushed. A patch with a positive guard ("+foo") is
-    pushed only if the qselect command has activated it. A patch with
-    a negative guard ("-foo") is never pushed if the qselect command
-    has activated it.
+    Guards control whether a patch can be pushed. A patch with no guards is
+    always pushed. A patch with a positive guard ("+foo") is pushed only if
+    the qselect command has activated it. A patch with a negative guard
+    ("-foo") is never pushed if the qselect command has activated it.
 
-    With no arguments, print the currently active guards.
-    With arguments, set guards for the named patch.
+    With no arguments, print the currently active guards. With arguments, set
+    guards for the named patch.
     NOTE: Specifying negative guards now requires '--'.
 
     To set guards on another patch:
@@ -2098,8 +2096,8 @@
 def push(ui, repo, patch=None, **opts):
     """push the next patch onto the stack
 
-    When -f/--force is applied, all local changes in patched files
-    will be lost.
+    When -f/--force is applied, all local changes in patched files will be
+    lost.
     """
     q = repo.mq
     mergeq = None
@@ -2121,9 +2119,9 @@
 def pop(ui, repo, patch=None, **opts):
     """pop the current patch off the stack
 
-    By default, pops off the top of the patch stack. If given a patch
-    name, keeps popping off patches until the named patch is at the
-    top of the stack.
+    By default, pops off the top of the patch stack. If given a patch name,
+    keeps popping off patches until the named patch is at the top of the
+    stack.
     """
     localupdate = True
     if opts['name']:
@@ -2240,8 +2238,7 @@
     """strip a revision and all its descendants from the repository
 
     If one of the working directory's parent revisions is stripped, the
-    working directory will be updated to the parent of the stripped
-    revision.
+    working directory will be updated to the parent of the stripped revision.
     """
     backup = 'all'
     if opts['backup']:
@@ -2266,35 +2263,33 @@
 def select(ui, repo, *args, **opts):
     '''set or print guarded patches to push
 
-    Use the qguard command to set or print guards on patch, then use
-    qselect to tell mq which guards to use. A patch will be pushed if
-    it has no guards or any positive guards match the currently
-    selected guard, but will not be pushed if any negative guards
-    match the current guard. For example:
+    Use the qguard command to set or print guards on patch, then use qselect
+    to tell mq which guards to use. A patch will be pushed if it has no guards
+    or any positive guards match the currently selected guard, but will not be
+    pushed if any negative guards match the current guard. For example:
 
         qguard foo.patch -stable    (negative guard)
         qguard bar.patch +stable    (positive guard)
         qselect stable
 
-    This activates the "stable" guard. mq will skip foo.patch (because
-    it has a negative match) but push bar.patch (because it has a
-    positive match).
+    This activates the "stable" guard. mq will skip foo.patch (because it has
+    a negative match) but push bar.patch (because it has a positive match).
 
-    With no arguments, prints the currently active guards.
-    With one argument, sets the active guard.
+    With no arguments, prints the currently active guards. With one argument,
+    sets the active guard.
 
-    Use -n/--none to deactivate guards (no other arguments needed).
-    When no guards are active, patches with positive guards are
-    skipped and patches with negative guards are pushed.
+    Use -n/--none to deactivate guards (no other arguments needed). When no
+    guards are active, patches with positive guards are skipped and patches
+    with negative guards are pushed.
 
-    qselect can change the guards on applied patches. It does not pop
-    guarded patches by default. Use --pop to pop back to the last
-    applied patch that is not guarded. Use --reapply (which implies
-    --pop) to push back to the current patch afterwards, but skip
-    guarded patches.
+    qselect can change the guards on applied patches. It does not pop guarded
+    patches by default. Use --pop to pop back to the last applied patch that
+    is not guarded. Use --reapply (which implies --pop) to push back to the
+    current patch afterwards, but skip guarded patches.
 
-    Use -s/--series to print a list of all guards in the series file
-    (no other arguments needed). Use -v for more information.'''
+    Use -s/--series to print a list of all guards in the series file (no other
+    arguments needed). Use -v for more information.
+    '''
 
     q = repo.mq
     guards = q.active()
@@ -2330,7 +2325,7 @@
         if ui.verbose:
             guards['NONE'] = noguards
         guards = guards.items()
-        guards.sort(lambda a, b: cmp(a[0][1:], b[0][1:]))
+        guards.sort(key=lambda x: x[0][1:])
         if guards:
             ui.note(_('guards in series file:\n'))
             for guard, count in guards:
@@ -2369,18 +2364,16 @@
 def finish(ui, repo, *revrange, **opts):
     """move applied patches into repository history
 
-    Finishes the specified revisions (corresponding to applied
-    patches) by moving them out of mq control into regular repository
-    history.
+    Finishes the specified revisions (corresponding to applied patches) by
+    moving them out of mq control into regular repository history.
 
-    Accepts a revision range or the -a/--applied option. If --applied
-    is specified, all applied mq revisions are removed from mq
-    control. Otherwise, the given revisions must be at the base of the
-    stack of applied patches.
+    Accepts a revision range or the -a/--applied option. If --applied is
+    specified, all applied mq revisions are removed from mq control.
+    Otherwise, the given revisions must be at the base of the stack of applied
+    patches.
 
-    This can be especially useful if your changes have been applied to
-    an upstream repository, or if you are about to push your changes
-    to upstream.
+    This can be especially useful if your changes have been applied to an
+    upstream repository, or if you are about to push your changes to upstream.
     """
     if not opts['applied'] and not revrange:
         raise util.Abort(_('no revisions specified'))
@@ -2423,34 +2416,33 @@
                 raise util.Abort(_('source has mq patches applied'))
             return super(mqrepo, self).push(remote, force, revs)
 
-        def tags(self):
-            if self.tagscache:
-                return self.tagscache
-
-            tagscache = super(mqrepo, self).tags()
+        def _findtags(self):
+            '''augment tags from base class with patch tags'''
+            result = super(mqrepo, self)._findtags()
 
             q = self.mq
             if not q.applied:
-                return tagscache
+                return result
 
             mqtags = [(bin(patch.rev), patch.name) for patch in q.applied]
 
             if mqtags[-1][0] not in self.changelog.nodemap:
                 self.ui.warn(_('mq status file refers to unknown node %s\n')
                              % short(mqtags[-1][0]))
-                return tagscache
+                return result
 
             mqtags.append((mqtags[-1][0], 'qtip'))
             mqtags.append((mqtags[0][0], 'qbase'))
             mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
+            tags = result[0]
             for patch in mqtags:
-                if patch[1] in tagscache:
+                if patch[1] in tags:
                     self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
                                  % patch[1])
                 else:
-                    tagscache[patch[1]] = patch[0]
+                    tags[patch[1]] = patch[0]
 
-            return tagscache
+            return result
 
         def _branchtags(self, partial, lrev):
             q = self.mq
--- a/hgext/notify.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/notify.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,62 +7,64 @@
 
 '''hooks for sending email notifications at commit/push time
 
-Subscriptions can be managed through hgrc. Default mode is to print
+Subscriptions can be managed through a hgrc file. Default mode is to print
 messages to stdout, for testing and configuring.
 
-To use, configure notify extension and enable in hgrc like this:
+To use, configure the notify extension and enable it in hgrc like this::
 
-   [extensions]
-   hgext.notify =
+  [extensions]
+  hgext.notify =
 
-   [hooks]
-   # one email for each incoming changeset
-   incoming.notify = python:hgext.notify.hook
-   # batch emails when many changesets incoming at one time
-   changegroup.notify = python:hgext.notify.hook
+  [hooks]
+  # one email for each incoming changeset
+  incoming.notify = python:hgext.notify.hook
+  # batch emails when many changesets incoming at one time
+  changegroup.notify = python:hgext.notify.hook
 
-   [notify]
-   # config items go in here
+  [notify]
+  # config items go here
 
- config items:
+Required configuration items::
 
- REQUIRED:
-   config = /path/to/file # file containing subscriptions
+  config = /path/to/file # file containing subscriptions
+
+Optional configuration items::
 
- OPTIONAL:
-   test = True            # print messages to stdout for testing
-   strip = 3              # number of slashes to strip for url paths
-   domain = example.com   # domain to use if committer missing domain
-   style = ...            # style file to use when formatting email
-   template = ...         # template to use when formatting email
-   incoming = ...         # template to use when run as incoming hook
-   changegroup = ...      # template when run as changegroup hook
-   maxdiff = 300          # max lines of diffs to include (0=none, -1=all)
-   maxsubject = 67        # truncate subject line longer than this
-   diffstat = True        # add a diffstat before the diff content
-   sources = serve        # notify if source of incoming changes in this list
-                          # (serve == ssh or http, push, pull, bundle)
-   [email]
-   from = user@host.com   # email address to send as if none given
-   [web]
-   baseurl = http://hgserver/... # root of hg web site for browsing commits
+  test = True            # print messages to stdout for testing
+  strip = 3              # number of slashes to strip for url paths
+  domain = example.com   # domain to use if committer missing domain
+  style = ...            # style file to use when formatting email
+  template = ...         # template to use when formatting email
+  incoming = ...         # template to use when run as incoming hook
+  changegroup = ...      # template when run as changegroup hook
+  maxdiff = 300          # max lines of diffs to include (0=none, -1=all)
+  maxsubject = 67        # truncate subject line longer than this
+  diffstat = True        # add a diffstat before the diff content
+  sources = serve        # notify if source of incoming changes in this list
+                         # (serve == ssh or http, push, pull, bundle)
+  [email]
+  from = user@host.com   # email address to send as if none given
+  [web]
+  baseurl = http://hgserver/... # root of hg web site for browsing commits
 
- notify config file has same format as regular hgrc. it has two
- sections so you can express subscriptions in whatever way is handier
- for you.
+The notify config file has same format as a regular hgrc file. It has two
+sections so you can express subscriptions in whatever way is handier for you.
 
-   [usersubs]
-   # key is subscriber email, value is ","-separated list of glob patterns
-   user@host = pattern
+::
+
+  [usersubs]
+  # key is subscriber email, value is ","-separated list of glob patterns
+  user@host = pattern
 
-   [reposubs]
-   # key is glob pattern, value is ","-separated list of subscriber emails
-   pattern = user@host
+  [reposubs]
+  # key is glob pattern, value is ","-separated list of subscriber emails
+  pattern = user@host
 
- glob patterns are matched against path to repository root.
+Glob patterns are matched against path to repository root.
 
- if you like, you can put notify config file in repository that users
- can push changes to, they can manage their own subscriptions.'''
+If you like, you can put notify config file in repository that users can push
+changes to, they can manage their own subscriptions.
+'''
 
 from mercurial.i18n import _
 from mercurial import patch, cmdutil, templater, util, mail
@@ -226,7 +228,7 @@
                                   hash(self.repo.root), socket.getfqdn()))
         msg['To'] = ', '.join(self.subs)
 
-        msgtext = msg.as_string(0)
+        msgtext = msg.as_string()
         if self.test:
             self.ui.write(msgtext)
             if not msgtext.endswith('\n'):
--- a/hgext/pager.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/pager.py	Thu Aug 06 18:48:00 2009 -0700
@@ -14,36 +14,34 @@
 
 '''browse command output with an external pager
 
-To set the pager that should be used, set the application variable:
+To set the pager that should be used, set the application variable::
 
   [pager]
   pager = LESS='FSRX' less
 
-If no pager is set, the pager extensions uses the environment variable
-$PAGER. If neither pager.pager, nor $PAGER is set, no pager is used.
+If no pager is set, the pager extensions uses the environment variable $PAGER.
+If neither pager.pager, nor $PAGER is set, no pager is used.
 
-If you notice "BROKEN PIPE" error messages, you can disable them by
-setting:
+If you notice "BROKEN PIPE" error messages, you can disable them by setting::
 
   [pager]
   quiet = True
 
 You can disable the pager for certain commands by adding them to the
-pager.ignore list:
+pager.ignore list::
 
   [pager]
   ignore = version, help, update
 
-You can also enable the pager only for certain commands using
-pager.attend:
+You can also enable the pager only for certain commands using pager.attend::
 
   [pager]
   attend = log
 
 If pager.attend is present, pager.ignore will be ignored.
 
-To ignore global commands like "hg version" or "hg help", you have to
-specify them in the global .hgrc
+To ignore global commands like "hg version" or "hg help", you have to specify
+them in the global .hgrc
 '''
 
 import sys, os, signal
--- a/hgext/parentrevspec.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/parentrevspec.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,18 +7,18 @@
 
 '''interpret suffixes to refer to ancestor revisions
 
-This extension allows you to use git-style suffixes to refer to the
-ancestors of a specific revision.
+This extension allows you to use git-style suffixes to refer to the ancestors
+of a specific revision.
 
-For example, if you can refer to a revision as "foo", then:
+For example, if you can refer to a revision as "foo", then::
 
-- foo^N = Nth parent of foo
+  foo^N = Nth parent of foo
   foo^0 = foo
   foo^1 = first parent of foo
   foo^2 = second parent of foo
   foo^  = foo^1
 
-- foo~N = Nth first grandparent of foo
+  foo~N = Nth first grandparent of foo
   foo~0 = foo
   foo~1 = foo^1 = foo^ = first parent of foo
   foo~2 = foo^1^1 = foo^^ = first parent of first parent of foo
--- a/hgext/patchbomb.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/patchbomb.py	Thu Aug 06 18:48:00 2009 -0700
@@ -10,9 +10,9 @@
 The series is started off with a "[PATCH 0 of N]" introduction, which
 describes the series as a whole.
 
-Each patch email has a Subject line of "[PATCH M of N] ...", using the
-first line of the changeset description as the subject text. The
-message contains two or three body parts:
+Each patch email has a Subject line of "[PATCH M of N] ...", using the first
+line of the changeset description as the subject text. The message contains
+two or three body parts:
 
   The changeset description.
 
@@ -20,16 +20,15 @@
 
   The patch itself, as generated by "hg export".
 
-Each message refers to the first in the series using the In-Reply-To
-and References headers, so they will show up as a sequence in threaded
-mail and news readers, and in mail archives.
+Each message refers to the first in the series using the In-Reply-To and
+References headers, so they will show up as a sequence in threaded mail and
+news readers, and in mail archives.
 
-With the -d/--diffstat option, you will be prompted for each changeset
-with a diffstat summary and the changeset summary, so you can be sure
-you are sending the right changes.
+With the -d/--diffstat option, you will be prompted for each changeset with a
+diffstat summary and the changeset summary, so you can be sure you are sending
+the right changes.
 
-To configure other defaults, add a section like this to your hgrc
-file:
+To configure other defaults, add a section like this to your hgrc file::
 
   [email]
   from = My Name <my@email>
@@ -37,40 +36,38 @@
   cc = cc1, cc2, ...
   bcc = bcc1, bcc2, ...
 
-Then you can use the "hg email" command to mail a series of changesets
-as a patchbomb.
+Then you can use the "hg email" command to mail a series of changesets as a
+patchbomb.
 
-To avoid sending patches prematurely, it is a good idea to first run
-the "email" command with the "-n" option (test only). You will be
-prompted for an email recipient address, a subject and an introductory
-message describing the patches of your patchbomb. Then when all is
-done, patchbomb messages are displayed. If the PAGER environment
-variable is set, your pager will be fired up once for each patchbomb
-message, so you can verify everything is alright.
+To avoid sending patches prematurely, it is a good idea to first run the
+"email" command with the "-n" option (test only). You will be prompted for an
+email recipient address, a subject and an introductory message describing the
+patches of your patchbomb. Then when all is done, patchbomb messages are
+displayed. If the PAGER environment variable is set, your pager will be fired
+up once for each patchbomb message, so you can verify everything is alright.
 
-The -m/--mbox option is also very useful. Instead of previewing each
-patchbomb message in a pager or sending the messages directly, it will
-create a UNIX mailbox file with the patch emails. This mailbox file
-can be previewed with any mail user agent which supports UNIX mbox
-files, e.g. with mutt:
+The -m/--mbox option is also very useful. Instead of previewing each patchbomb
+message in a pager or sending the messages directly, it will create a UNIX
+mailbox file with the patch emails. This mailbox file can be previewed with
+any mail user agent which supports UNIX mbox files, e.g. with mutt::
 
   % mutt -R -f mbox
 
-When you are previewing the patchbomb messages, you can use `formail'
-(a utility that is commonly installed as part of the procmail
-package), to send each message out:
+When you are previewing the patchbomb messages, you can use `formail' (a
+utility that is commonly installed as part of the procmail package), to send
+each message out::
 
   % formail -s sendmail -bm -t < mbox
 
 That should be all. Now your patchbomb is on its way out.
 
-You can also either configure the method option in the email section
-to be a sendmail compatible mailer or fill out the [smtp] section so
-that the patchbomb extension can automatically send patchbombs
-directly from the commandline. See the [email] and [smtp] sections in
-hgrc(5) for details.'''
+You can also either configure the method option in the email section to be a
+sendmail compatible mailer or fill out the [smtp] section so that the
+patchbomb extension can automatically send patchbombs directly from the
+commandline. See the [email] and [smtp] sections in hgrc(5) for details.
+'''
 
-import os, errno, socket, tempfile, cStringIO
+import os, errno, socket, tempfile, cStringIO, time
 import email.MIMEMultipart, email.MIMEBase
 import email.Utils, email.Encoders, email.Generator
 from mercurial import cmdutil, commands, hg, mail, patch, util
@@ -176,30 +173,27 @@
 def patchbomb(ui, repo, *revs, **opts):
     '''send changesets by email
 
-    By default, diffs are sent in the format generated by hg export,
-    one per message. The series starts with a "[PATCH 0 of N]"
-    introduction, which describes the series as a whole.
+    By default, diffs are sent in the format generated by hg export, one per
+    message. The series starts with a "[PATCH 0 of N]" introduction, which
+    describes the series as a whole.
 
-    Each patch email has a Subject line of "[PATCH M of N] ...", using
-    the first line of the changeset description as the subject text.
-    The message contains two or three parts. First, the changeset
-    description. Next, (optionally) if the diffstat program is
-    installed and -d/--diffstat is used, the result of running
-    diffstat on the patch. Finally, the patch itself, as generated by
-    "hg export".
+    Each patch email has a Subject line of "[PATCH M of N] ...", using the
+    first line of the changeset description as the subject text. The message
+    contains two or three parts. First, the changeset description. Next,
+    (optionally) if the diffstat program is installed and -d/--diffstat is
+    used, the result of running diffstat on the patch. Finally, the patch
+    itself, as generated by "hg export".
 
-    By default the patch is included as text in the email body for
-    easy reviewing. Using the -a/--attach option will instead create
-    an attachment for the patch. With -i/--inline an inline attachment
-    will be created.
+    By default the patch is included as text in the email body for easy
+    reviewing. Using the -a/--attach option will instead create an attachment
+    for the patch. With -i/--inline an inline attachment will be created.
 
-    With -o/--outgoing, emails will be generated for patches not found
-    in the destination repository (or only those which are ancestors
-    of the specified revisions if any are provided)
+    With -o/--outgoing, emails will be generated for patches not found in the
+    destination repository (or only those which are ancestors of the specified
+    revisions if any are provided)
 
-    With -b/--bundle, changesets are selected as for --outgoing, but a
-    single email containing a binary Mercurial bundle as an attachment
-    will be sent.
+    With -b/--bundle, changesets are selected as for --outgoing, but a single
+    email containing a binary Mercurial bundle as an attachment will be sent.
 
     Examples:
 
@@ -218,8 +212,8 @@
     hg email -b -r 3000       # bundle of all ancestors of 3000 not in default
     hg email -b -r 3000 DEST  # bundle of all ancestors of 3000 not in DEST
 
-    Before using this command, you will need to enable email in your
-    hgrc. See the [email] section in hgrc(5) for details.
+    Before using this command, you will need to enable email in your hgrc. See
+    the [email] section in hgrc(5) for details.
     '''
 
     _charsets = mail._charsets(ui)
@@ -417,7 +411,7 @@
             first = False
 
         m['User-Agent'] = 'Mercurial-patchbomb/%s' % util.version()
-        m['Date'] = email.Utils.formatdate(start_time[0])
+        m['Date'] = email.Utils.formatdate(start_time[0], localtime=True)
 
         start_time = (start_time[0] + 1, start_time[1])
         m['From'] = sender
@@ -446,7 +440,7 @@
             ui.status(_('Writing '), subj, ' ...\n')
             fp = open(opts.get('mbox'), 'In-Reply-To' in m and 'ab+' or 'wb+')
             generator = email.Generator.Generator(fp, mangle_from_=True)
-            date = util.datestr(start_time, '%a %b %d %H:%M:%S %Y')
+            date = time.ctime(start_time[0])
             fp.write('From %s %s\n' % (sender_addr, date))
             generator.flatten(m, 0)
             fp.write('\n\n')
--- a/hgext/purge.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/purge.py	Thu Aug 06 18:48:00 2009 -0700
@@ -32,25 +32,27 @@
 def purge(ui, repo, *dirs, **opts):
     '''removes files not tracked by Mercurial
 
-    Delete files not known to Mercurial. This is useful to test local
-    and uncommitted changes in an otherwise-clean source tree.
+    Delete files not known to Mercurial. This is useful to test local and
+    uncommitted changes in an otherwise-clean source tree.
 
     This means that purge will delete:
-     - Unknown files: files marked with "?" by "hg status"
-     - Empty directories: in fact Mercurial ignores directories unless
-       they contain files under source control management
+
+    - Unknown files: files marked with "?" by "hg status"
+    - Empty directories: in fact Mercurial ignores directories unless they
+      contain files under source control management
+
     But it will leave untouched:
-     - Modified and unmodified tracked files
-     - Ignored files (unless --all is specified)
-     - New files added to the repository (with "hg add")
+
+    - Modified and unmodified tracked files
+    - Ignored files (unless --all is specified)
+    - New files added to the repository (with "hg add")
 
     If directories are given on the command line, only files in these
     directories are considered.
 
-    Be careful with purge, as you could irreversibly delete some files
-    you forgot to add to the repository. If you only want to print the
-    list of files that this program would delete, use the --print
-    option.
+    Be careful with purge, as you could irreversibly delete some files you
+    forgot to add to the repository. If you only want to print the list of
+    files that this program would delete, use the --print option.
     '''
     act = not opts['print']
     eol = '\n'
--- a/hgext/rebase.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/rebase.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,8 +7,7 @@
 
 '''command to move sets of revisions to a different ancestor
 
-This extension lets you rebase changesets in an existing Mercurial
-repository.
+This extension lets you rebase changesets in an existing Mercurial repository.
 
 For more information:
 http://mercurial.selenic.com/wiki/RebaseProject
@@ -42,9 +41,9 @@
 def rebase(ui, repo, **opts):
     """move changeset (and descendants) to a different branch
 
-    Rebase uses repeated merging to graft changesets from one part of
-    history onto another. This can be useful for linearizing local
-    changes relative to a master development tree.
+    Rebase uses repeated merging to graft changesets from one part of history
+    onto another. This can be useful for linearizing local changes relative to
+    a master development tree.
 
     If a rebase is interrupted to manually resolve a merge, it can be
     continued with --continue/-c or aborted with --abort/-a.
--- a/hgext/record.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/record.py	Thu Aug 06 18:48:00 2009 -0700
@@ -291,25 +291,28 @@
                     _('Record &all changes to all remaining files'),
                     _('&Quit, recording no changes'),
                     _('&?'))
-            r = (ui.prompt("%s %s " % (query, resps), choices)
-                 or _('y')).lower()
-            if r == _('?'):
+            r = ui.promptchoice("%s %s " % (query, resps), choices)
+            if r == 7: # ?
                 doc = gettext(record.__doc__)
                 c = doc.find(_('y - record this change'))
                 for l in doc[c:].splitlines():
                     if l: ui.write(l.strip(), '\n')
                 continue
-            elif r == _('s'):
-                r = resp_file[0] = 'n'
-            elif r == _('f'):
-                r = resp_file[0] = 'y'
-            elif r == _('d'):
-                r = resp_all[0] = 'n'
-            elif r == _('a'):
-                r = resp_all[0] = 'y'
-            elif r == _('q'):
+            elif r == 0: # yes
+                ret = 'y'
+            elif r == 1: # no
+                ret = 'n'
+            elif r == 2: # Skip
+                ret = resp_file[0] = 'n'
+            elif r == 3: # file (Record remaining)
+                ret = resp_file[0] = 'y'
+            elif r == 4: # done, skip remaining
+                ret = resp_all[0] = 'n'
+            elif r == 5: # all
+                ret = resp_all[0] = 'y'
+            elif r == 6: # quit
                 raise util.Abort(_('user quit'))
-            return r
+            return ret
     pos, total = 0, len(chunks) - 1
     while chunks:
         chunk = chunks.pop()
@@ -354,27 +357,26 @@
 def record(ui, repo, *pats, **opts):
     '''interactively select changes to commit
 
-    If a list of files is omitted, all changes reported by "hg status"
-    will be candidates for recording.
+    If a list of files is omitted, all changes reported by "hg status" will be
+    candidates for recording.
 
     See 'hg help dates' for a list of formats valid for -d/--date.
 
-    You will be prompted for whether to record changes to each
-    modified file, and for files with multiple changes, for each
-    change to use. For each query, the following responses are
-    possible:
+    You will be prompted for whether to record changes to each modified file,
+    and for files with multiple changes, for each change to use. For each
+    query, the following responses are possible::
 
-    y - record this change
-    n - skip this change
+      y - record this change
+      n - skip this change
 
-    s - skip remaining changes to this file
-    f - record remaining changes to this file
+      s - skip remaining changes to this file
+      f - record remaining changes to this file
 
-    d - done, skip remaining changes and files
-    a - record all changes to all remaining files
-    q - quit, recording no changes
+      d - done, skip remaining changes and files
+      a - record all changes to all remaining files
+      q - quit, recording no changes
 
-    ? - display help'''
+      ? - display help'''
 
     def record_committer(ui, repo, pats, opts):
         commands.commit(ui, repo, *pats, **opts)
@@ -385,8 +387,7 @@
 def qrecord(ui, repo, patch, *pats, **opts):
     '''interactively record a new patch
 
-    See 'hg help qnew' & 'hg help record' for more information and
-    usage.
+    See 'hg help qnew' & 'hg help record' for more information and usage.
     '''
 
     try:
@@ -409,7 +410,7 @@
     def recordfunc(ui, repo, message, match, opts):
         """This is generic record driver.
 
-        It's job is to interactively filter local changes, and accordingly
+        Its job is to interactively filter local changes, and accordingly
         prepare working dir into a state, where the job can be delegated to
         non-interactive commit command such as 'commit' or 'qrefresh'.
 
--- a/hgext/share.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/share.py	Thu Aug 06 18:48:00 2009 -0700
@@ -5,18 +5,17 @@
 
 '''share a common history between several working directories'''
 
-import os
 from mercurial.i18n import _
 from mercurial import hg, commands
 
 def share(ui, source, dest=None, noupdate=False):
     """create a new shared repository (experimental)
 
-    Initialize a new repository and working directory that shares its
-    history with another repository.
+    Initialize a new repository and working directory that shares its history
+    with another repository.
 
-    NOTE: actions that change history such as rollback or moving the
-    source may confuse sharers.
+    NOTE: actions that change history such as rollback or moving the source
+    may confuse sharers.
     """
 
     return hg.share(ui, source, dest, not noupdate)
--- a/hgext/transplant.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/transplant.py	Thu Aug 06 18:48:00 2009 -0700
@@ -9,8 +9,8 @@
 
 This extension allows you to transplant patches from another branch.
 
-Transplanted patches are recorded in .hg/transplant/transplants, as a
-map from a changeset hash to its hash in the source repository.
+Transplanted patches are recorded in .hg/transplant/transplants, as a map from
+a changeset hash to its hash in the source repository.
 '''
 
 from mercurial.i18n import _
@@ -438,37 +438,34 @@
     '''transplant changesets from another branch
 
     Selected changesets will be applied on top of the current working
-    directory with the log of the original changeset. If --log is
-    specified, log messages will have a comment appended of the form:
+    directory with the log of the original changeset. If --log is specified,
+    log messages will have a comment appended of the form::
 
-    (transplanted from CHANGESETHASH)
+      (transplanted from CHANGESETHASH)
 
-    You can rewrite the changelog message with the --filter option.
-    Its argument will be invoked with the current changelog message as
-    $1 and the patch as $2.
+    You can rewrite the changelog message with the --filter option. Its
+    argument will be invoked with the current changelog message as $1 and the
+    patch as $2.
 
-    If --source/-s is specified, selects changesets from the named
-    repository. If --branch/-b is specified, selects changesets from
-    the branch holding the named revision, up to that revision. If
-    --all/-a is specified, all changesets on the branch will be
-    transplanted, otherwise you will be prompted to select the
-    changesets you want.
+    If --source/-s is specified, selects changesets from the named repository.
+    If --branch/-b is specified, selects changesets from the branch holding
+    the named revision, up to that revision. If --all/-a is specified, all
+    changesets on the branch will be transplanted, otherwise you will be
+    prompted to select the changesets you want.
 
-    hg transplant --branch REVISION --all will rebase the selected
-    branch (up to the named revision) onto your current working
-    directory.
+    hg transplant --branch REVISION --all will rebase the selected branch (up
+    to the named revision) onto your current working directory.
 
     You can optionally mark selected transplanted changesets as merge
-    changesets. You will not be prompted to transplant any ancestors
-    of a merged transplant, and you can merge descendants of them
-    normally instead of transplanting them.
+    changesets. You will not be prompted to transplant any ancestors of a
+    merged transplant, and you can merge descendants of them normally instead
+    of transplanting them.
 
-    If no merges or revisions are provided, hg transplant will start
-    an interactive changeset browser.
+    If no merges or revisions are provided, hg transplant will start an
+    interactive changeset browser.
 
-    If a changeset application fails, you can fix the merge by hand
-    and then resume where you left off by calling hg transplant
-    --continue/-c.
+    If a changeset application fails, you can fix the merge by hand and then
+    resume where you left off by calling hg transplant --continue/-c.
     '''
     def getremotechanges(repo, url):
         sourcerepo = ui.expandpath(url)
--- a/hgext/win32mbcs.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/win32mbcs.py	Thu Aug 06 18:48:00 2009 -0700
@@ -11,31 +11,31 @@
 
 '''allow the use of MBCS paths with problematic encodings
 
-Some MBCS encodings are not good for some path operations (i.e.
-splitting path, case conversion, etc.) with its encoded bytes. We call
-such a encoding (i.e. shift_jis and big5) as "problematic encoding".
-This extension can be used to fix the issue with those encodings by
-wrapping some functions to convert to Unicode string before path
-operation.
+Some MBCS encodings are not good for some path operations (i.e. splitting
+path, case conversion, etc.) with its encoded bytes. We call such a encoding
+(i.e. shift_jis and big5) as "problematic encoding". This extension can be
+used to fix the issue with those encodings by wrapping some functions to
+convert to Unicode string before path operation.
 
 This extension is useful for:
- * Japanese Windows users using shift_jis encoding.
- * Chinese Windows users using big5 encoding.
- * All users who use a repository with one of problematic encodings on
-   case-insensitive file system.
+
+- Japanese Windows users using shift_jis encoding.
+- Chinese Windows users using big5 encoding.
+- All users who use a repository with one of problematic encodings on
+  case-insensitive file system.
 
 This extension is not needed for:
- * Any user who use only ASCII chars in path.
- * Any user who do not use any of problematic encodings.
+
+- Any user who use only ASCII chars in path.
+- Any user who do not use any of problematic encodings.
 
 Note that there are some limitations on using this extension:
- * You should use single encoding in one repository.
- * You should set same encoding for the repository by locale or
-   HGENCODING.
 
-Path encoding conversion are done between Unicode and
-encoding.encoding which is decided by Mercurial from current locale
-setting or HGENCODING.
+- You should use single encoding in one repository.
+- You should set same encoding for the repository by locale or HGENCODING.
+
+Path encoding conversion are done between Unicode and encoding.encoding which
+is decided by Mercurial from current locale setting or HGENCODING.
 '''
 
 import os, sys
--- a/hgext/win32text.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/win32text.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,30 +7,30 @@
 
 '''perform automatic newline conversion
 
-To perform automatic newline conversion, use:
+To perform automatic newline conversion, use::
 
-[extensions]
-hgext.win32text =
-[encode]
-** = cleverencode:
-# or ** = macencode:
+  [extensions]
+  hgext.win32text =
+  [encode]
+  ** = cleverencode:
+  # or ** = macencode:
 
-[decode]
-** = cleverdecode:
-# or ** = macdecode:
+  [decode]
+  ** = cleverdecode:
+  # or ** = macdecode:
 
-If not doing conversion, to make sure you do not commit CRLF/CR by accident:
+If not doing conversion, to make sure you do not commit CRLF/CR by accident::
 
-[hooks]
-pretxncommit.crlf = python:hgext.win32text.forbidcrlf
-# or pretxncommit.cr = python:hgext.win32text.forbidcr
+  [hooks]
+  pretxncommit.crlf = python:hgext.win32text.forbidcrlf
+  # or pretxncommit.cr = python:hgext.win32text.forbidcr
 
 To do the same check on a server to prevent CRLF/CR from being
-pushed or pulled:
+pushed or pulled::
 
-[hooks]
-pretxnchangegroup.crlf = python:hgext.win32text.forbidcrlf
-# or pretxnchangegroup.cr = python:hgext.win32text.forbidcr
+  [hooks]
+  pretxnchangegroup.crlf = python:hgext.win32text.forbidcrlf
+  # or pretxnchangegroup.cr = python:hgext.win32text.forbidcr
 '''
 
 from mercurial.i18n import _
--- a/hgext/zeroconf/__init__.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/hgext/zeroconf/__init__.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,20 +7,20 @@
 
 '''discover and advertise repositories on the local network
 
-Zeroconf enabled repositories will be announced in a network without
-the need to configure a server or a service. They can be discovered
-without knowing their actual IP address.
+Zeroconf enabled repositories will be announced in a network without the need
+to configure a server or a service. They can be discovered without knowing
+their actual IP address.
 
-To allow other people to discover your repository using run "hg serve"
-in your repository.
+To allow other people to discover your repository using run "hg serve" in your
+repository::
 
- $ cd test
- $ hg serve
+  $ cd test
+  $ hg serve
 
-You can discover zeroconf enabled repositories by running "hg paths".
+You can discover zeroconf enabled repositories by running "hg paths"::
 
- $ hg paths
- zc-test = http://example.com:8000/test
+  $ hg paths
+  zc-test = http://example.com:8000/test
 '''
 
 import Zeroconf, socket, time, os
--- a/mercurial/bundlerepo.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/bundlerepo.py	Thu Aug 06 18:48:00 2009 -0700
@@ -160,7 +160,7 @@
             localrepo.localrepository.__init__(self, ui, path)
         except error.RepoError:
             self._tempparent = tempfile.mkdtemp()
-            localrepo.instance(ui,self._tempparent,1)
+            localrepo.instance(ui, self._tempparent, 1)
             localrepo.localrepository.__init__(self, ui, self._tempparent)
 
         if path:
--- a/mercurial/byterange.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/byterange.py	Thu Aug 06 18:48:00 2009 -0700
@@ -208,7 +208,7 @@
     """
     def open_local_file(self, req):
         import mimetypes
-        import mimetools
+        import email
         host = req.get_host()
         file = req.get_selector()
         localfile = urllib.url2pathname(file)
@@ -232,9 +232,9 @@
                 raise RangeError('Requested Range Not Satisfiable')
             size = (lb - fb)
             fo = RangeableFileObject(fo, (fb, lb))
-        headers = mimetools.Message(StringIO(
+        headers = email.message_from_string(
             'Content-Type: %s\nContent-Length: %d\nLast-Modified: %s\n' %
-            (mtype or 'text/plain', size, modified)))
+            (mtype or 'text/plain', size, modified))
         return urllib.addinfourl(fo, headers, 'file:'+file)
 
 
@@ -251,7 +251,7 @@
 import socket
 import sys
 import mimetypes
-import mimetools
+import email
 
 class FTPRangeHandler(urllib2.FTPHandler):
     def ftp_open(self, req):
@@ -325,8 +325,7 @@
                 headers += "Content-Type: %s\n" % mtype
             if retrlen is not None and retrlen >= 0:
                 headers += "Content-Length: %d\n" % retrlen
-            sf = StringIO(headers)
-            headers = mimetools.Message(sf)
+            headers = email.message_from_string(headers)
             return addinfourl(fp, headers, req.get_full_url())
         except ftplib.all_errors, msg:
             raise IOError('ftp error', msg), sys.exc_info()[2]
--- a/mercurial/changegroup.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/changegroup.py	Thu Aug 06 18:48:00 2009 -0700
@@ -52,7 +52,7 @@
     "HG10GZ": ("HG10GZ", lambda: zlib.compressobj()),
 }
 
-# hgweb uses this list to communicate it's preferred type
+# hgweb uses this list to communicate its preferred type
 bundlepriority = ['HG10GZ', 'HG10BZ', 'HG10UN']
 
 def writebundle(cg, filename, bundletype):
--- a/mercurial/changelog.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/changelog.py	Thu Aug 06 18:48:00 2009 -0700
@@ -87,25 +87,39 @@
         self.data.append(str(s))
         self.offset += len(s)
 
+def delayopener(opener, target, divert, buf):
+    def o(name, mode='r'):
+        if name != target:
+            return opener(name, mode)
+        if divert:
+            return opener(name + ".a", mode.replace('a', 'w'))
+        # otherwise, divert to memory
+        return appender(opener(name, mode), buf)
+    return o
+
 class changelog(revlog.revlog):
     def __init__(self, opener):
+        revlog.revlog.__init__(self, opener, "00changelog.i")
         self._realopener = opener
         self._delayed = False
-        revlog.revlog.__init__(self, self._delayopener, "00changelog.i")
+        self._divert = False
 
     def delayupdate(self):
         "delay visibility of index updates to other readers"
         self._delayed = True
-        self._delaycount = len(self)
+        self._divert = (len(self) == 0)
         self._delaybuf = []
-        self._delayname = None
+        self.opener = delayopener(self._realopener, self.indexfile,
+                                  self._divert, self._delaybuf)
 
     def finalize(self, tr):
         "finalize index updates"
         self._delayed = False
+        self.opener = self._realopener
         # move redirected index data back into place
-        if self._delayname:
-            util.rename(self._delayname + ".a", self._delayname)
+        if self._divert:
+            n = self.opener(self.indexfile + ".a").name
+            util.rename(n, n[:-2])
         elif self._delaybuf:
             fp = self.opener(self.indexfile, 'a')
             fp.write("".join(self._delaybuf))
@@ -114,21 +128,6 @@
         # split when we're done
         self.checkinlinesize(tr)
 
-    def _delayopener(self, name, mode='r'):
-        fp = self._realopener(name, mode)
-        # only divert the index
-        if not self._delayed or not name == self.indexfile:
-            return fp
-        # if we're doing an initial clone, divert to another file
-        if self._delaycount == 0:
-            self._delayname = fp.name
-            if not len(self):
-                # make sure to truncate the file
-                mode = mode.replace('a', 'w')
-            return self._realopener(name + ".a", mode)
-        # otherwise, divert to memory
-        return appender(fp, self._delaybuf)
-
     def readpending(self, file):
         r = revlog.revlog(self.opener, file)
         self.index = r.index
@@ -147,17 +146,16 @@
             fp2.close()
             # switch modes so finalize can simply rename
             self._delaybuf = []
-            self._delayname = fp1.name
+            self._divert = True
 
-        if self._delayname:
+        if self._divert:
             return True
 
         return False
 
     def checkinlinesize(self, tr, fp=None):
-        if self.opener == self._delayopener:
-            return
-        return revlog.revlog.checkinlinesize(self, tr, fp)
+        if not self._delayed:
+            revlog.revlog.checkinlinesize(self, tr, fp)
 
     def read(self, node):
         """
--- a/mercurial/commands.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/commands.py	Thu Aug 06 18:48:00 2009 -0700
@@ -8,23 +8,23 @@
 from node import hex, nullid, nullrev, short
 from lock import release
 from i18n import _, gettext
-import os, re, sys, subprocess, difflib, time
+import os, re, sys, subprocess, difflib, time, tempfile
 import hg, util, revlog, bundlerepo, extensions, copies, context, error
-import patch, help, mdiff, tempfile, url, encoding
+import patch, help, mdiff, url, encoding
 import archival, changegroup, cmdutil, sshserver, hbisect
 from hgweb import server
 import merge as merge_
+import minirst
 
 # Commands start here, listed alphabetically
 
 def add(ui, repo, *pats, **opts):
     """add the specified files on the next commit
 
-    Schedule files to be version controlled and added to the
-    repository.
-
-    The files will be added to the repository at the next commit. To
-    undo an add before that, see hg forget.
+    Schedule files to be version controlled and added to the repository.
+
+    The files will be added to the repository at the next commit. To undo an
+    add before that, see hg forget.
 
     If no names are given, add all files to the repository.
     """
@@ -49,19 +49,16 @@
 def addremove(ui, repo, *pats, **opts):
     """add all new files, delete all missing files
 
-    Add all new files and remove all missing files from the
-    repository.
-
-    New files are ignored if they match any of the patterns in
-    .hgignore. As with add, these changes take effect at the next
-    commit.
-
-    Use the -s/--similarity option to detect renamed files. With a
-    parameter > 0, this compares every removed file with every added
-    file and records those similar enough as renames. This option
-    takes a percentage between 0 (disabled) and 100 (files must be
-    identical) as its parameter. Detecting renamed files this way can
-    be expensive.
+    Add all new files and remove all missing files from the repository.
+
+    New files are ignored if they match any of the patterns in .hgignore. As
+    with add, these changes take effect at the next commit.
+
+    Use the -s/--similarity option to detect renamed files. With a parameter
+    greater than 0, this compares every removed file with every added file and
+    records those similar enough as renames. This option takes a percentage
+    between 0 (disabled) and 100 (files must be identical) as its parameter.
+    Detecting renamed files this way can be expensive.
     """
     try:
         sim = float(opts.get('similarity') or 0)
@@ -74,16 +71,13 @@
 def annotate(ui, repo, *pats, **opts):
     """show changeset information by line for each file
 
-    List changes in files, showing the revision id responsible for
-    each line
-
-    This command is useful for discovering when a change was made and
-    by whom.
-
-    Without the -a/--text option, annotate will avoid processing files
-    it detects as binary. With -a, annotate will annotate the file
-    anyway, although the results will probably be neither useful
-    nor desirable.
+    List changes in files, showing the revision id responsible for each line
+
+    This command is useful for discovering when a change was made and by whom.
+
+    Without the -a/--text option, annotate will avoid processing files it
+    detects as binary. With -a, annotate will annotate the file anyway,
+    although the results will probably be neither useful nor desirable.
     """
     datefunc = ui.quiet and util.shortdate or util.datestr
     getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
@@ -137,26 +131,24 @@
 def archive(ui, repo, dest, **opts):
     '''create an unversioned archive of a repository revision
 
-    By default, the revision used is the parent of the working
-    directory; use -r/--rev to specify a different revision.
-
-    To specify the type of archive to create, use -t/--type. Valid
-    types are:
-
-    "files" (default): a directory full of files
-    "tar": tar archive, uncompressed
-    "tbz2": tar archive, compressed using bzip2
-    "tgz": tar archive, compressed using gzip
-    "uzip": zip archive, uncompressed
-    "zip": zip archive, compressed using deflate
-
-    The exact name of the destination archive or directory is given
-    using a format string; see 'hg help export' for details.
-
-    Each member added to an archive file has a directory prefix
-    prepended. Use -p/--prefix to specify a format string for the
-    prefix. The default is the basename of the archive, with suffixes
-    removed.
+    By default, the revision used is the parent of the working directory; use
+    -r/--rev to specify a different revision.
+
+    To specify the type of archive to create, use -t/--type. Valid types are::
+
+      "files" (default): a directory full of files
+      "tar": tar archive, uncompressed
+      "tbz2": tar archive, compressed using bzip2
+      "tgz": tar archive, compressed using gzip
+      "uzip": zip archive, uncompressed
+      "zip": zip archive, compressed using deflate
+
+    The exact name of the destination archive or directory is given using a
+    format string; see 'hg help export' for details.
+
+    Each member added to an archive file has a directory prefix prepended. Use
+    -p/--prefix to specify a format string for the prefix. The default is the
+    basename of the archive, with suffixes removed.
     '''
 
     ctx = repo[opts.get('rev')]
@@ -181,17 +173,17 @@
 def backout(ui, repo, node=None, rev=None, **opts):
     '''reverse effect of earlier changeset
 
-    Commit the backed out changes as a new changeset. The new
-    changeset is a child of the backed out changeset.
-
-    If you backout a changeset other than the tip, a new head is
-    created. This head will be the new tip and you should merge this
-    backout changeset with another head.
-
-    The --merge option remembers the parent of the working directory
-    before starting the backout, then merges the new head with that
-    changeset afterwards. This saves you from doing the merge by hand.
-    The result of this merge is not committed, as with a normal merge.
+    Commit the backed out changes as a new changeset. The new changeset is a
+    child of the backed out changeset.
+
+    If you backout a changeset other than the tip, a new head is created. This
+    head will be the new tip and you should merge this backout changeset with
+    another head.
+
+    The --merge option remembers the parent of the working directory before
+    starting the backout, then merges the new head with that changeset
+    afterwards. This saves you from doing the merge by hand. The result of
+    this merge is not committed, as with a normal merge.
 
     See 'hg help dates' for a list of formats valid for -d/--date.
     '''
@@ -247,7 +239,7 @@
     commit_opts['addremove'] = False
     if not commit_opts['message'] and not commit_opts['logfile']:
         # we don't translate commit messages
-        commit_opts['message'] = "Backed out changeset %s" % (short(node))
+        commit_opts['message'] = "Backed out changeset %s" % short(node)
         commit_opts['force_editor'] = True
     commit(ui, repo, **commit_opts)
     def nice(node):
@@ -269,23 +261,22 @@
                reset=None, good=None, bad=None, skip=None, noupdate=None):
     """subdivision search of changesets
 
-    This command helps to find changesets which introduce problems. To
-    use, mark the earliest changeset you know exhibits the problem as
-    bad, then mark the latest changeset which is free from the problem
-    as good. Bisect will update your working directory to a revision
-    for testing (unless the -U/--noupdate option is specified). Once
-    you have performed tests, mark the working directory as good or
-    bad, and bisect will either update to another candidate changeset
-    or announce that it has found the bad revision.
-
-    As a shortcut, you can also use the revision argument to mark a
-    revision as good or bad without checking it out first.
-
-    If you supply a command, it will be used for automatic bisection.
-    Its exit status will be used to mark revisions as good or bad:
-    status 0 means good, 125 means to skip the revision, 127
-    (command not found) will abort the bisection, and any other
-    non-zero exit status means the revision is bad.
+    This command helps to find changesets which introduce problems. To use,
+    mark the earliest changeset you know exhibits the problem as bad, then
+    mark the latest changeset which is free from the problem as good. Bisect
+    will update your working directory to a revision for testing (unless the
+    -U/--noupdate option is specified). Once you have performed tests, mark
+    the working directory as good or bad, and bisect will either update to
+    another candidate changeset or announce that it has found the bad
+    revision.
+
+    As a shortcut, you can also use the revision argument to mark a revision
+    as good or bad without checking it out first.
+
+    If you supply a command, it will be used for automatic bisection. Its exit
+    status will be used to mark revisions as good or bad: status 0 means good,
+    125 means to skip the revision, 127 (command not found) will abort the
+    bisection, and any other non-zero exit status means the revision is bad.
     """
     def print_result(nodes, good):
         displayer = cmdutil.show_changeset(ui, repo, {})
@@ -397,8 +388,8 @@
         while size <= changesets:
             tests, size = tests + 1, size * 2
         rev = repo.changelog.rev(node)
-        ui.write(_("Testing changeset %s:%s "
-                   "(%s changesets remaining, ~%s tests)\n")
+        ui.write(_("Testing changeset %d:%s "
+                   "(%d changesets remaining, ~%d tests)\n")
                  % (rev, short(node), changesets, tests))
         if not noupdate:
             cmdutil.bail_if_changed(repo)
@@ -407,21 +398,19 @@
 def branch(ui, repo, label=None, **opts):
     """set or show the current branch name
 
-    With no argument, show the current branch name. With one argument,
-    set the working directory branch name (the branch will not exist
-    in the repository until the next commit). Standard practice
-    recommends that primary development take place on the 'default'
-    branch.
-
-    Unless -f/--force is specified, branch will not let you set a
-    branch name that already exists, even if it's inactive.
-
-    Use -C/--clean to reset the working directory branch to that of
-    the parent of the working directory, negating a previous branch
-    change.
-
-    Use the command 'hg update' to switch to an existing branch. Use
-    'hg commit --close-branch' to mark this branch as closed.
+    With no argument, show the current branch name. With one argument, set the
+    working directory branch name (the branch will not exist in the repository
+    until the next commit). Standard practice recommends that primary
+    development take place on the 'default' branch.
+
+    Unless -f/--force is specified, branch will not let you set a branch name
+    that already exists, even if it's inactive.
+
+    Use -C/--clean to reset the working directory branch to that of the parent
+    of the working directory, negating a previous branch change.
+
+    Use the command 'hg update' to switch to an existing branch. Use 'hg
+    commit --close-branch' to mark this branch as closed.
     """
 
     if opts.get('clean'):
@@ -441,12 +430,12 @@
 def branches(ui, repo, active=False, closed=False):
     """list repository named branches
 
-    List the repository's named branches, indicating which ones are
-    inactive. If -c/--closed is specified, also list branches which have
-    been marked closed (see hg commit --close-branch).
-
-    If -a/--active is specified, only show active branches. A branch
-    is considered active if it contains repository heads.
+    List the repository's named branches, indicating which ones are inactive.
+    If -c/--closed is specified, also list branches which have been marked
+    closed (see hg commit --close-branch).
+
+    If -a/--active is specified, only show active branches. A branch is
+    considered active if it contains repository heads.
 
     Use the command 'hg update' to switch to an existing branch.
     """
@@ -483,25 +472,24 @@
 def bundle(ui, repo, fname, dest=None, **opts):
     """create a changegroup file
 
-    Generate a compressed changegroup file collecting changesets not
-    known to be in another repository.
-
-    If no destination repository is specified the destination is
-    assumed to have all the nodes specified by one or more --base
-    parameters. To create a bundle containing all changesets, use
-    -a/--all (or --base null).
-
-    You can change compression method with the -t/--type option.
-    The available compression methods are: none, bzip2, and
-    gzip (by default, bundles are compressed using bzip2).
-
-    The bundle file can then be transferred using conventional means
-    and applied to another repository with the unbundle or pull
-    command. This is useful when direct push and pull are not
-    available or when exporting an entire repository is undesirable.
-
-    Applying bundles preserves all changeset contents including
-    permissions, copy/rename information, and revision history.
+    Generate a compressed changegroup file collecting changesets not known to
+    be in another repository.
+
+    If no destination repository is specified the destination is assumed to
+    have all the nodes specified by one or more --base parameters. To create a
+    bundle containing all changesets, use -a/--all (or --base null).
+
+    You can change compression method with the -t/--type option. The available
+    compression methods are: none, bzip2, and gzip (by default, bundles are
+    compressed using bzip2).
+
+    The bundle file can then be transferred using conventional means and
+    applied to another repository with the unbundle or pull command. This is
+    useful when direct push and pull are not available or when exporting an
+    entire repository is undesirable.
+
+    Applying bundles preserves all changeset contents including permissions,
+    copy/rename information, and revision history.
     """
     revs = opts.get('rev') or None
     if revs:
@@ -558,17 +546,17 @@
 def cat(ui, repo, file1, *pats, **opts):
     """output the current or given revision of files
 
-    Print the specified files as they were at the given revision. If
-    no revision is given, the parent of the working directory is used,
-    or tip if no revision is checked out.
-
-    Output may be to a file, in which case the name of the file is
-    given using a format string. The formatting rules are the same as
-    for the export command, with the following additions:
-
-    %s   basename of file being printed
-    %d   dirname of file being printed, or '.' if in repository root
-    %p   root-relative path name of file being printed
+    Print the specified files as they were at the given revision. If no
+    revision is given, the parent of the working directory is used, or tip if
+    no revision is checked out.
+
+    Output may be to a file, in which case the name of the file is given using
+    a format string. The formatting rules are the same as for the export
+    command, with the following additions::
+
+      %s   basename of file being printed
+      %d   dirname of file being printed, or '.' if in repository root
+      %p   root-relative path name of file being printed
     """
     ctx = repo[opts.get('rev')]
     err = 1
@@ -587,47 +575,42 @@
 
     Create a copy of an existing repository in a new directory.
 
-    If no destination directory name is specified, it defaults to the
-    basename of the source.
-
-    The location of the source is added to the new repository's
-    .hg/hgrc file, as the default to be used for future pulls.
-
-    If you use the -r/--rev option to clone up to a specific revision,
-    no subsequent revisions (including subsequent tags) will be
-    present in the cloned repository. This option implies --pull, even
-    on local repositories.
-
-    By default, clone will check out the head of the 'default' branch.
-    If the -U/--noupdate option is used, the new clone will contain
-    only a repository (.hg) and no working copy (the working copy
-    parent is the null revision).
+    If no destination directory name is specified, it defaults to the basename
+    of the source.
+
+    The location of the source is added to the new repository's .hg/hgrc file,
+    as the default to be used for future pulls.
+
+    If you use the -r/--rev option to clone up to a specific revision, no
+    subsequent revisions (including subsequent tags) will be present in the
+    cloned repository. This option implies --pull, even on local repositories.
+
+    By default, clone will check out the head of the 'default' branch. If the
+    -U/--noupdate option is used, the new clone will contain only a repository
+    (.hg) and no working copy (the working copy parent is the null revision).
 
     See 'hg help urls' for valid source format details.
 
     It is possible to specify an ssh:// URL as the destination, but no
-    .hg/hgrc and working directory will be created on the remote side.
-    Please see 'hg help urls' for important details about ssh:// URLs.
-
-    For efficiency, hardlinks are used for cloning whenever the source
-    and destination are on the same filesystem (note this applies only
-    to the repository data, not to the checked out files). Some
-    filesystems, such as AFS, implement hardlinking incorrectly, but
-    do not report errors. In these cases, use the --pull option to
-    avoid hardlinking.
-
-    In some cases, you can clone repositories and checked out files
-    using full hardlinks with
+    .hg/hgrc and working directory will be created on the remote side. Please
+    see 'hg help urls' for important details about ssh:// URLs.
+
+    For efficiency, hardlinks are used for cloning whenever the source and
+    destination are on the same filesystem (note this applies only to the
+    repository data, not to the checked out files). Some filesystems, such as
+    AFS, implement hardlinking incorrectly, but do not report errors. In these
+    cases, use the --pull option to avoid hardlinking.
+
+    In some cases, you can clone repositories and checked out files using full
+    hardlinks with ::
 
       $ cp -al REPO REPOCLONE
 
-    This is the fastest way to clone, but it is not always safe. The
-    operation is not atomic (making sure REPO is not modified during
-    the operation is up to you) and you have to make sure your editor
-    breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
-    this is not compatible with certain extensions that place their
-    metadata under the .hg directory, such as mq.
-
+    This is the fastest way to clone, but it is not always safe. The operation
+    is not atomic (making sure REPO is not modified during the operation is up
+    to you) and you have to make sure your editor breaks hardlinks (Emacs and
+    most Linux Kernel tools do so). Also, this is not compatible with certain
+    extensions that place their metadata under the .hg directory, such as mq.
     """
     hg.clone(cmdutil.remoteui(ui, opts), source, dest,
              pull=opts.get('pull'),
@@ -639,17 +622,17 @@
     """commit the specified files or all outstanding changes
 
     Commit changes to the given files into the repository. Unlike a
-    centralized RCS, this operation is a local operation. See hg push
-    for a way to actively distribute your changes.
-
-    If a list of files is omitted, all changes reported by "hg status"
-    will be committed.
-
-    If you are committing the result of a merge, do not provide any
-    filenames or -I/-X filters.
-
-    If no commit message is specified, the configured editor is
-    started to prompt you for a message.
+    centralized RCS, this operation is a local operation. See hg push for a
+    way to actively distribute your changes.
+
+    If a list of files is omitted, all changes reported by "hg status" will be
+    committed.
+
+    If you are committing the result of a merge, do not provide any filenames
+    or -I/-X filters.
+
+    If no commit message is specified, the configured editor is started to
+    prompt you for a message.
 
     See 'hg help dates' for a list of formats valid for -d/--date.
     """
@@ -680,23 +663,23 @@
         ui.status(_('created new head\n'))
 
     if ui.debugflag:
-        ui.write(_('committed changeset %d:%s\n') % (rev,hex(node)))
+        ui.write(_('committed changeset %d:%s\n') % (rev, hex(node)))
     elif ui.verbose:
-        ui.write(_('committed changeset %d:%s\n') % (rev,short(node)))
+        ui.write(_('committed changeset %d:%s\n') % (rev, short(node)))
 
 def copy(ui, repo, *pats, **opts):
     """mark files as copied for the next commit
 
-    Mark dest as having copies of source files. If dest is a
-    directory, copies are put in that directory. If dest is a file,
-    the source must be a single file.
-
-    By default, this command copies the contents of files as they
-    exist in the working directory. If invoked with -A/--after, the
-    operation is recorded, but no copying is performed.
-
-    This command takes effect with the next commit. To undo a copy
-    before that, see hg revert.
+    Mark dest as having copies of source files. If dest is a directory, copies
+    are put in that directory. If dest is a file, the source must be a single
+    file.
+
+    By default, this command copies the contents of files as they exist in the
+    working directory. If invoked with -A/--after, the operation is recorded,
+    but no copying is performed.
+
+    This command takes effect with the next commit. To undo a copy before
+    that, see hg revert.
     """
     wlock = repo.wlock(False)
     try:
@@ -751,7 +734,7 @@
     ui.write("%s\n" % "\n".join(sorted(cmdlist)))
 
 def debugfsinfo(ui, path = "."):
-    file('.debugfsinfo', 'w').write('')
+    open('.debugfsinfo', 'w').write('')
     ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
     ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
     ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
@@ -799,14 +782,14 @@
 
     With no arguments, print names and values of all config items.
 
-    With one argument of the form section.name, print just the value
-    of that config item.
-
-    With multiple arguments, print names and values of all config
-    items with matching section names.
-
-    With --debug, the source (filename and line number) is printed
-    for each config item.
+    With one argument of the form section.name, print just the value of that
+    config item.
+
+    With multiple arguments, print names and values of all config items with
+    matching section names.
+
+    With --debug, the source (filename and line number) is printed for each
+    config item.
     """
 
     untrusted = bool(opts.get('untrusted'))
@@ -833,8 +816,8 @@
 def debugsetparents(ui, repo, rev1, rev2=None):
     """manually set the parents of the current working directory
 
-    This is useful for writing repository conversion tools, but should
-    be used with care.
+    This is useful for writing repository conversion tools, but should be used
+    with care.
     """
 
     if not rev2:
@@ -984,7 +967,7 @@
         if list(files) != [os.path.basename(fa)]:
             ui.write(_(" unexpected patch output!\n"))
             patchproblems += 1
-        a = file(fa).read()
+        a = open(fa).read()
         if a != b:
             ui.write(_(" patch test failed!\n"))
             patchproblems += 1
@@ -1068,22 +1051,21 @@
 
     Differences between files are shown using the unified diff format.
 
-    NOTE: diff may generate unexpected results for merges, as it will
-    default to comparing against the working directory's first parent
-    changeset if no revisions are specified.
-
-    When two revision arguments are given, then changes are shown
-    between those revisions. If only one revision is specified then
-    that revision is compared to the working directory, and, when no
-    revisions are specified, the working directory files are compared
-    to its parent.
-
-    Without the -a/--text option, diff will avoid generating diffs of
-    files it detects as binary. With -a, diff will generate a diff
-    anyway, probably with undesirable results.
-
-    Use the -g/--git option to generate diffs in the git extended diff
-    format. For more information, read 'hg help diffs'.
+    NOTE: diff may generate unexpected results for merges, as it will default
+    to comparing against the working directory's first parent changeset if no
+    revisions are specified.
+
+    When two revision arguments are given, then changes are shown between
+    those revisions. If only one revision is specified then that revision is
+    compared to the working directory, and, when no revisions are specified,
+    the working directory files are compared to its parent.
+
+    Without the -a/--text option, diff will avoid generating diffs of files it
+    detects as binary. With -a, diff will generate a diff anyway, probably
+    with undesirable results.
+
+    Use the -g/--git option to generate diffs in the git extended diff format.
+    For more information, read 'hg help diffs'.
     """
 
     revs = opts.get('rev')
@@ -1108,34 +1090,33 @@
 
     Print the changeset header and diffs for one or more revisions.
 
-    The information shown in the changeset header is: author,
-    changeset hash, parent(s) and commit comment.
-
-    NOTE: export may generate unexpected diff output for merge
-    changesets, as it will compare the merge changeset against its
-    first parent only.
-
-    Output may be to a file, in which case the name of the file is
-    given using a format string. The formatting rules are as follows:
-
-    %%   literal "%" character
-    %H   changeset hash (40 bytes of hexadecimal)
-    %N   number of patches being generated
-    %R   changeset revision number
-    %b   basename of the exporting repository
-    %h   short-form changeset hash (12 bytes of hexadecimal)
-    %n   zero-padded sequence number, starting at 1
-    %r   zero-padded changeset revision number
-
-    Without the -a/--text option, export will avoid generating diffs
-    of files it detects as binary. With -a, export will generate a
-    diff anyway, probably with undesirable results.
-
-    Use the -g/--git option to generate diffs in the git extended diff
-    format. See 'hg help diffs' for more information.
-
-    With the --switch-parent option, the diff will be against the
-    second parent. It can be useful to review a merge.
+    The information shown in the changeset header is: author, changeset hash,
+    parent(s) and commit comment.
+
+    NOTE: export may generate unexpected diff output for merge changesets, as
+    it will compare the merge changeset against its first parent only.
+
+    Output may be to a file, in which case the name of the file is given using
+    a format string. The formatting rules are as follows::
+
+      %%   literal "%" character
+      %H   changeset hash (40 bytes of hexadecimal)
+      %N   number of patches being generated
+      %R   changeset revision number
+      %b   basename of the exporting repository
+      %h   short-form changeset hash (12 bytes of hexadecimal)
+      %n   zero-padded sequence number, starting at 1
+      %r   zero-padded changeset revision number
+
+    Without the -a/--text option, export will avoid generating diffs of files
+    it detects as binary. With -a, export will generate a diff anyway,
+    probably with undesirable results.
+
+    Use the -g/--git option to generate diffs in the git extended diff format.
+    See 'hg help diffs' for more information.
+
+    With the --switch-parent option, the diff will be against the second
+    parent. It can be useful to review a merge.
     """
     if not changesets:
         raise util.Abort(_("export requires at least one changeset"))
@@ -1151,12 +1132,11 @@
 def forget(ui, repo, *pats, **opts):
     """forget the specified files on the next commit
 
-    Mark the specified files so they will no longer be tracked
-    after the next commit.
-
-    This only removes files from the current branch, not from the
-    entire project history, and it does not delete them from the
-    working directory.
+    Mark the specified files so they will no longer be tracked after the next
+    commit.
+
+    This only removes files from the current branch, not from the entire
+    project history, and it does not delete them from the working directory.
 
     To undo a forget before the next commit, see hg add.
     """
@@ -1185,15 +1165,13 @@
     Search revisions of files for a regular expression.
 
     This command behaves differently than Unix grep. It only accepts
-    Python/Perl regexps. It searches repository history, not the
-    working directory. It always prints the revision number in which a
-    match appears.
-
-    By default, grep only prints output for the first revision of a
-    file in which it finds a match. To get it to print every revision
-    that contains a change in match status ("-" for a match that
-    becomes a non-match, or "+" for a non-match that becomes a match),
-    use the --all flag.
+    Python/Perl regexps. It searches repository history, not the working
+    directory. It always prints the revision number in which a match appears.
+
+    By default, grep only prints output for the first revision of a file in
+    which it finds a match. To get it to print every revision that contains a
+    change in match status ("-" for a match that becomes a non-match, or "+"
+    for a non-match that becomes a match), use the --all flag.
     """
     reflags = 0
     if opts.get('ignore_case'):
@@ -1356,23 +1334,23 @@
 
     With no arguments, show all repository head changesets.
 
-    Repository "heads" are changesets that don't have child
-    changesets. They are where development generally takes place and
-    are the usual targets for update and merge operations.
-
-    If one or more REV is given, the "branch heads" will be shown for
-    the named branch associated with that revision. The name of the
-    branch is called the revision's branch tag.
-
-    Branch heads are revisions on a given named branch that do not have
-    any descendants on the same branch. A branch head could be a true head
-    or it could be the last changeset on a branch before a new branch
-    was created. If none of the branch heads are true heads, the branch
-    is considered inactive. If -c/--closed is specified, also show branch
-    heads marked closed (see hg commit --close-branch).
-
-    If STARTREV is specified only those heads (or branch heads) that
-    are descendants of STARTREV will be displayed.
+    Repository "heads" are changesets that don't have child changesets. They
+    are where development generally takes place and are the usual targets for
+    update and merge operations.
+
+    If one or more REV is given, the "branch heads" will be shown for the
+    named branch associated with that revision. The name of the branch is
+    called the revision's branch tag.
+
+    Branch heads are revisions on a given named branch that do not have any
+    descendants on the same branch. A branch head could be a true head or it
+    could be the last changeset on a branch before a new branch was created.
+    If none of the branch heads are true heads, the branch is considered
+    inactive. If -c/--closed is specified, also show branch heads marked
+    closed (see hg commit --close-branch).
+
+    If STARTREV is specified only those heads (or branch heads) that are
+    descendants of STARTREV will be displayed.
     """
     if opts.get('rev'):
         start = repo.lookup(opts['rev'])
@@ -1420,9 +1398,10 @@
 
     With no arguments, print a list of commands with short help messages.
 
-    Given a topic, extension, or command name, print help for that
-    topic."""
+    Given a topic, extension, or command name, print help for that topic.
+    """
     option_lists = []
+    textwidth = util.termwidth() - 2
 
     def addglobalopts(aliases):
         if ui.verbose:
@@ -1449,7 +1428,10 @@
         try:
             aliases, i = cmdutil.findcmd(name, table, False)
         except error.AmbiguousCommand, inst:
-            select = lambda c: c.lstrip('^').startswith(inst.args[0])
+            # py3k fix: except vars can't be used outside the scope of the
+            # except block, nor can be used inside a lambda. python issue4617
+            prefix = inst.args[0]
+            select = lambda c: c.lstrip('^').startswith(prefix)
             helplist(_('list of commands:\n\n'), select)
             return
 
@@ -1471,8 +1453,8 @@
         if not doc:
             doc = _("(no help text available)")
         if ui.quiet:
-            doc = doc.splitlines(0)[0]
-        ui.write("\n%s\n" % doc.rstrip())
+            doc = doc.splitlines()[0]
+        ui.write("\n%s\n" % minirst.format(doc, textwidth))
 
         if not ui.quiet:
             # options
@@ -1502,7 +1484,7 @@
             doc = gettext(doc)
             if not doc:
                 doc = _("(no help text available)")
-            h[f] = doc.splitlines(0)[0].rstrip()
+            h[f] = doc.splitlines()[0].rstrip()
             cmds[f] = c.lstrip("^")
 
         if not h:
@@ -1521,7 +1503,9 @@
 
         if name != 'shortlist':
             exts, maxlength = extensions.enabled()
-            ui.write(help.listexts(_('enabled extensions:'), exts, maxlength))
+            text = help.listexts(_('enabled extensions:'), exts, maxlength)
+            if text:
+                ui.write("\n%s\n" % minirst.format(text, textwidth))
 
         if not ui.quiet:
             addglobalopts(True)
@@ -1539,8 +1523,8 @@
         if hasattr(doc, '__call__'):
             doc = doc()
 
-        ui.write("%s\n" % header)
-        ui.write("%s\n" % doc.rstrip())
+        ui.write("%s\n\n" % header)
+        ui.write("%s\n" % minirst.format(doc, textwidth))
 
     def helpext(name):
         try:
@@ -1549,12 +1533,11 @@
             raise error.UnknownCommand(name)
 
         doc = gettext(mod.__doc__) or _('no help text available')
-        doc = doc.splitlines(0)
-        ui.write(_('%s extension - %s\n') % (name.split('.')[-1], doc[0]))
-        for d in doc[1:]:
-            ui.write(d, '\n')
-
-        ui.status('\n')
+        head, tail = doc.split('\n', 1)
+        ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
+        if tail:
+            ui.write(minirst.format(tail, textwidth))
+            ui.status('\n\n')
 
         try:
             ct = mod.cmdtable
@@ -1629,16 +1612,15 @@
              rev=None, num=None, id=None, branch=None, tags=None):
     """identify the working copy or specified revision
 
-    With no revision, print a summary of the current state of the
-    repository.
-
-    Specifying a path to a repository root or Mercurial bundle will
-    cause lookup to operate on that repository/bundle.
-
-    This summary identifies the repository state using one or two
-    parent hash identifiers, followed by a "+" if there are
-    uncommitted changes in the working directory, a list of tags for
-    this revision and a branch name for non-default branches.
+    With no revision, print a summary of the current state of the repository.
+
+    Specifying a path to a repository root or Mercurial bundle will cause
+    lookup to operate on that repository/bundle.
+
+    This summary identifies the repository state using one or two parent hash
+    identifiers, followed by a "+" if there are uncommitted changes in the
+    working directory, a list of tags for this revision and a branch name for
+    non-default branches.
     """
 
     if not repo and not source:
@@ -1705,33 +1687,31 @@
 
     Import a list of patches and commit them individually.
 
-    If there are outstanding changes in the working directory, import
-    will abort unless given the -f/--force flag.
-
-    You can import a patch straight from a mail message. Even patches
-    as attachments work (to use the body part, it must have type
-    text/plain or text/x-patch). From and Subject headers of email
-    message are used as default committer and commit message. All
-    text/plain body parts before first diff are added to commit
-    message.
-
-    If the imported patch was generated by hg export, user and
-    description from patch override values from message headers and
-    body. Values given on command line with -m/--message and -u/--user
-    override these.
-
-    If --exact is specified, import will set the working directory to
-    the parent of each patch before applying it, and will abort if the
-    resulting changeset has a different ID than the one recorded in
-    the patch. This may happen due to character set problems or other
-    deficiencies in the text patch format.
-
-    With -s/--similarity, hg will attempt to discover renames and
-    copies in the patch in the same way as 'addremove'.
-
-    To read a patch from standard input, use "-" as the patch name. If
-    a URL is specified, the patch will be downloaded from it.
-    See 'hg help dates' for a list of formats valid for -d/--date.
+    If there are outstanding changes in the working directory, import will
+    abort unless given the -f/--force flag.
+
+    You can import a patch straight from a mail message. Even patches as
+    attachments work (to use the body part, it must have type text/plain or
+    text/x-patch). From and Subject headers of email message are used as
+    default committer and commit message. All text/plain body parts before
+    first diff are added to commit message.
+
+    If the imported patch was generated by hg export, user and description
+    from patch override values from message headers and body. Values given on
+    command line with -m/--message and -u/--user override these.
+
+    If --exact is specified, import will set the working directory to the
+    parent of each patch before applying it, and will abort if the resulting
+    changeset has a different ID than the one recorded in the patch. This may
+    happen due to character set problems or other deficiencies in the text
+    patch format.
+
+    With -s/--similarity, hg will attempt to discover renames and copies in
+    the patch in the same way as 'addremove'.
+
+    To read a patch from standard input, use "-" as the patch name. If a URL
+    is specified, the patch will be downloaded from it. See 'hg help dates'
+    for a list of formats valid for -d/--date.
     """
     patches = (patch1,) + patches
 
@@ -1831,12 +1811,12 @@
 def incoming(ui, repo, source="default", **opts):
     """show new changesets found in source
 
-    Show new changesets found in the specified path/URL or the default
-    pull location. These are the changesets that would have been pulled
-    if a pull at the time you issued this command.
-
-    For remote repository, using --bundle avoids downloading the
-    changesets twice if the incoming is followed by a pull.
+    Show new changesets found in the specified path/URL or the default pull
+    location. These are the changesets that would have been pulled if a pull
+    at the time you issued this command.
+
+    For remote repository, using --bundle avoids downloading the changesets
+    twice if the incoming is followed by a pull.
 
     See pull for valid source format details.
     """
@@ -1900,33 +1880,33 @@
 def init(ui, dest=".", **opts):
     """create a new repository in the given directory
 
-    Initialize a new repository in the given directory. If the given
-    directory does not exist, it will be created.
+    Initialize a new repository in the given directory. If the given directory
+    does not exist, it will be created.
 
     If no directory is given, the current directory is used.
 
-    It is possible to specify an ssh:// URL as the destination.
-    See 'hg help urls' for more information.
+    It is possible to specify an ssh:// URL as the destination. See 'hg help
+    urls' for more information.
     """
     hg.repository(cmdutil.remoteui(ui, opts), dest, create=1)
 
 def locate(ui, repo, *pats, **opts):
     """locate files matching specific patterns
 
-    Print files under Mercurial control in the working directory whose
-    names match the given patterns.
+    Print files under Mercurial control in the working directory whose names
+    match the given patterns.
 
     By default, this command searches all directories in the working
-    directory. To search just the current directory and its
-    subdirectories, use "--include .".
-
-    If no patterns are given to match, this command prints the names
-    of all files under Mercurial control in the working directory.
-
-    If you want to feed the output of this command into the "xargs"
-    command, use the -0 option to both this command and "xargs". This
-    will avoid the problem of "xargs" treating single filenames that
-    contain whitespace as multiple filenames.
+    directory. To search just the current directory and its subdirectories,
+    use "--include .".
+
+    If no patterns are given to match, this command prints the names of all
+    files under Mercurial control in the working directory.
+
+    If you want to feed the output of this command into the "xargs" command,
+    use the -0 option to both this command and "xargs". This will avoid the
+    problem of "xargs" treating single filenames that contain whitespace as
+    multiple filenames.
     """
     end = opts.get('print0') and '\0' or '\n'
     rev = opts.get('rev') or None
@@ -1948,30 +1928,29 @@
 def log(ui, repo, *pats, **opts):
     """show revision history of entire repository or files
 
-    Print the revision history of the specified files or the entire
-    project.
-
-    File history is shown without following rename or copy history of
-    files. Use -f/--follow with a filename to follow history across
-    renames and copies. --follow without a filename will only show
-    ancestors or descendants of the starting revision. --follow-first
-    only follows the first parent of merge revisions.
-
-    If no revision range is specified, the default is tip:0 unless
-    --follow is set, in which case the working directory parent is
-    used as the starting revision.
+    Print the revision history of the specified files or the entire project.
+
+    File history is shown without following rename or copy history of files.
+    Use -f/--follow with a filename to follow history across renames and
+    copies. --follow without a filename will only show ancestors or
+    descendants of the starting revision. --follow-first only follows the
+    first parent of merge revisions.
+
+    If no revision range is specified, the default is tip:0 unless --follow is
+    set, in which case the working directory parent is used as the starting
+    revision.
 
     See 'hg help dates' for a list of formats valid for -d/--date.
 
-    By default this command prints revision number and changeset id,
-    tags, non-trivial parents, user, date and time, and a summary for
-    each commit. When the -v/--verbose switch is used, the list of
-    changed files and full commit message are shown.
+    By default this command prints revision number and changeset id, tags,
+    non-trivial parents, user, date and time, and a summary for each commit.
+    When the -v/--verbose switch is used, the list of changed files and full
+    commit message are shown.
 
     NOTE: log -p/--patch may generate unexpected diff output for merge
-    changesets, as it will only compare the merge changeset against
-    its first parent. Also, only files different from BOTH parents
-    will appear in files:.
+    changesets, as it will only compare the merge changeset against its first
+    parent. Also, only files different from BOTH parents will appear in
+    files:.
     """
 
     get = util.cachefunc(lambda r: repo[r].changeset())
@@ -2074,9 +2053,9 @@
 def manifest(ui, repo, node=None, rev=None):
     """output the current or given revision of the project manifest
 
-    Print a list of version controlled files for the given revision.
-    If no revision is given, the first parent of the working directory
-    is used, or the null revision if no revision is checked out.
+    Print a list of version controlled files for the given revision. If no
+    revision is given, the first parent of the working directory is used, or
+    the null revision if no revision is checked out.
 
     With -v, print file permissions, symlink and executable bits.
     With --debug, print file revision hashes.
@@ -2100,18 +2079,17 @@
 def merge(ui, repo, node=None, **opts):
     """merge working directory with another revision
 
-    The current working directory is updated with all changes made in
-    the requested revision since the last common predecessor revision.
-
-    Files that changed between either parent are marked as changed for
-    the next commit and a commit must be performed before any further
-    updates to the repository are allowed. The next commit will have
-    two parents.
-
-    If no revision is specified, the working directory's parent is a
-    head revision, and the current branch contains exactly one other
-    head, the other head is merged with by default. Otherwise, an
-    explicit revision with which to merge with must be provided.
+    The current working directory is updated with all changes made in the
+    requested revision since the last common predecessor revision.
+
+    Files that changed between either parent are marked as changed for the
+    next commit and a commit must be performed before any further updates to
+    the repository are allowed. The next commit will have two parents.
+
+    If no revision is specified, the working directory's parent is a head
+    revision, and the current branch contains exactly one other head, the
+    other head is merged with by default. Otherwise, an explicit revision with
+    which to merge with must be provided.
     """
 
     if opts.get('rev') and node:
@@ -2158,9 +2136,9 @@
 def outgoing(ui, repo, dest=None, **opts):
     """show changesets not found in destination
 
-    Show changesets not found in the specified destination repository
-    or the default push location. These are the changesets that would
-    be pushed if a push was requested.
+    Show changesets not found in the specified destination repository or the
+    default push location. These are the changesets that would be pushed if a
+    push was requested.
 
     See pull for valid destination format details.
     """
@@ -2193,11 +2171,10 @@
 def parents(ui, repo, file_=None, **opts):
     """show the parents of the working directory or revision
 
-    Print the working directory's parent revisions. If a revision is
-    given via -r/--rev, the parent of that revision will be printed.
-    If a file argument is given, the revision in which the file was
-    last changed (before the working directory revision or the
-    argument to --rev if given) is printed.
+    Print the working directory's parent revisions. If a revision is given via
+    -r/--rev, the parent of that revision will be printed. If a file argument
+    is given, the revision in which the file was last changed (before the
+    working directory revision or the argument to --rev if given) is printed.
     """
     rev = opts.get('rev')
     if rev:
@@ -2233,11 +2210,11 @@
 def paths(ui, repo, search=None):
     """show aliases for remote repositories
 
-    Show definition of symbolic path name NAME. If no name is given,
-    show definition of all available names.
-
-    Path names are defined in the [paths] section of /etc/mercurial/hgrc
-    and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
+    Show definition of symbolic path name NAME. If no name is given, show
+    definition of all available names.
+
+    Path names are defined in the [paths] section of /etc/mercurial/hgrc and
+    $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
 
     See 'hg help urls' for more information.
     """
@@ -2270,18 +2247,18 @@
 
     Pull changes from a remote repository to a local one.
 
-    This finds all changes from the repository at the specified path
-    or URL and adds them to a local repository (the current one unless
-    -R is specified). By default, this does not update the copy of the
-    project in the working directory.
-
-    Use hg incoming if you want to see what would have been added by a
-    pull at the time you issued this command. If you then decide to
-    added those changes to the repository, you should use pull -r X
-    where X is the last changeset listed by hg incoming.
-
-    If SOURCE is omitted, the 'default' path will be used.
-    See 'hg help urls' for more information.
+    This finds all changes from the repository at the specified path or URL
+    and adds them to a local repository (the current one unless -R is
+    specified). By default, this does not update the copy of the project in
+    the working directory.
+
+    Use hg incoming if you want to see what would have been added by a pull at
+    the time you issued this command. If you then decide to added those
+    changes to the repository, you should use pull -r X where X is the last
+    changeset listed by hg incoming.
+
+    If SOURCE is omitted, the 'default' path will be used. See 'hg help urls'
+    for more information.
     """
     source, revs, checkout = hg.parseurl(ui.expandpath(source), opts.get('rev'))
     other = hg.repository(cmdutil.remoteui(repo, opts), source)
@@ -2302,20 +2279,19 @@
 
     Push changes from the local repository to the given destination.
 
-    This is the symmetrical operation for pull. It moves changes from
-    the current repository to a different one. If the destination is
-    local this is identical to a pull in that directory from the
-    current one.
+    This is the symmetrical operation for pull. It moves changes from the
+    current repository to a different one. If the destination is local this is
+    identical to a pull in that directory from the current one.
 
     By default, push will refuse to run if it detects the result would
-    increase the number of remote heads. This generally indicates the
-    user forgot to pull and merge before pushing.
-
-    If -r/--rev is used, the named revision and all its ancestors will
-    be pushed to the remote repository.
-
-    Please see 'hg help urls' for important details about ssh://
-    URLs. If DESTINATION is omitted, a default path will be used.
+    increase the number of remote heads. This generally indicates the user
+    forgot to pull and merge before pushing.
+
+    If -r/--rev is used, the named revision and all its ancestors will be
+    pushed to the remote repository.
+
+    Please see 'hg help urls' for important details about ssh:// URLs. If
+    DESTINATION is omitted, a default path will be used.
     """
     dest, revs, checkout = hg.parseurl(
         ui.expandpath(dest or 'default-push', dest or 'default'), opts.get('rev'))
@@ -2338,9 +2314,8 @@
 
     Recover from an interrupted commit or pull.
 
-    This command tries to fix the repository status after an
-    interrupted operation. It should only be necessary when Mercurial
-    suggests it.
+    This command tries to fix the repository status after an interrupted
+    operation. It should only be necessary when Mercurial suggests it.
     """
     if repo.recover():
         return hg.verify(repo)
@@ -2351,26 +2326,25 @@
 
     Schedule the indicated files for removal from the repository.
 
-    This only removes files from the current branch, not from the
-    entire project history. -A/--after can be used to remove only
-    files that have already been deleted, -f/--force can be used to
-    force deletion, and -Af can be used to remove files from the next
-    revision without deleting them from the working directory.
-
-    The following table details the behavior of remove for different
-    file states (columns) and option combinations (rows). The file
-    states are Added [A], Clean [C], Modified [M] and Missing [!]
-    (as reported by hg status). The actions are Warn, Remove (from
-    branch) and Delete (from disk).
-
-           A  C  M  !
-    none   W  RD W  R
-    -f     R  RD RD R
-    -A     W  W  W  R
-    -Af    R  R  R  R
-
-    This command schedules the files to be removed at the next commit.
-    To undo a remove before that, see hg revert.
+    This only removes files from the current branch, not from the entire
+    project history. -A/--after can be used to remove only files that have
+    already been deleted, -f/--force can be used to force deletion, and -Af
+    can be used to remove files from the next revision without deleting them
+    from the working directory.
+
+    The following table details the behavior of remove for different file
+    states (columns) and option combinations (rows). The file states are Added
+    [A], Clean [C], Modified [M] and Missing [!] (as reported by hg status).
+    The actions are Warn, Remove (from branch) and Delete (from disk)::
+
+             A  C  M  !
+      none   W  RD W  R
+      -f     R  RD RD R
+      -A     W  W  W  R
+      -Af    R  R  R  R
+
+    This command schedules the files to be removed at the next commit. To undo
+    a remove before that, see hg revert.
     """
 
     after, force = opts.get('after'), opts.get('force')
@@ -2410,16 +2384,16 @@
 def rename(ui, repo, *pats, **opts):
     """rename files; equivalent of copy + remove
 
-    Mark dest as copies of sources; mark sources for deletion. If dest
-    is a directory, copies are put in that directory. If dest is a
-    file, there can only be one source.
-
-    By default, this command copies the contents of files as they
-    exist in the working directory. If invoked with -A/--after, the
-    operation is recorded, but no copying is performed.
-
-    This command takes effect at the next commit. To undo a rename
-    before that, see hg revert.
+    Mark dest as copies of sources; mark sources for deletion. If dest is a
+    directory, copies are put in that directory. If dest is a file, there can
+    only be one source.
+
+    By default, this command copies the contents of files as they exist in the
+    working directory. If invoked with -A/--after, the operation is recorded,
+    but no copying is performed.
+
+    This command takes effect at the next commit. To undo a rename before
+    that, see hg revert.
     """
     wlock = repo.wlock(False)
     try:
@@ -2431,20 +2405,21 @@
     """retry file merges from a merge or update
 
     This command will cleanly retry unresolved file merges using file
-    revisions preserved from the last update or merge. To attempt to
-    resolve all unresolved files, use the -a/--all switch.
-
-    If a conflict is resolved manually, please note that the changes
-    will be overwritten if the merge is retried with resolve. The
-    -m/--mark switch should be used to mark the file as resolved.
-
-    This command also allows listing resolved files and manually
-    indicating whether or not files are resolved. All files must be
-    marked as resolved before a commit is permitted.
-
-    The codes used to show the status of files are:
-    U = unresolved
-    R = resolved
+    revisions preserved from the last update or merge. To attempt to resolve
+    all unresolved files, use the -a/--all switch.
+
+    If a conflict is resolved manually, please note that the changes will be
+    overwritten if the merge is retried with resolve. The -m/--mark switch
+    should be used to mark the file as resolved.
+
+    This command also allows listing resolved files and manually indicating
+    whether or not files are resolved. All files must be marked as resolved
+    before a commit is permitted.
+
+    The codes used to show the status of files are::
+
+      U = unresolved
+      R = resolved
     """
 
     all, mark, unmark, show = [opts.get(o) for o in 'all mark unmark list'.split()]
@@ -2485,35 +2460,33 @@
 def revert(ui, repo, *pats, **opts):
     """restore individual files or directories to an earlier state
 
-    (Use update -r to check out earlier revisions, revert does not
-    change the working directory parents.)
-
-    With no revision specified, revert the named files or directories
-    to the contents they had in the parent of the working directory.
-    This restores the contents of the affected files to an unmodified
-    state and unschedules adds, removes, copies, and renames. If the
-    working directory has two parents, you must explicitly specify the
-    revision to revert to.
-
-    Using the -r/--rev option, revert the given files or directories
-    to their contents as of a specific revision. This can be helpful
-    to "roll back" some or all of an earlier change. See 'hg help
-    dates' for a list of formats valid for -d/--date.
-
-    Revert modifies the working directory. It does not commit any
-    changes, or change the parent of the working directory. If you
-    revert to a revision other than the parent of the working
-    directory, the reverted files will thus appear modified
-    afterwards.
-
-    If a file has been deleted, it is restored. If the executable mode
-    of a file was changed, it is reset.
-
-    If names are given, all files matching the names are reverted.
-    If no arguments are given, no files are reverted.
-
-    Modified files are saved with a .orig suffix before reverting.
-    To disable these backups, use --no-backup.
+    (Use update -r to check out earlier revisions, revert does not change the
+    working directory parents.)
+
+    With no revision specified, revert the named files or directories to the
+    contents they had in the parent of the working directory. This restores
+    the contents of the affected files to an unmodified state and unschedules
+    adds, removes, copies, and renames. If the working directory has two
+    parents, you must explicitly specify the revision to revert to.
+
+    Using the -r/--rev option, revert the given files or directories to their
+    contents as of a specific revision. This can be helpful to "roll back"
+    some or all of an earlier change. See 'hg help dates' for a list of
+    formats valid for -d/--date.
+
+    Revert modifies the working directory. It does not commit any changes, or
+    change the parent of the working directory. If you revert to a revision
+    other than the parent of the working directory, the reverted files will
+    thus appear modified afterwards.
+
+    If a file has been deleted, it is restored. If the executable mode of a
+    file was changed, it is reset.
+
+    If names are given, all files matching the names are reverted. If no
+    arguments are given, no files are reverted.
+
+    Modified files are saved with a .orig suffix before reverting. To disable
+    these backups, use --no-backup.
     """
 
     if opts["date"]:
@@ -2702,15 +2675,14 @@
     """roll back the last transaction
 
     This command should be used with care. There is only one level of
-    rollback, and there is no way to undo a rollback. It will also
-    restore the dirstate at the time of the last transaction, losing
-    any dirstate changes since that time. This command does not alter
-    the working directory.
-
-    Transactions are used to encapsulate the effects of all commands
-    that create new changesets or propagate existing changesets into a
-    repository. For example, the following commands are transactional,
-    and their effects can be rolled back:
+    rollback, and there is no way to undo a rollback. It will also restore the
+    dirstate at the time of the last transaction, losing any dirstate changes
+    since that time. This command does not alter the working directory.
+
+    Transactions are used to encapsulate the effects of all commands that
+    create new changesets or propagate existing changesets into a repository.
+    For example, the following commands are transactional, and their effects
+    can be rolled back::
 
       commit
       import
@@ -2718,12 +2690,12 @@
       push (with this repository as destination)
       unbundle
 
-    This command is not intended for use on public repositories. Once
-    changes are visible for pull by other users, rolling a transaction
-    back locally is ineffective (someone else may already have pulled
-    the changes). Furthermore, a race is possible with readers of the
-    repository; for example an in-progress pull from the repository
-    may fail if a rollback is performed.
+    This command is not intended for use on public repositories. Once changes
+    are visible for pull by other users, rolling a transaction back locally is
+    ineffective (someone else may already have pulled the changes).
+    Furthermore, a race is possible with readers of the repository; for
+    example an in-progress pull from the repository may fail if a rollback is
+    performed.
     """
     repo.rollback()
 
@@ -2739,9 +2711,8 @@
 
     Start a local HTTP repository browser and pull server.
 
-    By default, the server logs accesses to stdout and errors to
-    stderr. Use the -A/--accesslog and -E/--errorlog options to log to
-    files.
+    By default, the server logs accesses to stdout and errors to stderr. Use
+    the -A/--accesslog and -E/--errorlog options to log to files.
     """
 
     if opts["stdio"]:
@@ -2802,34 +2773,33 @@
 def status(ui, repo, *pats, **opts):
     """show changed files in the working directory
 
-    Show status of files in the repository. If names are given, only
-    files that match are shown. Files that are clean or ignored or
-    the source of a copy/move operation, are not listed unless
-    -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
-    Unless options described with "show only ..." are given, the
-    options -mardu are used.
-
-    Option -q/--quiet hides untracked (unknown and ignored) files
-    unless explicitly requested with -u/--unknown or -i/--ignored.
-
-    NOTE: status may appear to disagree with diff if permissions have
-    changed or a merge has occurred. The standard diff format does not
-    report permission changes and diff only reports changes relative
-    to one merge parent.
-
-    If one revision is given, it is used as the base revision.
-    If two revisions are given, the differences between them are
-    shown.
-
-    The codes used to show the status of files are:
-    M = modified
-    A = added
-    R = removed
-    C = clean
-    ! = missing (deleted by non-hg command, but still tracked)
-    ? = not tracked
-    I = ignored
-      = origin of the previous file listed as A (added)
+    Show status of files in the repository. If names are given, only files
+    that match are shown. Files that are clean or ignored or the source of a
+    copy/move operation, are not listed unless -c/--clean, -i/--ignored,
+    -C/--copies or -A/--all are given. Unless options described with "show
+    only ..." are given, the options -mardu are used.
+
+    Option -q/--quiet hides untracked (unknown and ignored) files unless
+    explicitly requested with -u/--unknown or -i/--ignored.
+
+    NOTE: status may appear to disagree with diff if permissions have changed
+    or a merge has occurred. The standard diff format does not report
+    permission changes and diff only reports changes relative to one merge
+    parent.
+
+    If one revision is given, it is used as the base revision. If two
+    revisions are given, the differences between them are shown.
+
+    The codes used to show the status of files are::
+
+      M = modified
+      A = added
+      R = removed
+      C = clean
+      ! = missing (deleted by non-hg command, but still tracked)
+      ? = not tracked
+      I = ignored
+        = origin of the previous file listed as A (added)
     """
 
     node1, node2 = cmdutil.revpair(repo, opts.get('rev'))
@@ -2877,18 +2847,17 @@
 
     Name a particular revision using <name>.
 
-    Tags are used to name particular revisions of the repository and are
-    very useful to compare different revisions, to go back to significant
-    earlier versions or to mark branch points as releases, etc.
-
-    If no revision is given, the parent of the working directory is
-    used, or tip if no revision is checked out.
-
-    To facilitate version control, distribution, and merging of tags,
-    they are stored as a file named ".hgtags" which is managed
-    similarly to other project files and can be hand-edited if
-    necessary. The file '.hg/localtags' is used for local tags (not
-    shared among repositories).
+    Tags are used to name particular revisions of the repository and are very
+    useful to compare different revisions, to go back to significant earlier
+    versions or to mark branch points as releases, etc.
+
+    If no revision is given, the parent of the working directory is used, or
+    tip if no revision is checked out.
+
+    To facilitate version control, distribution, and merging of tags, they are
+    stored as a file named ".hgtags" which is managed similarly to other
+    project files and can be hand-edited if necessary. The file
+    '.hg/localtags' is used for local tags (not shared among repositories).
 
     See 'hg help dates' for a list of formats valid for -d/--date.
     """
@@ -2943,8 +2912,8 @@
 def tags(ui, repo):
     """list repository tags
 
-    This lists both regular and local tags. When the -v/--verbose
-    switch is used, a third column "local" is printed for local tags.
+    This lists both regular and local tags. When the -v/--verbose switch is
+    used, a third column "local" is printed for local tags.
     """
 
     hexfunc = ui.debugflag and hex or short
@@ -2972,22 +2941,22 @@
 def tip(ui, repo, **opts):
     """show the tip revision
 
-    The tip revision (usually just called the tip) is the changeset
-    most recently added to the repository (and therefore the most
-    recently changed head).
-
-    If you have just made a commit, that commit will be the tip. If
-    you have just pulled changes from another repository, the tip of
-    that repository becomes the current tip. The "tip" tag is special
-    and cannot be renamed or assigned to a different changeset.
+    The tip revision (usually just called the tip) is the changeset most
+    recently added to the repository (and therefore the most recently changed
+    head).
+
+    If you have just made a commit, that commit will be the tip. If you have
+    just pulled changes from another repository, the tip of that repository
+    becomes the current tip. The "tip" tag is special and cannot be renamed or
+    assigned to a different changeset.
     """
     cmdutil.show_changeset(ui, repo, opts).show(repo[len(repo) - 1])
 
 def unbundle(ui, repo, fname1, *fnames, **opts):
     """apply one or more changegroup files
 
-    Apply one or more compressed changegroup files generated by the
-    bundle command.
+    Apply one or more compressed changegroup files generated by the bundle
+    command.
     """
     fnames = (fname1,) + fnames
 
@@ -3005,31 +2974,27 @@
 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
     """update working directory
 
-    Update the repository's working directory to the specified
-    revision, or the tip of the current branch if none is specified.
-    Use null as the revision to remove the working copy (like 'hg
-    clone -U').
-
-    When the working directory contains no uncommitted changes, it
-    will be replaced by the state of the requested revision from the
-    repository. When the requested revision is on a different branch,
-    the working directory will additionally be switched to that
-    branch.
-
-    When there are uncommitted changes, use option -C/--clean to
-    discard them, forcibly replacing the state of the working
-    directory with the requested revision. Alternately, use -c/--check
-    to abort.
-
-    When there are uncommitted changes and option -C/--clean is not
-    used, and the parent revision and requested revision are on the
-    same branch, and one of them is an ancestor of the other, then the
-    new working directory will contain the requested revision merged
-    with the uncommitted changes. Otherwise, the update will fail with
-    a suggestion to use 'merge' or 'update -C' instead.
-
-    If you want to update just one file to an older revision, use
-    revert.
+    Update the repository's working directory to the specified revision, or
+    the tip of the current branch if none is specified. Use null as the
+    revision to remove the working copy (like 'hg clone -U').
+
+    When the working directory contains no uncommitted changes, it will be
+    replaced by the state of the requested revision from the repository. When
+    the requested revision is on a different branch, the working directory
+    will additionally be switched to that branch.
+
+    When there are uncommitted changes, use option -C/--clean to discard them,
+    forcibly replacing the state of the working directory with the requested
+    revision. Alternately, use -c/--check to abort.
+
+    When there are uncommitted changes and option -C/--clean is not used, and
+    the parent revision and requested revision are on the same branch, and one
+    of them is an ancestor of the other, then the new working directory will
+    contain the requested revision merged with the uncommitted changes.
+    Otherwise, the update will fail with a suggestion to use 'merge' or
+    'update -C' instead.
+
+    If you want to update just one file to an older revision, use revert.
 
     See 'hg help dates' for a list of formats valid for -d/--date.
     """
@@ -3060,10 +3025,10 @@
 
     Verify the integrity of the current repository.
 
-    This will perform an extensive check of the repository's
-    integrity, validating the hashes and checksums of each entry in
-    the changelog, manifest, and tracked files, as well as the
-    integrity of their crosslinks and indices.
+    This will perform an extensive check of the repository's integrity,
+    validating the hashes and checksums of each entry in the changelog,
+    manifest, and tracked files, as well as the integrity of their crosslinks
+    and indices.
     """
     return hg.verify(repo)
 
--- a/mercurial/config.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/config.py	Thu Aug 06 18:48:00 2009 -0700
@@ -82,7 +82,7 @@
         line = 0
         cont = 0
 
-        for l in data.splitlines(1):
+        for l in data.splitlines(True):
             line += 1
             if cont:
                 m = contre.match(l)
--- a/mercurial/context.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/context.py	Thu Aug 06 18:48:00 2009 -0700
@@ -199,7 +199,9 @@
 
         assert (changeid is not None
                 or fileid is not None
-                or changectx is not None)
+                or changectx is not None), \
+                ("bad args: changeid=%r, fileid=%r, changectx=%r"
+                 % (changeid, fileid, changectx))
 
         if filelog:
             self._filelog = filelog
@@ -441,7 +443,7 @@
                         del hist[p]
             hist[f] = curr
 
-        return zip(hist[f][0], hist[f][1].splitlines(1))
+        return zip(hist[f][0], hist[f][1].splitlines(True))
 
     def ancestor(self, fc2):
         """
--- a/mercurial/copies.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/copies.py	Thu Aug 06 18:48:00 2009 -0700
@@ -42,7 +42,7 @@
         seen.add(s)
         if fc.path() != orig and fc.path() not in old:
             old[fc.path()] = (depth, fc.path()) # remember depth
-        if fc.rev() < limit and fc.rev() is not None:
+        if fc.rev() is not None and fc.rev() < limit:
             continue
         visit += [(p, depth - 1) for p in fc.parents()]
 
--- a/mercurial/dirstate.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/dirstate.py	Thu Aug 06 18:48:00 2009 -0700
@@ -59,7 +59,7 @@
     def _foldmap(self):
         f = {}
         for name in self._map:
-            f[os.path.normcase(name)] = name
+            f[util.realpath(self._join(name))] = name
         return f
 
     @propertycache
@@ -340,7 +340,7 @@
             self._ui.warn(_("not in dirstate: %s\n") % f)
 
     def _normalize(self, path, knownpath):
-        norm_path = os.path.normcase(path)
+        norm_path = util.realpath(self._join(path))
         fold_path = self._foldmap.get(norm_path, None)
         if fold_path is None:
             if knownpath or not os.path.exists(os.path.join(self._root, path)):
--- a/mercurial/extensions.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/extensions.py	Thu Aug 06 18:48:00 2009 -0700
@@ -166,10 +166,6 @@
 
 def enabled():
     '''return a dict of {name: desc} of extensions, and the max name length'''
-
-    if not enabled:
-        return {}, 0
-
     exts = {}
     maxlength = 0
     exthelps = []
@@ -177,6 +173,6 @@
         doc = (gettext(ext.__doc__) or _('(no help text available)'))
         ename = ename.split('.')[-1]
         maxlength = max(len(ename), maxlength)
-        exts[ename] = doc.splitlines(0)[0].strip()
+        exts[ename] = doc.splitlines()[0].strip()
 
     return exts, maxlength
--- a/mercurial/filemerge.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/filemerge.py	Thu Aug 06 18:48:00 2009 -0700
@@ -145,9 +145,9 @@
 
     if not tool or tool == 'internal:prompt':
         tool = "internal:local"
-        if ui.prompt(_(" no tool found to merge %s\n"
-                       "keep (l)ocal or take (o)ther?") % fd,
-                     (_("&Local"), _("&Other")), _("l")) != _("l"):
+        if ui.promptchoice(_(" no tool found to merge %s\n"
+                             "keep (l)ocal or take (o)ther?") % fd,
+                           (_("&Local"), _("&Other")), 0):
             tool = "internal:other"
     if tool == "internal:local":
         return 0
@@ -213,9 +213,9 @@
 
     if not r and _toolbool(ui, tool, "checkchanged"):
         if filecmp.cmp(repo.wjoin(fd), back):
-            if ui.prompt(_(" output file %s appears unchanged\n"
-                "was merge successful (yn)?") % fd,
-                (_("&Yes"), _("&No")), _("n")) != _("y"):
+            if ui.promptchoice(_(" output file %s appears unchanged\n"
+                                 "was merge successful (yn)?") % fd,
+                               (_("&Yes"), _("&No")), 1):
                 r = 1
 
     if _toolbool(ui, tool, "fixeol"):
--- a/mercurial/help.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/help.py	Thu Aug 06 18:48:00 2009 -0700
@@ -43,41 +43,39 @@
     '''return a text listing of the given extensions'''
     if not exts:
         return ''
-    result = '\n%s\n\n' % header
+    # TODO: literal block is wrong, should be a field list or a simple table.
+    result = '\n%s\n\n ::\n\n' % header
     for name, desc in sorted(exts.iteritems()):
-        desc = util.wrap(desc, maxlength + 4)
-        result += ' %s   %s\n' % (name.ljust(maxlength), desc)
+        desc = util.wrap(desc, maxlength + 5)
+        result += '  %s   %s\n' % (name.ljust(maxlength), desc)
     return result
 
 def extshelp():
     doc = _(r'''
     Mercurial has the ability to add new features through the use of
-    extensions. Extensions may add new commands, add options to
-    existing commands, change the default behavior of commands, or
-    implement hooks.
+    extensions. Extensions may add new commands, add options to existing
+    commands, change the default behavior of commands, or implement hooks.
 
-    Extensions are not loaded by default for a variety of reasons:
-    they can increase startup overhead; they may be meant for
-    advanced usage only; they may provide potentially dangerous
-    abilities (such as letting you destroy or modify history); they
-    might not be ready for prime time; or they may alter some
-    usual behaviors of stock Mercurial. It is thus up to the user to
-    activate extensions as needed.
+    Extensions are not loaded by default for a variety of reasons: they can
+    increase startup overhead; they may be meant for advanced usage only; they
+    may provide potentially dangerous abilities (such as letting you destroy
+    or modify history); they might not be ready for prime time; or they may
+    alter some usual behaviors of stock Mercurial. It is thus up to the user
+    to activate extensions as needed.
 
-    To enable the "foo" extension, either shipped with Mercurial
-    or in the Python search path, create an entry for it in your
-    hgrc, like this:
+    To enable the "foo" extension, either shipped with Mercurial or in the
+    Python search path, create an entry for it in your hgrc, like this::
 
       [extensions]
       foo =
 
-    You may also specify the full path to an extension:
+    You may also specify the full path to an extension::
 
       [extensions]
       myfeature = ~/.hgext/myfeature.py
 
-    To explicitly disable an extension enabled in an hgrc of broader
-    scope, prepend its path with !:
+    To explicitly disable an extension enabled in an hgrc of broader scope,
+    prepend its path with !::
 
       [extensions]
       # disabling extension bar residing in /path/to/extension/bar.py
@@ -98,225 +96,220 @@
     (["dates"], _("Date Formats"),
      _(r'''
     Some commands allow the user to specify a date, e.g.:
-    * backout, commit, import, tag: Specify the commit date.
-    * log, revert, update: Select revision(s) by date.
 
-    Many date formats are valid. Here are some examples:
+    - backout, commit, import, tag: Specify the commit date.
+    - log, revert, update: Select revision(s) by date.
+
+    Many date formats are valid. Here are some examples::
 
-    "Wed Dec 6 13:18:29 2006" (local timezone assumed)
-    "Dec 6 13:18 -0600" (year assumed, time offset provided)
-    "Dec 6 13:18 UTC" (UTC and GMT are aliases for +0000)
-    "Dec 6" (midnight)
-    "13:18" (today assumed)
-    "3:39" (3:39AM assumed)
-    "3:39pm" (15:39)
-    "2006-12-06 13:18:29" (ISO 8601 format)
-    "2006-12-6 13:18"
-    "2006-12-6"
-    "12-6"
-    "12/6"
-    "12/6/6" (Dec 6 2006)
+      "Wed Dec 6 13:18:29 2006" (local timezone assumed)
+      "Dec 6 13:18 -0600" (year assumed, time offset provided)
+      "Dec 6 13:18 UTC" (UTC and GMT are aliases for +0000)
+      "Dec 6" (midnight)
+      "13:18" (today assumed)
+      "3:39" (3:39AM assumed)
+      "3:39pm" (15:39)
+      "2006-12-06 13:18:29" (ISO 8601 format)
+      "2006-12-6 13:18"
+      "2006-12-6"
+      "12-6"
+      "12/6"
+      "12/6/6" (Dec 6 2006)
 
     Lastly, there is Mercurial's internal format:
 
     "1165432709 0" (Wed Dec 6 13:18:29 2006 UTC)
 
-    This is the internal representation format for dates. unixtime is
-    the number of seconds since the epoch (1970-01-01 00:00 UTC).
-    offset is the offset of the local timezone, in seconds west of UTC
-    (negative if the timezone is east of UTC).
+    This is the internal representation format for dates. unixtime is the
+    number of seconds since the epoch (1970-01-01 00:00 UTC). offset is the
+    offset of the local timezone, in seconds west of UTC (negative if the
+    timezone is east of UTC).
 
-    The log command also accepts date ranges:
+    The log command also accepts date ranges::
 
-    "<{datetime}" - at or before a given date/time
-    ">{datetime}" - on or after a given date/time
-    "{datetime} to {datetime}" - a date range, inclusive
-    "-{days}" - within a given number of days of today
+      "<{datetime}" - at or before a given date/time
+      ">{datetime}" - on or after a given date/time
+      "{datetime} to {datetime}" - a date range, inclusive
+      "-{days}" - within a given number of days of today
     ''')),
 
     (["patterns"], _("File Name Patterns"),
      _(r'''
-    Mercurial accepts several notations for identifying one or more
-    files at a time.
+    Mercurial accepts several notations for identifying one or more files at a
+    time.
 
-    By default, Mercurial treats filenames as shell-style extended
-    glob patterns.
+    By default, Mercurial treats filenames as shell-style extended glob
+    patterns.
 
     Alternate pattern notations must be specified explicitly.
 
-    To use a plain path name without any pattern matching, start it
-    with "path:". These path names must completely match starting at
-    the current repository root.
+    To use a plain path name without any pattern matching, start it with
+    "path:". These path names must completely match starting at the current
+    repository root.
 
-    To use an extended glob, start a name with "glob:". Globs are
-    rooted at the current directory; a glob such as "*.c" will only
-    match files in the current directory ending with ".c".
+    To use an extended glob, start a name with "glob:". Globs are rooted at
+    the current directory; a glob such as "``*.c``" will only match files in the
+    current directory ending with ".c".
 
-    The supported glob syntax extensions are "**" to match any string
-    across path separators and "{a,b}" to mean "a or b".
+    The supported glob syntax extensions are "``**``" to match any string across
+    path separators and "{a,b}" to mean "a or b".
 
-    To use a Perl/Python regular expression, start a name with "re:".
-    Regexp pattern matching is anchored at the root of the repository.
+    To use a Perl/Python regular expression, start a name with "re:". Regexp
+    pattern matching is anchored at the root of the repository.
 
-    Plain examples:
+    Plain examples::
 
-    path:foo/bar   a name bar in a directory named foo in the root of
-                   the repository
-    path:path:name a file or directory named "path:name"
+      path:foo/bar   a name bar in a directory named foo in the root of
+                     the repository
+      path:path:name a file or directory named "path:name"
 
-    Glob examples:
+    Glob examples::
 
-    glob:*.c       any name ending in ".c" in the current directory
-    *.c            any name ending in ".c" in the current directory
-    **.c           any name ending in ".c" in any subdirectory of the
-                   current directory including itself.
-    foo/*.c        any name ending in ".c" in the directory foo
-    foo/**.c       any name ending in ".c" in any subdirectory of foo
-                   including itself.
+      glob:*.c       any name ending in ".c" in the current directory
+      *.c            any name ending in ".c" in the current directory
+      **.c           any name ending in ".c" in any subdirectory of the
+                     current directory including itself.
+      foo/*.c        any name ending in ".c" in the directory foo
+      foo/**.c       any name ending in ".c" in any subdirectory of foo
+                     including itself.
 
-    Regexp examples:
+    Regexp examples::
 
-    re:.*\.c$      any name ending in ".c", anywhere in the repository
+      re:.*\.c$      any name ending in ".c", anywhere in the repository
 
     ''')),
 
     (['environment', 'env'], _('Environment Variables'),
      _(r'''
-HG::
-    Path to the 'hg' executable, automatically passed when running
-    hooks, extensions or external tools. If unset or empty, this is
-    the hg executable's name if it's frozen, or an executable named
-    'hg' (with %PATHEXT% [defaulting to COM/EXE/BAT/CMD] extensions on
-    Windows) is searched.
+HG
+    Path to the 'hg' executable, automatically passed when running hooks,
+    extensions or external tools. If unset or empty, this is the hg
+    executable's name if it's frozen, or an executable named 'hg' (with
+    %PATHEXT% [defaulting to COM/EXE/BAT/CMD] extensions on Windows) is
+    searched.
 
-HGEDITOR::
+HGEDITOR
     This is the name of the editor to run when committing. See EDITOR.
 
     (deprecated, use .hgrc)
 
-HGENCODING::
-    This overrides the default locale setting detected by Mercurial.
-    This setting is used to convert data including usernames,
-    changeset descriptions, tag names, and branches. This setting can
-    be overridden with the --encoding command-line option.
+HGENCODING
+    This overrides the default locale setting detected by Mercurial. This
+    setting is used to convert data including usernames, changeset
+    descriptions, tag names, and branches. This setting can be overridden with
+    the --encoding command-line option.
 
-HGENCODINGMODE::
-    This sets Mercurial's behavior for handling unknown characters
-    while transcoding user input. The default is "strict", which
-    causes Mercurial to abort if it can't map a character. Other
-    settings include "replace", which replaces unknown characters, and
-    "ignore", which drops them. This setting can be overridden with
-    the --encodingmode command-line option.
+HGENCODINGMODE
+    This sets Mercurial's behavior for handling unknown characters while
+    transcoding user input. The default is "strict", which causes Mercurial to
+    abort if it can't map a character. Other settings include "replace", which
+    replaces unknown characters, and "ignore", which drops them. This setting
+    can be overridden with the --encodingmode command-line option.
 
-HGMERGE::
-    An executable to use for resolving merge conflicts. The program
-    will be executed with three arguments: local file, remote file,
-    ancestor file.
+HGMERGE
+    An executable to use for resolving merge conflicts. The program will be
+    executed with three arguments: local file, remote file, ancestor file.
 
     (deprecated, use .hgrc)
 
-HGRCPATH::
-    A list of files or directories to search for hgrc files. Item
-    separator is ":" on Unix, ";" on Windows. If HGRCPATH is not set,
-    platform default search path is used. If empty, only the .hg/hgrc
-    from the current repository is read.
+HGRCPATH
+    A list of files or directories to search for hgrc files. Item separator is
+    ":" on Unix, ";" on Windows. If HGRCPATH is not set, platform default
+    search path is used. If empty, only the .hg/hgrc from the current
+    repository is read.
 
     For each element in HGRCPATH:
-    * if it's a directory, all files ending with .rc are added
-    * otherwise, the file itself will be added
+
+    - if it's a directory, all files ending with .rc are added
+    - otherwise, the file itself will be added
 
-HGUSER::
-    This is the string used as the author of a commit. If not set,
-    available values will be considered in this order:
+HGUSER
+    This is the string used as the author of a commit. If not set, available
+    values will be considered in this order:
 
-    * HGUSER (deprecated)
-    * hgrc files from the HGRCPATH
-    * EMAIL
-    * interactive prompt
-    * LOGNAME (with '@hostname' appended)
+    - HGUSER (deprecated)
+    - hgrc files from the HGRCPATH
+    - EMAIL
+    - interactive prompt
+    - LOGNAME (with '@hostname' appended)
 
     (deprecated, use .hgrc)
 
-EMAIL::
+EMAIL
     May be used as the author of a commit; see HGUSER.
 
-LOGNAME::
+LOGNAME
     May be used as the author of a commit; see HGUSER.
 
-VISUAL::
+VISUAL
     This is the name of the editor to use when committing. See EDITOR.
 
-EDITOR::
-    Sometimes Mercurial needs to open a text file in an editor for a
-    user to modify, for example when writing commit messages. The
-    editor it uses is determined by looking at the environment
-    variables HGEDITOR, VISUAL and EDITOR, in that order. The first
-    non-empty one is chosen. If all of them are empty, the editor
-    defaults to 'vi'.
+EDITOR
+    Sometimes Mercurial needs to open a text file in an editor for a user to
+    modify, for example when writing commit messages. The editor it uses is
+    determined by looking at the environment variables HGEDITOR, VISUAL and
+    EDITOR, in that order. The first non-empty one is chosen. If all of them
+    are empty, the editor defaults to 'vi'.
 
-PYTHONPATH::
-    This is used by Python to find imported modules and may need to be
-    set appropriately if this Mercurial is not installed system-wide.
+PYTHONPATH
+    This is used by Python to find imported modules and may need to be set
+    appropriately if this Mercurial is not installed system-wide.
     ''')),
 
     (['revs', 'revisions'], _('Specifying Single Revisions'),
      _(r'''
     Mercurial supports several ways to specify individual revisions.
 
-    A plain integer is treated as a revision number. Negative integers
-    are treated as sequential offsets from the tip, with -1 denoting
-    the tip, -2 denoting the revision prior to the tip, and so forth.
+    A plain integer is treated as a revision number. Negative integers are
+    treated as topological offsets from the tip, with -1 denoting the tip. As
+    such, negative numbers are only useful if you've memorized your local tree
+    numbers and want to save typing a single digit. This editor suggests copy
+    and paste.
 
-    A 40-digit hexadecimal string is treated as a unique revision
-    identifier.
+    A 40-digit hexadecimal string is treated as a unique revision identifier.
 
-    A hexadecimal string less than 40 characters long is treated as a
-    unique revision identifier and is referred to as a short-form
-    identifier. A short-form identifier is only valid if it is the
-    prefix of exactly one full-length identifier.
+    A hexadecimal string less than 40 characters long is treated as a unique
+    revision identifier, and referred to as a short-form identifier. A
+    short-form identifier is only valid if it is the prefix of exactly one
+    full-length identifier.
 
-    Any other string is treated as a tag or branch name. A tag name is
-    a symbolic name associated with a revision identifier. A branch
-    name denotes the tipmost revision of that branch. Tag and branch
-    names must not contain the ":" character.
+    Any other string is treated as a tag name, which is a symbolic name
+    associated with a revision identifier. Tag names may not contain the ":"
+    character.
 
-    The reserved name "tip" is a special tag that always identifies
-    the most recent revision.
+    The reserved name "tip" is a special tag that always identifies the most
+    recent revision.
 
-    The reserved name "null" indicates the null revision. This is the
-    revision of an empty repository, and the parent of revision 0.
+    The reserved name "null" indicates the null revision. This is the revision
+    of an empty repository, and the parent of revision 0.
 
-    The reserved name "." indicates the working directory parent. If
-    no working directory is checked out, it is equivalent to null. If
-    an uncommitted merge is in progress, "." is the revision of the
-    first parent.
+    The reserved name "." indicates the working directory parent. If no
+    working directory is checked out, it is equivalent to null. If an
+    uncommitted merge is in progress, "." is the revision of the first parent.
     ''')),
 
     (['mrevs', 'multirevs'], _('Specifying Multiple Revisions'),
      _(r'''
-    When Mercurial accepts more than one revision, they may be
-    specified individually, or provided as a topologically continuous
-    range, separated by the ":" character.
+    When Mercurial accepts more than one revision, they may be specified
+    individually, or provided as a topologically continuous range, separated
+    by the ":" character.
 
-    The syntax of range notation is [BEGIN]:[END], where BEGIN and END
-    are revision identifiers. Both BEGIN and END are optional. If
-    BEGIN is not specified, it defaults to revision number 0. If END
-    is not specified, it defaults to the tip. The range ":" thus means
-    "all revisions".
+    The syntax of range notation is [BEGIN]:[END], where BEGIN and END are
+    revision identifiers. Both BEGIN and END are optional. If BEGIN is not
+    specified, it defaults to revision number 0. If END is not specified, it
+    defaults to the tip. The range ":" thus means "all revisions".
 
-    If BEGIN is greater than END, revisions are treated in reverse
-    order.
+    If BEGIN is greater than END, revisions are treated in reverse order.
 
-    A range acts as a closed interval. This means that a range of 3:5
-    gives 3, 4 and 5. Similarly, a range of 9:6 gives 9, 8, 7, and 6.
+    A range acts as a closed interval. This means that a range of 3:5 gives 3,
+    4 and 5. Similarly, a range of 9:6 gives 9, 8, 7, and 6.
     ''')),
 
     (['diffs'], _('Diff Formats'),
      _(r'''
-    Mercurial's default format for showing changes between two
-    versions of a file is compatible with the unified format of GNU
-    diff, which can be used by GNU patch and many other standard
-    tools.
+    Mercurial's default format for showing changes between two versions of a
+    file is compatible with the unified format of GNU diff, which can be used
+    by GNU patch and many other standard tools.
 
     While this standard format is often enough, it does not encode the
     following information:
@@ -326,127 +319,121 @@
      - changes in binary files
      - creation or deletion of empty files
 
-    Mercurial also supports the extended diff format from the git VCS
-    which addresses these limitations. The git diff format is not
-    produced by default because a few widespread tools still do not
-    understand this format.
+    Mercurial also supports the extended diff format from the git VCS which
+    addresses these limitations. The git diff format is not produced by
+    default because a few widespread tools still do not understand this
+    format.
 
-    This means that when generating diffs from a Mercurial repository
-    (e.g. with "hg export"), you should be careful about things like
-    file copies and renames or other things mentioned above, because
-    when applying a standard diff to a different repository, this
-    extra information is lost. Mercurial's internal operations (like
-    push and pull) are not affected by this, because they use an
-    internal binary format for communicating changes.
+    This means that when generating diffs from a Mercurial repository (e.g.
+    with "hg export"), you should be careful about things like file copies and
+    renames or other things mentioned above, because when applying a standard
+    diff to a different repository, this extra information is lost.
+    Mercurial's internal operations (like push and pull) are not affected by
+    this, because they use an internal binary format for communicating
+    changes.
 
-    To make Mercurial produce the git extended diff format, use the
-    --git option available for many commands, or set 'git = True' in
-    the [diff] section of your hgrc. You do not need to set this
-    option when importing diffs in this format or using them in the mq
-    extension.
+    To make Mercurial produce the git extended diff format, use the --git
+    option available for many commands, or set 'git = True' in the [diff]
+    section of your hgrc. You do not need to set this option when importing
+    diffs in this format or using them in the mq extension.
     ''')),
     (['templating'], _('Template Usage'),
      _(r'''
-    Mercurial allows you to customize output of commands through
-    templates. You can either pass in a template from the command
-    line, via the --template option, or select an existing
-    template-style (--style).
+    Mercurial allows you to customize output of commands through templates.
+    You can either pass in a template from the command line, via the
+    --template option, or select an existing template-style (--style).
 
-    You can customize output for any "log-like" command: log,
-    outgoing, incoming, tip, parents, heads and glog.
+    You can customize output for any "log-like" command: log, outgoing,
+    incoming, tip, parents, heads and glog.
 
-    Three styles are packaged with Mercurial: default (the style used
-    when no explicit preference is passed), compact and changelog.
-    Usage:
+    Three styles are packaged with Mercurial: default (the style used when no
+    explicit preference is passed), compact and changelog. Usage:
 
         $ hg log -r1 --style changelog
 
-    A template is a piece of text, with markup to invoke variable
-    expansion:
+    A template is a piece of text, with markup to invoke variable expansion:
 
         $ hg log -r1 --template "{node}\n"
         b56ce7b07c52de7d5fd79fb89701ea538af65746
 
-    Strings in curly braces are called keywords. The availability of
-    keywords depends on the exact context of the templater. These
-    keywords are usually available for templating a log-like command:
+    Strings in curly braces are called keywords. The availability of keywords
+    depends on the exact context of the templater. These keywords are usually
+    available for templating a log-like command:
 
     - author: String. The unmodified author of the changeset.
-    - branches: String. The name of the branch on which the changeset
-          was committed. Will be empty if the branch name was default.
+    - branches: String. The name of the branch on which the changeset was
+      committed. Will be empty if the branch name was default.
     - date: Date information. The date when the changeset was committed.
     - desc: String. The text of the changeset description.
-    - diffstat: String. Statistics of changes with the following
-          format: "modified files: +added/-removed lines"
-    - files: List of strings. All files modified, added, or removed by
-          this changeset.
+    - diffstat: String. Statistics of changes with the following format:
+      "modified files: +added/-removed lines"
+    - files: List of strings. All files modified, added, or removed by this
+      changeset.
     - file_adds: List of strings. Files added by this changeset.
     - file_mods: List of strings. Files modified by this changeset.
     - file_dels: List of strings. Files removed by this changeset.
-    - node: String. The changeset identification hash, as a
-          40-character hexadecimal string.
+    - node: String. The changeset identification hash, as a 40-character
+      hexadecimal string.
     - parents: List of strings. The parents of the changeset.
     - rev: Integer. The repository-local changeset revision number.
     - tags: List of strings. Any tags associated with the changeset.
 
-    The "date" keyword does not produce human-readable output. If you
-    want to use a date in your output, you can use a filter to process
-    it. Filters are functions which return a string based on the input
-    variable. You can also use a chain of filters to get the desired
-    output:
+    The "date" keyword does not produce human-readable output. If you want to
+    use a date in your output, you can use a filter to process it. Filters are
+    functions which return a string based on the input variable. You can also
+    use a chain of filters to get the desired output:
 
        $ hg tip --template "{date|isodate}\n"
        2008-08-21 18:22 +0000
 
     List of filters:
 
-    - addbreaks: Any text. Add an XHTML "<br />" tag before the end of
-          every line except the last.
-    - age: Date. Returns a human-readable date/time difference between
-          the given date/time and the current date/time.
-    - basename: Any text. Treats the text as a path, and returns the
-          last component of the path after splitting by the path
-          separator (ignoring trailing separators). For example,
-          "foo/bar/baz" becomes "baz" and "foo/bar//" becomes "bar".
+    - addbreaks: Any text. Add an XHTML "<br />" tag before the end of every
+      line except the last.
+    - age: Date. Returns a human-readable date/time difference between the
+      given date/time and the current date/time.
+    - basename: Any text. Treats the text as a path, and returns the last
+      component of the path after splitting by the path separator (ignoring
+      trailing separators). For example, "foo/bar/baz" becomes "baz" and
+      "foo/bar//" becomes "bar".
     - stripdir: Treat the text as path and strip a directory level, if
-          possible. For example, "foo" and "foo/bar" becomes "foo".
-    - date: Date. Returns a date in a Unix date format, including
-          the timezone: "Mon Sep 04 15:13:13 2006 0700".
-    - domain: Any text. Finds the first string that looks like an
-          email address, and extracts just the domain component.
-          Example: 'User <user@example.com>' becomes 'example.com'.
-    - email: Any text. Extracts the first string that looks like an
-          email address. Example: 'User <user@example.com>' becomes
-          'user@example.com'.
-    - escape: Any text. Replaces the special XML/XHTML characters "&",
-          "<" and ">" with XML entities.
+      possible. For example, "foo" and "foo/bar" becomes "foo".
+    - date: Date. Returns a date in a Unix date format, including the
+      timezone: "Mon Sep 04 15:13:13 2006 0700".
+    - domain: Any text. Finds the first string that looks like an email
+      address, and extracts just the domain component. Example: 'User
+      <user@example.com>' becomes 'example.com'.
+    - email: Any text. Extracts the first string that looks like an email
+      address. Example: 'User <user@example.com>' becomes 'user@example.com'.
+    - escape: Any text. Replaces the special XML/XHTML characters "&", "<" and
+      ">" with XML entities.
     - fill68: Any text. Wraps the text to fit in 68 columns.
     - fill76: Any text. Wraps the text to fit in 76 columns.
     - firstline: Any text. Returns the first line of text.
     - nonempty: Any text. Returns '(none)' if the string is empty.
-    - hgdate: Date. Returns the date as a pair of numbers:
-          "1157407993 25200" (Unix timestamp, timezone offset).
+    - hgdate: Date. Returns the date as a pair of numbers: "1157407993 25200"
+      (Unix timestamp, timezone offset).
     - isodate: Date. Returns the date in ISO 8601 format.
     - localdate: Date. Converts a date to local date.
-    - obfuscate: Any text. Returns the input text rendered as a
-          sequence of XML entities.
+    - obfuscate: Any text. Returns the input text rendered as a sequence of
+      XML entities.
     - person: Any text. Returns the text before an email address.
-    - rfc822date: Date. Returns a date using the same format used
-          in email headers.
-    - short: Changeset hash. Returns the short form of a changeset
-          hash, i.e. a 12-byte hexadecimal string.
+    - rfc822date: Date. Returns a date using the same format used in email
+      headers.
+    - short: Changeset hash. Returns the short form of a changeset hash, i.e.
+      a 12-byte hexadecimal string.
     - shortdate: Date. Returns a date like "2006-09-18".
     - strip: Any text. Strips all leading and trailing whitespace.
-    - tabindent: Any text. Returns the text, with every line except
-          the first starting with a tab character.
-    - urlescape: Any text. Escapes all "special" characters. For
-          example, "foo bar" becomes "foo%20bar".
+    - tabindent: Any text. Returns the text, with every line except the first
+      starting with a tab character.
+    - urlescape: Any text. Escapes all "special" characters. For example, "foo
+      bar" becomes "foo%20bar".
     - user: Any text. Returns the user portion of an email address.
     ''')),
 
     (['urls'], _('URL Paths'),
      _(r'''
-    Valid URLs are of the form:
+    Valid URLs are of the form::
 
       local/filesystem/path[#revision]
       file://local/filesystem/path[#revision]
@@ -454,57 +441,59 @@
       https://[user[:pass]@]host[:port]/[path][#revision]
       ssh://[user[:pass]@]host[:port]/[path][#revision]
 
-    Paths in the local filesystem can either point to Mercurial
-    repositories or to bundle files (as created by 'hg bundle' or
-    'hg incoming --bundle').
+    Paths in the local filesystem can either point to Mercurial repositories
+    or to bundle files (as created by 'hg bundle' or 'hg incoming --bundle').
 
-    An optional identifier after # indicates a particular branch, tag,
-    or changeset to use from the remote repository. See also 'hg help
-    revisions'.
+    An optional identifier after # indicates a particular branch, tag, or
+    changeset to use from the remote repository. See also 'hg help revisions'.
 
-    Some features, such as pushing to http:// and https:// URLs are
-    only possible if the feature is explicitly enabled on the remote
-    Mercurial server.
+    Some features, such as pushing to http:// and https:// URLs are only
+    possible if the feature is explicitly enabled on the remote Mercurial
+    server.
 
     Some notes about using SSH with Mercurial:
-    - SSH requires an accessible shell account on the destination
-      machine and a copy of hg in the remote path or specified with as
-      remotecmd.
-    - path is relative to the remote user's home directory by default.
-      Use an extra slash at the start of a path to specify an absolute path:
+
+    - SSH requires an accessible shell account on the destination machine and
+      a copy of hg in the remote path or specified with as remotecmd.
+    - path is relative to the remote user's home directory by default. Use an
+      extra slash at the start of a path to specify an absolute path::
+
         ssh://example.com//tmp/repository
-    - Mercurial doesn't use its own compression via SSH; the right
-      thing to do is to configure it in your ~/.ssh/config, e.g.:
+
+    - Mercurial doesn't use its own compression via SSH; the right thing to do
+      is to configure it in your ~/.ssh/config, e.g.::
+
         Host *.mylocalnetwork.example.com
           Compression no
         Host *
           Compression yes
-      Alternatively specify "ssh -C" as your ssh command in your hgrc
-      or with the --ssh command line option.
+
+      Alternatively specify "ssh -C" as your ssh command in your hgrc or with
+      the --ssh command line option.
+
+    These URLs can all be stored in your hgrc with path aliases under the
+    [paths] section like so::
 
-    These URLs can all be stored in your hgrc with path aliases under
-    the [paths] section like so:
-    [paths]
-    alias1 = URL1
-    alias2 = URL2
-    ...
+      [paths]
+      alias1 = URL1
+      alias2 = URL2
+      ...
 
-    You can then use the alias for any command that uses a URL (for
-    example 'hg pull alias1' would pull from the 'alias1' path).
+    You can then use the alias for any command that uses a URL (for example
+    'hg pull alias1' would pull from the 'alias1' path).
 
-    Two path aliases are special because they are used as defaults
-    when you do not provide the URL to a command:
+    Two path aliases are special because they are used as defaults when you do
+    not provide the URL to a command:
 
     default:
-      When you create a repository with hg clone, the clone command
-      saves the location of the source repository as the new
-      repository's 'default' path. This is then used when you omit
-      path from push- and pull-like commands (including incoming and
-      outgoing).
+      When you create a repository with hg clone, the clone command saves the
+      location of the source repository as the new repository's 'default'
+      path. This is then used when you omit path from push- and pull-like
+      commands (including incoming and outgoing).
 
     default-push:
-      The push command will look for a path named 'default-push', and
-      prefer it over 'default' if both are defined.
+      The push command will look for a path named 'default-push', and prefer
+      it over 'default' if both are defined.
     ''')),
     (["extensions"], _("Using additional features"), extshelp),
 )
--- a/mercurial/hg.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/hg.py	Thu Aug 06 18:48:00 2009 -0700
@@ -277,9 +277,9 @@
             revs = None
             if rev:
                 if 'lookup' not in src_repo.capabilities:
-                    raise util.Abort(_("src repository does not support revision "
-                                       "lookup and so doesn't support clone by "
-                                       "revision"))
+                    raise util.Abort(_("src repository does not support "
+                                       "revision lookup and so doesn't "
+                                       "support clone by revision"))
                 revs = [src_repo.lookup(r) for r in rev]
                 checkout = revs[0]
             if dest_repo.local():
--- a/mercurial/hgweb/common.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/hgweb/common.py	Thu Aug 06 18:48:00 2009 -0700
@@ -69,7 +69,7 @@
         os.stat(path)
         ct = mimetypes.guess_type(path)[0] or "text/plain"
         req.respond(HTTP_OK, ct, length = os.path.getsize(path))
-        return file(path, 'rb').read()
+        return open(path, 'rb').read()
     except TypeError:
         raise ErrorResponse(HTTP_SERVER_ERROR, 'illegal filename')
     except OSError, err:
--- a/mercurial/hgweb/protocol.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/hgweb/protocol.py	Thu Aug 06 18:48:00 2009 -0700
@@ -26,7 +26,7 @@
     try:
         r = hex(repo.lookup(req.form['key'][0]))
         success = 1
-    except Exception,inst:
+    except Exception, inst:
         r = str(inst)
         success = 0
     resp = "%s %s\n" % (success, r)
--- a/mercurial/hgweb/server.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/hgweb/server.py	Thu Aug 06 18:48:00 2009 -0700
@@ -35,7 +35,7 @@
         for msg in seq:
             self.handler.log_error("HG error:  %s", msg)
 
-class _hgwebhandler(object, BaseHTTPServer.BaseHTTPRequestHandler):
+class _hgwebhandler(BaseHTTPServer.BaseHTTPRequestHandler):
 
     url_scheme = 'http'
 
--- a/mercurial/hgweb/webcommands.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/hgweb/webcommands.py	Thu Aug 06 18:48:00 2009 -0700
@@ -65,7 +65,7 @@
         text = '(binary:%s)' % mt
 
     def lines():
-        for lineno, t in enumerate(text.splitlines(1)):
+        for lineno, t in enumerate(text.splitlines(True)):
             yield {"line": t,
                    "lineid": "l%d" % (lineno + 1),
                    "linenumber": "% 6d" % (lineno + 1),
@@ -339,7 +339,7 @@
     i.reverse()
     parity = paritygen(web.stripecount)
 
-    def entries(notip=False,limit=0, **map):
+    def entries(notip=False, limit=0, **map):
         count = 0
         for k, n in i:
             if notip and k == "tip":
--- a/mercurial/ignore.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/ignore.py	Thu Aug 06 18:48:00 2009 -0700
@@ -11,8 +11,16 @@
 
 _commentre = None
 
-def _parselines(fp):
-    for line in fp:
+def ignorepats(lines):
+    '''parse lines (iterable) of .hgignore text, returning a tuple of
+    (patterns, parse errors). These patterns should be given to compile()
+    to be validated and converted into a match function.'''
+    syntaxes = {'re': 'relre:', 'regexp': 'relre:', 'glob': 'relglob:'}
+    syntax = 'relre:'
+    patterns = []
+    warnings = []
+
+    for line in lines:
         if "#" in line:
             global _commentre
             if not _commentre:
@@ -22,11 +30,30 @@
             # fixup properly escaped comments that survived the above
             line = line.replace("\\#", "#")
         line = line.rstrip()
-        if line:
-            yield line
+        if not line:
+            continue
+
+        if line.startswith('syntax:'):
+            s = line[7:].strip()
+            try:
+                syntax = syntaxes[s]
+            except KeyError:
+                warnings.append(_("ignoring invalid syntax '%s'") % s)
+            continue
+        pat = syntax + line
+        for s, rels in syntaxes.iteritems():
+            if line.startswith(rels):
+                pat = line
+                break
+            elif line.startswith(s+':'):
+                pat = rels + line[len(s)+1:]
+                break
+        patterns.append(pat)
+
+    return patterns, warnings
 
 def ignore(root, files, warn):
-    '''return the contents of .hgignore files as a list of patterns.
+    '''return matcher covering patterns in 'files'.
 
     the files parsed for patterns include:
     .hgignore in the repository root
@@ -45,30 +72,14 @@
     glob:pattern   # non-rooted glob
     pattern        # pattern of the current default type'''
 
-    syntaxes = {'re': 'relre:', 'regexp': 'relre:', 'glob': 'relglob:'}
     pats = {}
     for f in files:
         try:
             pats[f] = []
             fp = open(f)
-            syntax = 'relre:'
-            for line in _parselines(fp):
-                if line.startswith('syntax:'):
-                    s = line[7:].strip()
-                    try:
-                        syntax = syntaxes[s]
-                    except KeyError:
-                        warn(_("%s: ignoring invalid syntax '%s'\n") % (f, s))
-                    continue
-                pat = syntax + line
-                for s, rels in syntaxes.iteritems():
-                    if line.startswith(rels):
-                        pat = line
-                        break
-                    elif line.startswith(s+':'):
-                        pat = rels + line[len(s)+1:]
-                        break
-                pats[f].append(pat)
+            pats[f], warnings = ignorepats(fp)
+            for warning in warnings:
+                warn("%s: %s\n" % (f, warning))
         except IOError, inst:
             if f != files[0]:
                 warn(_("skipping unreadable ignore file '%s': %s\n") %
--- a/mercurial/localrepo.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/localrepo.py	Thu Aug 06 18:48:00 2009 -0700
@@ -13,6 +13,7 @@
 import util, extensions, hook, error
 import match as match_
 import merge as merge_
+import tags as tags_
 from lock import release
 import weakref, stat, errno, os, time, inspect
 propertycache = util.propertycache
@@ -89,8 +90,14 @@
         self.sjoin = self.store.join
         self.opener.createmode = self.store.createmode
 
-        self.tagscache = None
-        self._tagstypecache = None
+        # These two define the set of tags for this repository.  _tags
+        # maps tag name to node; _tagtypes maps tag name to 'global' or
+        # 'local'.  (Global tags are defined by .hgtags across all
+        # heads, and local tags are defined in .hg/localtags.)  They
+        # constitute the in-memory cache of tags.
+        self._tags = None
+        self._tagtypes = None
+
         self.branchcache = None
         self._ubranchcache = None  # UTF-8 version of branchcache
         self._branchcachetip = None
@@ -160,8 +167,8 @@
                 fp.write('\n')
             for name in names:
                 m = munge and munge(name) or name
-                if self._tagstypecache and name in self._tagstypecache:
-                    old = self.tagscache.get(name, nullid)
+                if self._tagtypes and name in self._tagtypes:
+                    old = self._tags.get(name, nullid)
                     fp.write('%s %s\n' % (hex(old), m))
                 fp.write('%s %s\n' % (hex(node), m))
             fp.close()
@@ -233,100 +240,43 @@
 
     def tags(self):
         '''return a mapping of tag to node'''
-        if self.tagscache:
-            return self.tagscache
+        if self._tags is None:
+            (self._tags, self._tagtypes) = self._findtags()
+
+        return self._tags
 
-        globaltags = {}
+    def _findtags(self):
+        '''Do the hard work of finding tags.  Return a pair of dicts
+        (tags, tagtypes) where tags maps tag name to node, and tagtypes
+        maps tag name to a string like \'global\' or \'local\'.
+        Subclasses or extensions are free to add their own tags, but
+        should be aware that the returned dicts will be retained for the
+        duration of the localrepo object.'''
+
+        # XXX what tagtype should subclasses/extensions use?  Currently
+        # mq and bookmarks add tags, but do not set the tagtype at all.
+        # Should each extension invent its own tag type?  Should there
+        # be one tagtype for all such "virtual" tags?  Or is the status
+        # quo fine?
+
+        alltags = {}                    # map tag name to (node, hist)
         tagtypes = {}
 
-        def readtags(lines, fn, tagtype):
-            filetags = {}
-            count = 0
-
-            def warn(msg):
-                self.ui.warn(_("%s, line %s: %s\n") % (fn, count, msg))
-
-            for l in lines:
-                count += 1
-                if not l:
-                    continue
-                s = l.split(" ", 1)
-                if len(s) != 2:
-                    warn(_("cannot parse entry"))
-                    continue
-                node, key = s
-                key = encoding.tolocal(key.strip()) # stored in UTF-8
-                try:
-                    bin_n = bin(node)
-                except TypeError:
-                    warn(_("node '%s' is not well formed") % node)
-                    continue
-                if bin_n not in self.changelog.nodemap:
-                    # silently ignore as pull -r might cause this
-                    continue
-
-                h = []
-                if key in filetags:
-                    n, h = filetags[key]
-                    h.append(n)
-                filetags[key] = (bin_n, h)
-
-            for k, nh in filetags.iteritems():
-                if k not in globaltags:
-                    globaltags[k] = nh
-                    tagtypes[k] = tagtype
-                    continue
+        tags_.findglobaltags(self.ui, self, alltags, tagtypes)
+        tags_.readlocaltags(self.ui, self, alltags, tagtypes)
 
-                # we prefer the global tag if:
-                #  it supercedes us OR
-                #  mutual supercedes and it has a higher rank
-                # otherwise we win because we're tip-most
-                an, ah = nh
-                bn, bh = globaltags[k]
-                if (bn != an and an in bh and
-                    (bn not in ah or len(bh) > len(ah))):
-                    an = bn
-                ah.extend([n for n in bh if n not in ah])
-                globaltags[k] = an, ah
-                tagtypes[k] = tagtype
-
-        seen = set()
-        f = None
-        ctxs = []
-        for node in self.heads():
-            try:
-                fnode = self[node].filenode('.hgtags')
-            except error.LookupError:
-                continue
-            if fnode not in seen:
-                seen.add(fnode)
-                if not f:
-                    f = self.filectx('.hgtags', fileid=fnode)
-                else:
-                    f = f.filectx(fnode)
-                ctxs.append(f)
-
-        # read the tags file from each head, ending with the tip
-        for f in reversed(ctxs):
-            readtags(f.data().splitlines(), f, "global")
-
-        try:
-            data = encoding.fromlocal(self.opener("localtags").read())
-            # localtags are stored in the local character set
-            # while the internal tag table is stored in UTF-8
-            readtags(data.splitlines(), "localtags", "local")
-        except IOError:
-            pass
-
-        self.tagscache = {}
-        self._tagstypecache = {}
-        for k, nh in globaltags.iteritems():
-            n = nh[0]
-            if n != nullid:
-                self.tagscache[k] = n
-            self._tagstypecache[k] = tagtypes[k]
-        self.tagscache['tip'] = self.changelog.tip()
-        return self.tagscache
+        # Build the return dicts.  Have to re-encode tag names because
+        # the tags module always uses UTF-8 (in order not to lose info
+        # writing to the cache), but the rest of Mercurial wants them in
+        # local encoding.
+        tags = {}
+        for (name, (node, hist)) in alltags.iteritems():
+            if node != nullid:
+                tags[encoding.tolocal(name)] = node
+        tags['tip'] = self.changelog.tip()
+        tagtypes = dict([(encoding.tolocal(name), value)
+                         for (name, value) in tagtypes.iteritems()])
+        return (tags, tagtypes)
 
     def tagtype(self, tagname):
         '''
@@ -339,7 +289,7 @@
 
         self.tags()
 
-        return self._tagstypecache.get(tagname)
+        return self._tagtypes.get(tagname)
 
     def tagslist(self):
         '''return a list of tags ordered by revision'''
@@ -668,6 +618,7 @@
                                  % encoding.tolocal(self.dirstate.branch()))
                 self.invalidate()
                 self.dirstate.invalidate()
+                self.destroyed()
             else:
                 self.ui.warn(_("no rollback information available\n"))
         finally:
@@ -677,8 +628,8 @@
         for a in "changelog manifest".split():
             if a in self.__dict__:
                 delattr(self, a)
-        self.tagscache = None
-        self._tagstypecache = None
+        self._tags = None
+        self._tagtypes = None
         self.nodetagscache = None
         self.branchcache = None
         self._ubranchcache = None
@@ -966,6 +917,25 @@
             del tr
             lock.release()
 
+    def destroyed(self):
+        '''Inform the repository that nodes have been destroyed.
+        Intended for use by strip and rollback, so there's a common
+        place for anything that has to be done after destroying history.'''
+        # XXX it might be nice if we could take the list of destroyed
+        # nodes, but I don't see an easy way for rollback() to do that
+
+        # Ensure the persistent tag cache is updated.  Doing it now
+        # means that the tag cache only has to worry about destroyed
+        # heads immediately after a strip/rollback.  That in turn
+        # guarantees that "cachetip == currenttip" (comparing both rev
+        # and node) always means no nodes have been added or destroyed.
+
+        # XXX this is suboptimal when qrefresh'ing: we strip the current
+        # head, refresh the tag cache, then immediately add a new head.
+        # But I think doing it this way is necessary for the "instant
+        # tag cache retrieval" case to work.
+        tags_.findglobaltags(self.ui, self, {}, {})
+
     def walk(self, match, node=None):
         '''
         walk recursively through the directory tree or a given
@@ -1708,24 +1678,13 @@
         def identity(x):
             return x
 
-        # A function generating function.  Sets up an environment for the
-        # inner function.
-        def cmp_by_rev_func(revlog):
-            # Compare two nodes by their revision number in the environment's
-            # revision history.  Since the revision number both represents the
-            # most efficient order to read the nodes in, and represents a
-            # topological sorting of the nodes, this function is often useful.
-            def cmp_by_rev(a, b):
-                return cmp(revlog.rev(a), revlog.rev(b))
-            return cmp_by_rev
-
         # If we determine that a particular file or manifest node must be a
         # node that the recipient of the changegroup will already have, we can
         # also assume the recipient will have all the parents.  This function
         # prunes them from the set of missing nodes.
         def prune_parents(revlog, hasset, msngset):
             haslst = list(hasset)
-            haslst.sort(cmp_by_rev_func(revlog))
+            haslst.sort(key=revlog.rev)
             for node in haslst:
                 parentlst = [p for p in revlog.parents(node) if p != nullid]
                 while parentlst:
@@ -1875,7 +1834,7 @@
             add_extra_nodes(1, msng_mnfst_set)
             msng_mnfst_lst = msng_mnfst_set.keys()
             # Sort the manifestnodes by revision number.
-            msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
+            msng_mnfst_lst.sort(key=mnfst.rev)
             # Create a generator for the manifestnodes that calls our lookup
             # and data collection functions back.
             group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
@@ -1913,7 +1872,7 @@
                     yield changegroup.chunkheader(len(fname))
                     yield fname
                     # Sort the filenodes by their revision #
-                    msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
+                    msng_filenode_lst.sort(key=filerevlog.rev)
                     # Create a group generator and only pass in a changenode
                     # lookup function as we need to collect no information
                     # from filenodes.
--- a/mercurial/lsprof.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/lsprof.py	Thu Aug 06 18:48:00 2009 -0700
@@ -26,12 +26,10 @@
         """XXX docstring"""
         if crit not in profiler_entry.__dict__:
             raise ValueError("Can't sort by %s" % crit)
-        self.data.sort(lambda b, a: cmp(getattr(a, crit),
-                                        getattr(b, crit)))
+        self.data.sort(key=lambda x: getattr(x, crit), reverse=True)
         for e in self.data:
             if e.calls:
-                e.calls.sort(lambda b, a: cmp(getattr(a, crit),
-                                              getattr(b, crit)))
+                e.calls.sort(key=lambda x: getattr(x, crit), reverse=True)
 
     def pprint(self, top=None, file=None, limit=None, climit=None):
         """XXX docstring"""
--- a/mercurial/match.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/match.py	Thu Aug 06 18:48:00 2009 -0700
@@ -5,7 +5,8 @@
 # This software may be used and distributed according to the terms of the
 # GNU General Public License version 2, incorporated herein by reference.
 
-import util, re
+import re
+import util
 
 class match(object):
     def __init__(self, root, cwd, patterns, include=[], exclude=[],
--- a/mercurial/merge.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/merge.py	Thu Aug 06 18:48:00 2009 -0700
@@ -131,11 +131,13 @@
         if m == n: # flags agree
             return m # unchanged
         if m and n and not a: # flags set, don't agree, differ from parent
-            r = repo.ui.prompt(
+            r = repo.ui.promptchoice(
                 _(" conflicting flags for %s\n"
                   "(n)one, e(x)ec or sym(l)ink?") % f,
-                (_("&None"), _("E&xec"), _("Sym&link")), _("n"))
-            return r != _("n") and r or ''
+                (_("&None"), _("E&xec"), _("Sym&link")), 0)
+            if r == 1: return "x" # Exec
+            if r == 2: return "l" # Symlink
+            return ""
         if m and m != a: # changed from a to m
             return m
         if n and n != a: # changed from a to n
@@ -191,10 +193,10 @@
                     f, f2, f, fmerge(f, f2, f2), False)
         elif f in ma: # clean, a different, no remote
             if n != ma[f]:
-                if repo.ui.prompt(
+                if repo.ui.promptchoice(
                     _(" local changed %s which remote deleted\n"
                       "use (c)hanged version or (d)elete?") % f,
-                    (_("&Changed"), _("&Delete")), _("c")) == _("d"):
+                    (_("&Changed"), _("&Delete")), 0):
                     act("prompt delete", "r", f)
                 else:
                     act("prompt keep", "a", f)
@@ -222,10 +224,10 @@
         elif f not in ma:
             act("remote created", "g", f, m2.flags(f))
         elif n != ma[f]:
-            if repo.ui.prompt(
+            if repo.ui.promptchoice(
                 _("remote changed %s which local deleted\n"
                   "use (c)hanged version or leave (d)eleted?") % f,
-                (_("&Changed"), _("&Deleted")), _("c")) == _("c"):
+                (_("&Changed"), _("&Deleted")), 0) == 0:
                 act("prompt recreating", "g", f, m2.flags(f))
 
     return action
@@ -288,7 +290,7 @@
                 continue
             f2, fd, flags, move = a[2:]
             r = ms.resolve(fd, wctx, mctx)
-            if r > 0:
+            if r is not None and r > 0:
                 unresolved += 1
             else:
                 if r is None:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mercurial/minirst.py	Thu Aug 06 18:48:00 2009 -0700
@@ -0,0 +1,299 @@
+# minirst.py - minimal reStructuredText parser
+#
+# Copyright 2009 Matt Mackall <mpm@selenic.com> and others
+#
+# This software may be used and distributed according to the terms of the
+# GNU General Public License version 2, incorporated herein by reference.
+
+"""simplified reStructuredText parser.
+
+This parser knows just enough about reStructuredText to parse the
+Mercurial docstrings.
+
+It cheats in a major way: nested blocks are not really nested. They
+are just indented blocks that look like they are nested. This relies
+on the user to keep the right indentation for the blocks.
+
+It only supports a small subset of reStructuredText:
+
+- paragraphs
+
+- definition lists (must use '  ' to indent definitions)
+
+- lists (items must start with '-')
+
+- literal blocks
+
+- option lists (supports only long options without arguments)
+
+- inline markup is not recognized at all.
+"""
+
+import re, sys, textwrap
+
+
+def findblocks(text):
+    """Find continuous blocks of lines in text.
+
+    Returns a list of dictionaries representing the blocks. Each block
+    has an 'indent' field and a 'lines' field.
+    """
+    blocks = [[]]
+    lines = text.splitlines()
+    for line in lines:
+        if line.strip():
+            blocks[-1].append(line)
+        elif blocks[-1]:
+            blocks.append([])
+    if not blocks[-1]:
+        del blocks[-1]
+
+    for i, block in enumerate(blocks):
+        indent = min((len(l) - len(l.lstrip())) for l in block)
+        blocks[i] = dict(indent=indent, lines=[l[indent:] for l in block])
+    return blocks
+
+
+def findliteralblocks(blocks):
+    """Finds literal blocks and adds a 'type' field to the blocks.
+
+    Literal blocks are given the type 'literal', all other blocks are
+    given type the 'paragraph'.
+    """
+    i = 0
+    while i < len(blocks):
+        # Searching for a block that looks like this:
+        #
+        # +------------------------------+
+        # | paragraph                    |
+        # | (ends with "::")             |
+        # +------------------------------+
+        #    +---------------------------+
+        #    | indented literal block    |
+        #    +---------------------------+
+        blocks[i]['type'] = 'paragraph'
+        if blocks[i]['lines'][-1].endswith('::') and i+1 < len(blocks):
+            indent = blocks[i]['indent']
+            adjustment = blocks[i+1]['indent'] - indent
+
+            if blocks[i]['lines'] == ['::']:
+                # Expanded form: remove block
+                del blocks[i]
+                i -= 1
+            elif blocks[i]['lines'][-1].endswith(' ::'):
+                # Partially minimized form: remove space and both
+                # colons.
+                blocks[i]['lines'][-1] = blocks[i]['lines'][-1][:-3]
+            else:
+                # Fully minimized form: remove just one colon.
+                blocks[i]['lines'][-1] = blocks[i]['lines'][-1][:-1]
+
+            # List items are formatted with a hanging indent. We must
+            # correct for this here while we still have the original
+            # information on the indentation of the subsequent literal
+            # blocks available.
+            if blocks[i]['lines'][0].startswith('- '):
+                indent += 2
+                adjustment -= 2
+
+            # Mark the following indented blocks.
+            while i+1 < len(blocks) and blocks[i+1]['indent'] > indent:
+                blocks[i+1]['type'] = 'literal'
+                blocks[i+1]['indent'] -= adjustment
+                i += 1
+        i += 1
+    return blocks
+
+
+def findsections(blocks):
+    """Finds sections.
+
+    The blocks must have a 'type' field, i.e., they should have been
+    run through findliteralblocks first.
+    """
+    for block in blocks:
+        # Searching for a block that looks like this:
+        #
+        # +------------------------------+
+        # | Section title                |
+        # | -------------                |
+        # +------------------------------+
+        if (block['type'] == 'paragraph' and
+            len(block['lines']) == 2 and
+            block['lines'][1] == '-' * len(block['lines'][0])):
+            block['type'] = 'section'
+    return blocks
+
+
+def findbulletlists(blocks):
+    """Finds bullet lists.
+
+    The blocks must have a 'type' field, i.e., they should have been
+    run through findliteralblocks first.
+    """
+    i = 0
+    while i < len(blocks):
+        # Searching for a paragraph that looks like this:
+        #
+        # +------+-----------------------+
+        # | "- " | list item             |
+        # +------| (body elements)+      |
+        #        +-----------------------+
+        if (blocks[i]['type'] == 'paragraph' and
+            blocks[i]['lines'][0].startswith('- ')):
+            items = []
+            for line in blocks[i]['lines']:
+                if line.startswith('- '):
+                    items.append(dict(type='bullet', lines=[],
+                                      indent=blocks[i]['indent'] + 2))
+                    line = line[2:]
+                items[-1]['lines'].append(line)
+            blocks[i:i+1] = items
+            i += len(items) - 1
+        i += 1
+    return blocks
+
+
+_optionre = re.compile(r'^(--[a-z-]+)((?:[ =][a-zA-Z][\w-]*)?  +)(.*)$')
+def findoptionlists(blocks):
+    """Finds option lists.
+
+    The blocks must have a 'type' field, i.e., they should have been
+    run through findliteralblocks first.
+    """
+    i = 0
+    while i < len(blocks):
+        # Searching for a paragraph that looks like this:
+        #
+        # +----------------------------+-------------+
+        # | "--" option "  "           | description |
+        # +-------+--------------------+             |
+        #         | (body elements)+                 |
+        #         +----------------------------------+
+        if (blocks[i]['type'] == 'paragraph' and
+            _optionre.match(blocks[i]['lines'][0])):
+            options = []
+            for line in blocks[i]['lines']:
+                m = _optionre.match(line)
+                if m:
+                    option, arg, rest = m.groups()
+                    width = len(option) + len(arg)
+                    options.append(dict(type='option', lines=[],
+                                        indent=blocks[i]['indent'],
+                                        width=width))
+                options[-1]['lines'].append(line)
+            blocks[i:i+1] = options
+            i += len(options) - 1
+        i += 1
+    return blocks
+
+
+def finddefinitionlists(blocks):
+    """Finds definition lists.
+
+    The blocks must have a 'type' field, i.e., they should have been
+    run through findliteralblocks first.
+    """
+    i = 0
+    while i < len(blocks):
+        # Searching for a paragraph that looks like this:
+        #
+        # +----------------------------+
+        # | term                       |
+        # +--+-------------------------+--+
+        #    | definition                 |
+        #    | (body elements)+           |
+        #    +----------------------------+
+        if (blocks[i]['type'] == 'paragraph' and
+            len(blocks[i]['lines']) > 1 and
+            not blocks[i]['lines'][0].startswith('  ') and
+            blocks[i]['lines'][1].startswith('  ')):
+            definitions = []
+            for line in blocks[i]['lines']:
+                if not line.startswith('  '):
+                    definitions.append(dict(type='definition', lines=[],
+                                            indent=blocks[i]['indent']))
+                definitions[-1]['lines'].append(line)
+                definitions[-1]['hang'] = len(line) - len(line.lstrip())
+            blocks[i:i+1] = definitions
+            i += len(definitions) - 1
+        i += 1
+    return blocks
+
+
+def addmargins(blocks):
+    """Adds empty blocks for vertical spacing.
+
+    This groups bullets, options, and definitions together with no vertical
+    space between them, and adds an empty block between all other blocks.
+    """
+    i = 1
+    while i < len(blocks):
+        if (blocks[i]['type'] == blocks[i-1]['type'] and
+            blocks[i]['type'] in ('bullet', 'option', 'definition')):
+            i += 1
+        else:
+            blocks.insert(i, dict(lines=[''], indent=0, type='margin'))
+            i += 2
+    return blocks
+
+
+def formatblock(block, width):
+    """Format a block according to width."""
+    indent = ' ' * block['indent']
+    if block['type'] == 'margin':
+        return ''
+    elif block['type'] in ('literal', 'section'):
+        return indent + ('\n' + indent).join(block['lines'])
+    elif block['type'] == 'definition':
+        term = indent + block['lines'][0]
+        defindent = indent + block['hang'] * ' '
+        text = ' '.join(map(str.strip, block['lines'][1:]))
+        return "%s\n%s" % (term, textwrap.fill(text, width=width,
+                                               initial_indent=defindent,
+                                               subsequent_indent=defindent))
+    else:
+        initindent = subindent = indent
+        text = ' '.join(map(str.strip, block['lines']))
+        if block['type'] == 'bullet':
+            initindent = indent[:-2] + '- '
+            subindent = indent
+        elif block['type'] == 'option':
+            subindent = indent + block['width'] * ' '
+
+        return textwrap.fill(text, width=width,
+                             initial_indent=initindent,
+                             subsequent_indent=subindent)
+
+
+def format(text, width):
+    """Parse and format the text according to width."""
+    blocks = findblocks(text)
+    blocks = findliteralblocks(blocks)
+    blocks = findsections(blocks)
+    blocks = findbulletlists(blocks)
+    blocks = findoptionlists(blocks)
+    blocks = finddefinitionlists(blocks)
+    blocks = addmargins(blocks)
+    return '\n'.join(formatblock(b, width) for b in blocks)
+
+
+if __name__ == "__main__":
+    from pprint import pprint
+
+    def debug(func, blocks):
+        blocks = func(blocks)
+        print "*** after %s:" % func.__name__
+        pprint(blocks)
+        print
+        return blocks
+
+    text = open(sys.argv[1]).read()
+    blocks = debug(findblocks, text)
+    blocks = debug(findliteralblocks, blocks)
+    blocks = debug(findsections, blocks)
+    blocks = debug(findbulletlists, blocks)
+    blocks = debug(findoptionlists, blocks)
+    blocks = debug(finddefinitionlists, blocks)
+    blocks = debug(addmargins, blocks)
+    print '\n'.join(formatblock(b, 30) for b in blocks)
--- a/mercurial/patch.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/patch.py	Thu Aug 06 18:48:00 2009 -0700
@@ -326,10 +326,6 @@
         # looks through the hash and finds candidate lines.  The
         # result is a list of line numbers sorted based on distance
         # from linenum
-        def sorter(a, b):
-            vala = abs(a - linenum)
-            valb = abs(b - linenum)
-            return cmp(vala, valb)
 
         try:
             cand = self.hash[l]
@@ -338,7 +334,7 @@
 
         if len(cand) > 1:
             # resort our list of potentials forward then back.
-            cand.sort(sorter)
+            cand.sort(key=lambda x: abs(x - linenum))
         return cand
 
     def hashlines(self):
@@ -1140,7 +1136,7 @@
         raise util.Abort(_('Unsupported line endings type: %s') % eolmode)
 
     try:
-        fp = file(patchobj, 'rb')
+        fp = open(patchobj, 'rb')
     except TypeError:
         fp = patchobj
     if cwd:
@@ -1432,8 +1428,8 @@
         # If diffstat runs out of room it doesn't print anything, which
         # isn't very useful, so always print at least one + or - if there
         # were at least some changes
-        pluses = '+' * max(adds/factor, int(bool(adds)))
-        minuses = '-' * max(removes/factor, int(bool(removes)))
+        pluses = '+' * max(adds // factor, int(bool(adds)))
+        minuses = '-' * max(removes // factor, int(bool(removes)))
         output.append(' %-*s |  %*.d %s%s\n' % (maxname, filename, countwidth,
                                                 adds+removes, pluses, minuses))
 
--- a/mercurial/posix.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/posix.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,9 +7,9 @@
 
 from i18n import _
 import osutil
-import os, sys, errno, stat, getpass, pwd, grp
+import os, sys, errno, stat, getpass, pwd, grp, fcntl
 
-posixfile = file
+posixfile = open
 nulldev = '/dev/null'
 normpath = os.path.normpath
 samestat = os.path.samestat
@@ -70,20 +70,20 @@
     if l:
         if not stat.S_ISLNK(s):
             # switch file to link
-            data = file(f).read()
+            data = open(f).read()
             os.unlink(f)
             try:
                 os.symlink(data, f)
             except:
                 # failed to make a link, rewrite file
-                file(f, "w").write(data)
+                open(f, "w").write(data)
         # no chmod needed at this point
         return
     if stat.S_ISLNK(s):
         # switch link to file
         data = os.readlink(f)
         os.unlink(f)
-        file(f, "w").write(data)
+        open(f, "w").write(data)
         s = 0666 & ~umask # avoid restatting for chmod
 
     sx = s & 0100
@@ -104,6 +104,44 @@
 def localpath(path):
     return path
 
+if sys.platform == 'darwin':
+    def realpath(path):
+        '''
+        Returns the true, canonical file system path equivalent to the given
+        path.
+
+        Equivalent means, in this case, resulting in the same, unique
+        file system link to the path. Every file system entry, whether a file,
+        directory, hard link or symbolic link or special, will have a single
+        path preferred by the system, but may allow multiple, differing path
+        lookups to point to it.
+
+        Most regular UNIX file systems only allow a file system entry to be
+        looked up by its distinct path. Obviously, this does not apply to case
+        insensitive file systems, whether case preserving or not. The most
+        complex issue to deal with is file systems transparently reencoding the
+        path, such as the non-standard Unicode normalisation required for HFS+
+        and HFSX.
+        '''
+        # Constants copied from /usr/include/sys/fcntl.h
+        F_GETPATH = 50
+        O_SYMLINK = 0x200000
+
+        try:
+            fd = os.open(path, O_SYMLINK)
+        except OSError, err:
+            if err.errno is errno.ENOENT:
+                return path
+            raise
+
+        try:
+            return fcntl.fcntl(fd, F_GETPATH, '\0' * 1024).rstrip('\0')
+        finally:
+            os.close(fd)
+else:
+    # Fallback to the likely inadequate Python builtin function.
+    realpath = os.path.realpath
+
 def shellquote(s):
     if os.sys.platform == 'OpenVMS':
         return '"%s"' % s
--- a/mercurial/pure/base85.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/pure/base85.py	Thu Aug 06 18:48:00 2009 -0700
@@ -25,8 +25,8 @@
     longs = len(text) >> 2
     words = struct.unpack('>%dL' % (longs), text)
 
-    out = ''.join(_b85chars[(word / 52200625) % 85] +
-                  _b85chars2[(word / 7225) % 7225] +
+    out = ''.join(_b85chars[(word // 52200625) % 85] +
+                  _b85chars2[(word // 7225) % 7225] +
                   _b85chars2[word % 7225]
                   for word in words)
 
@@ -37,7 +37,7 @@
     olen = l % 4
     if olen:
         olen += 1
-    olen += l / 4 * 5
+    olen += l // 4 * 5
     return out[:olen]
 
 def b85decode(text):
--- a/mercurial/pure/osutil.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/pure/osutil.py	Thu Aug 06 18:48:00 2009 -0700
@@ -8,7 +8,7 @@
 import os
 import stat as _stat
 
-posixfile = file
+posixfile = open
 
 def _mode_to_kind(mode):
     if _stat.S_ISREG(mode): return _stat.S_IFREG
--- a/mercurial/repair.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/repair.py	Thu Aug 06 18:48:00 2009 -0700
@@ -142,3 +142,4 @@
         if backup != "strip":
             os.unlink(chgrpfile)
 
+    repo.destroyed()
--- a/mercurial/revlog.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/revlog.py	Thu Aug 06 18:48:00 2009 -0700
@@ -879,7 +879,7 @@
         if len(id) < 40:
             try:
                 # hex(node)[:...]
-                l = len(id) / 2  # grab an even number of digits
+                l = len(id) // 2  # grab an even number of digits
                 bin_id = bin(id[:l*2])
                 nl = [n for n in self.nodemap if n[:l] == bin_id]
                 nl = [n for n in nl if hex(n).startswith(id)]
@@ -1354,7 +1354,7 @@
             f.seek(0, 2)
             actual = f.tell()
             s = self._io.size
-            i = max(0, actual / s)
+            i = max(0, actual // s)
             di = actual - (i * s)
             if self._inline:
                 databytes = 0
--- a/mercurial/sshserver.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/sshserver.py	Thu Aug 06 18:48:00 2009 -0700
@@ -59,7 +59,7 @@
         try:
             r = hex(self.repo.lookup(key))
             success = 1
-        except Exception,inst:
+        except Exception, inst:
             r = str(inst)
             success = 0
         self.respond("%s %s\n" % (success, r))
--- a/mercurial/statichttprepo.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/statichttprepo.py	Thu Aug 06 18:48:00 2009 -0700
@@ -114,7 +114,7 @@
 
         self.manifest = manifest.manifest(self.sopener)
         self.changelog = changelog.changelog(self.sopener)
-        self.tagscache = None
+        self._tags = None
         self.nodetagscache = None
         self.encodepats = None
         self.decodepats = None
--- a/mercurial/subrepo.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/subrepo.py	Thu Aug 06 18:48:00 2009 -0700
@@ -8,7 +8,7 @@
 import errno, os
 from i18n import _
 import config, util, node, error
-localrepo = hg = None
+hg = None
 
 nullstate = ('', '')
 
@@ -63,11 +63,11 @@
                 wctx.sub(s).get(r)
                 sm[s] = r
             elif l[0] != r[0]: # sources differ
-                if repo.ui.prompt(
+                if repo.ui.promptchoice(
                     _(' subrepository sources for %s differ\n'
                       'use (l)ocal source (%s) or (r)emote source (%s)?')
                       % (s, l[0], r[0]),
-                      (_('&Local'), _('&Remote')), _('l')) == _('r'):
+                      (_('&Local'), _('&Remote')), 0):
                     wctx.sub(s).get(r)
                     sm[s] = r
             elif l[1] == a[1]: # local side is unchanged
@@ -79,10 +79,10 @@
         elif l == a: # remote removed, local unchanged
             wctx.sub(s).remove()
         else:
-            if repo.ui.prompt(
+            if repo.ui.promptchoice(
                 _(' local changed subrepository %s which remote removed\n'
                   'use (c)hanged version or (d)elete?') % s,
-                  (_('&Changed'), _('&Delete')), _('c')) == _('d'):
+                (_('&Changed'), _('&Delete')), 0):
                 wctx.sub(s).remove()
 
     for s, r in s2.items():
@@ -92,10 +92,10 @@
             wctx.sub(s).get(r)
             sm[s] = r
         elif r != sa[s]:
-            if repo.ui.prompt(
+            if repo.ui.promptchoice(
                 _(' remote changed subrepository %s which local removed\n'
                   'use (c)hanged version or (d)elete?') % s,
-                  (_('&Changed'), _('&Delete')), _('c')) == _('c'):
+                (_('&Changed'), _('&Delete')), 0) == 0:
                 wctx.sub(s).get(r)
                 sm[s] = r
 
@@ -122,9 +122,8 @@
     # because it wants to make repo objects from deep inside the stack
     # so we manually delay the circular imports to not break
     # scripts that don't use our demand-loading
-    global localrepo, hg
-    import localrepo as l, hg as h
-    localrepo = l
+    global hg
+    import hg as h
     hg = h
 
     util.path_auditor(ctx._repo.root)(path)
@@ -140,10 +139,10 @@
         r = ctx._repo
         root = r.wjoin(path)
         if os.path.exists(os.path.join(root, '.hg')):
-            self._repo = localrepo.localrepository(r.ui, root)
+            self._repo = hg.repository(r.ui, root)
         else:
             util.makedirs(root)
-            self._repo = localrepo.localrepository(r.ui, root, create=True)
+            self._repo = hg.repository(r.ui, root, create=True)
         self._repo._subparent = r
         self._repo._subsource = state[0]
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mercurial/tags.py	Thu Aug 06 18:48:00 2009 -0700
@@ -0,0 +1,339 @@
+# tags.py - read tag info from local repository
+#
+# Copyright 2009 Matt Mackall <mpm@selenic.com>
+# Copyright 2009 Greg Ward <greg@gerg.ca>
+#
+# This software may be used and distributed according to the terms of the
+# GNU General Public License version 2, incorporated herein by reference.
+
+# Currently this module only deals with reading and caching tags.
+# Eventually, it could take care of updating (adding/removing/moving)
+# tags too.
+
+import os
+from node import nullid, bin, hex, short
+from i18n import _
+import encoding
+import error
+
+def _debugalways(ui, *msg):
+    ui.write(*msg)
+
+def _debugconditional(ui, *msg):
+    ui.debug(*msg)
+
+def _debugnever(ui, *msg):
+    pass
+
+_debug = _debugalways
+_debug = _debugnever
+
+def findglobaltags1(ui, repo, alltags, tagtypes):
+    '''Find global tags in repo by reading .hgtags from every head that
+    has a distinct version of it.  Updates the dicts alltags, tagtypes
+    in place: alltags maps tag name to (node, hist) pair (see _readtags()
+    below), and tagtypes maps tag name to tag type ('global' in this
+    case).'''
+
+    seen = set()
+    fctx = None
+    ctxs = []                       # list of filectx
+    for node in repo.heads():
+        try:
+            fnode = repo[node].filenode('.hgtags')
+        except error.LookupError:
+            continue
+        if fnode not in seen:
+            seen.add(fnode)
+            if not fctx:
+                fctx = repo.filectx('.hgtags', fileid=fnode)
+            else:
+                fctx = fctx.filectx(fnode)
+            ctxs.append(fctx)
+
+    # read the tags file from each head, ending with the tip
+    for fctx in reversed(ctxs):
+        filetags = _readtags(
+            ui, repo, fctx.data().splitlines(), fctx)
+        _updatetags(filetags, "global", alltags, tagtypes)
+
+def findglobaltags2(ui, repo, alltags, tagtypes):
+    '''Same as findglobaltags1(), but with caching.'''
+    # This is so we can be lazy and assume alltags contains only global
+    # tags when we pass it to _writetagcache().
+    assert len(alltags) == len(tagtypes) == 0, \
+           "findglobaltags() should be called first"
+
+    (heads, tagfnode, cachetags, shouldwrite) = _readtagcache(ui, repo)
+    if cachetags is not None:
+        assert not shouldwrite
+        # XXX is this really 100% correct?  are there oddball special
+        # cases where a global tag should outrank a local tag but won't,
+        # because cachetags does not contain rank info?
+        _updatetags(cachetags, 'global', alltags, tagtypes)
+        return
+
+    _debug(ui, "reading tags from %d head(s): %s\n"
+           % (len(heads), map(short, reversed(heads))))
+    seen = set()                    # set of fnode
+    fctx = None
+    for head in reversed(heads):        # oldest to newest
+        assert head in repo.changelog.nodemap, \
+               "tag cache returned bogus head %s" % short(head)
+
+        fnode = tagfnode.get(head)
+        if fnode and fnode not in seen:
+            seen.add(fnode)
+            if not fctx:
+                fctx = repo.filectx('.hgtags', fileid=fnode)
+            else:
+                fctx = fctx.filectx(fnode)
+
+            filetags = _readtags(ui, repo, fctx.data().splitlines(), fctx)
+            _updatetags(filetags, 'global', alltags, tagtypes)
+
+    # and update the cache (if necessary)
+    if shouldwrite:
+        _writetagcache(ui, repo, heads, tagfnode, alltags)
+
+# Set this to findglobaltags1 to disable tag caching.
+findglobaltags = findglobaltags2
+
+def readlocaltags(ui, repo, alltags, tagtypes):
+    '''Read local tags in repo.  Update alltags and tagtypes.'''
+    try:
+        # localtags is in the local encoding; re-encode to UTF-8 on
+        # input for consistency with the rest of this module.
+        data = repo.opener("localtags").read()
+        filetags = _readtags(
+            ui, repo, data.splitlines(), "localtags",
+            recode=encoding.fromlocal)
+        _updatetags(filetags, "local", alltags, tagtypes)
+    except IOError:
+        pass
+
+def _readtags(ui, repo, lines, fn, recode=None):
+    '''Read tag definitions from a file (or any source of lines).
+    Return a mapping from tag name to (node, hist): node is the node id
+    from the last line read for that name, and hist is the list of node
+    ids previously associated with it (in file order).  All node ids are
+    binary, not hex.'''
+
+    filetags = {}               # map tag name to (node, hist)
+    count = 0
+
+    def warn(msg):
+        ui.warn(_("%s, line %s: %s\n") % (fn, count, msg))
+
+    for line in lines:
+        count += 1
+        if not line:
+            continue
+        try:
+            (nodehex, name) = line.split(" ", 1)
+        except ValueError:
+            warn(_("cannot parse entry"))
+            continue
+        name = name.strip()
+        if recode:
+            name = recode(name)
+        try:
+            nodebin = bin(nodehex)
+        except TypeError:
+            warn(_("node '%s' is not well formed") % nodehex)
+            continue
+        if nodebin not in repo.changelog.nodemap:
+            # silently ignore as pull -r might cause this
+            continue
+
+        # update filetags
+        hist = []
+        if name in filetags:
+            n, hist = filetags[name]
+            hist.append(n)
+        filetags[name] = (nodebin, hist)
+    return filetags
+
+def _updatetags(filetags, tagtype, alltags, tagtypes):
+    '''Incorporate the tag info read from one file into the two
+    dictionaries, alltags and tagtypes, that contain all tag
+    info (global across all heads plus local).'''
+
+    for name, nodehist in filetags.iteritems():
+        if name not in alltags:
+            alltags[name] = nodehist
+            tagtypes[name] = tagtype
+            continue
+
+        # we prefer alltags[name] if:
+        #  it supercedes us OR
+        #  mutual supercedes and it has a higher rank
+        # otherwise we win because we're tip-most
+        anode, ahist = nodehist
+        bnode, bhist = alltags[name]
+        if (bnode != anode and anode in bhist and
+            (bnode not in ahist or len(bhist) > len(ahist))):
+            anode = bnode
+        ahist.extend([n for n in bhist if n not in ahist])
+        alltags[name] = anode, ahist
+        tagtypes[name] = tagtype
+
+
+# The tag cache only stores info about heads, not the tag contents
+# from each head.  I.e. it doesn't try to squeeze out the maximum
+# performance, but is simpler has a better chance of actually
+# working correctly.  And this gives the biggest performance win: it
+# avoids looking up .hgtags in the manifest for every head, and it
+# can avoid calling heads() at all if there have been no changes to
+# the repo.
+
+def _readtagcache(ui, repo):
+    '''Read the tag cache and return a tuple (heads, fnodes, cachetags,
+    shouldwrite).  If the cache is completely up-to-date, cachetags is a
+    dict of the form returned by _readtags(); otherwise, it is None and
+    heads and fnodes are set.  In that case, heads is the list of all
+    heads currently in the repository (ordered from tip to oldest) and
+    fnodes is a mapping from head to .hgtags filenode.  If those two are
+    set, caller is responsible for reading tag info from each head.'''
+
+    try:
+        cachefile = repo.opener('tags.cache', 'r')
+        _debug(ui, 'reading tag cache from %s\n' % cachefile.name)
+    except IOError:
+        cachefile = None
+
+    # The cache file consists of lines like
+    #   <headrev> <headnode> [<tagnode>]
+    # where <headrev> and <headnode> redundantly identify a repository
+    # head from the time the cache was written, and <tagnode> is the
+    # filenode of .hgtags on that head.  Heads with no .hgtags file will
+    # have no <tagnode>.  The cache is ordered from tip to oldest (which
+    # is part of why <headrev> is there: a quick visual check is all
+    # that's required to ensure correct order).
+    # 
+    # This information is enough to let us avoid the most expensive part
+    # of finding global tags, which is looking up <tagnode> in the
+    # manifest for each head.
+    cacherevs = []                      # list of headrev
+    cacheheads = []                     # list of headnode
+    cachefnode = {}                     # map headnode to filenode
+    if cachefile:
+        for line in cachefile:
+            if line == "\n":
+                break
+            line = line.rstrip().split()
+            cacherevs.append(int(line[0]))
+            headnode = bin(line[1])
+            cacheheads.append(headnode)
+            if len(line) == 3:
+                fnode = bin(line[2])
+                cachefnode[headnode] = fnode
+
+    tipnode = repo.changelog.tip()
+    tiprev = len(repo.changelog) - 1
+
+    # Case 1 (common): tip is the same, so nothing has changed.
+    # (Unchanged tip trivially means no changesets have been added.
+    # But, thanks to localrepository.destroyed(), it also means none
+    # have been destroyed by strip or rollback.)
+    if cacheheads and cacheheads[0] == tipnode and cacherevs[0] == tiprev:
+        _debug(ui, "tag cache: tip unchanged\n")
+        tags = _readtags(ui, repo, cachefile, cachefile.name)
+        cachefile.close()
+        return (None, None, tags, False)
+    if cachefile:
+        cachefile.close()               # ignore rest of file
+        
+    repoheads = repo.heads()
+
+    # Case 2 (uncommon): empty repo; get out quickly and don't bother
+    # writing an empty cache.
+    if repoheads == [nullid]:
+        return ([], {}, {}, False)
+
+    # Case 3 (uncommon): cache file missing or empty.
+    if not cacheheads:
+        _debug(ui, 'tag cache: cache file missing or empty\n')
+
+    # Case 4 (uncommon): tip rev decreased.  This should only happen
+    # when we're called from localrepository.destroyed().  Refresh the
+    # cache so future invocations will not see disappeared heads in the
+    # cache.
+    elif cacheheads and tiprev < cacherevs[0]:
+        _debug(ui,
+               'tag cache: tip rev decremented (from %d to %d), '
+               'so we must be destroying nodes\n'
+               % (cacherevs[0], tiprev))
+
+    # Case 5 (common): tip has changed, so we've added/replaced heads.
+    else:
+        _debug(ui,
+               'tag cache: tip has changed (%d:%s); must find new heads\n'
+               % (tiprev, short(tipnode)))
+
+    # Luckily, the code to handle cases 3, 4, 5 is the same.  So the
+    # above if/elif/else can disappear once we're confident this thing
+    # actually works and we don't need the debug output.
+
+    # N.B. in case 4 (nodes destroyed), "new head" really means "newly
+    # exposed".
+    newheads = [head
+                for head in repoheads
+                if head not in set(cacheheads)]
+    _debug(ui, 'tag cache: found %d head(s) not in cache: %s\n'
+           % (len(newheads), map(short, newheads)))
+
+    # Now we have to lookup the .hgtags filenode for every new head.
+    # This is the most expensive part of finding tags, so performance
+    # depends primarily on the size of newheads.  Worst case: no cache
+    # file, so newheads == repoheads.
+    for head in newheads:
+        cctx = repo[head]
+        try:
+            fnode = cctx.filenode('.hgtags')
+            cachefnode[head] = fnode
+        except error.LookupError:
+            # no .hgtags file on this head
+            pass
+
+    # Caller has to iterate over all heads, but can use the filenodes in
+    # cachefnode to get to each .hgtags revision quickly.
+    return (repoheads, cachefnode, None, True)
+
+def _writetagcache(ui, repo, heads, tagfnode, cachetags):
+
+    cachefile = repo.opener('tags.cache', 'w', atomictemp=True)
+    _debug(ui, 'writing cache file %s\n' % cachefile.name)
+
+    realheads = repo.heads()            # for sanity checks below
+    for head in heads:
+        # temporary sanity checks; these can probably be removed
+        # once this code has been in crew for a few weeks
+        assert head in repo.changelog.nodemap, \
+               'trying to write non-existent node %s to tag cache' % short(head)
+        assert head in realheads, \
+               'trying to write non-head %s to tag cache' % short(head)
+        assert head != nullid, \
+               'trying to write nullid to tag cache'
+
+        # This can't fail because of the first assert above.  When/if we
+        # remove that assert, we might want to catch LookupError here
+        # and downgrade it to a warning.
+        rev = repo.changelog.rev(head)
+
+        fnode = tagfnode.get(head)
+        if fnode:
+            cachefile.write('%d %s %s\n' % (rev, hex(head), hex(fnode)))
+        else:
+            cachefile.write('%d %s\n' % (rev, hex(head)))
+
+    # Tag names in the cache are in UTF-8 -- which is the whole reason
+    # we keep them in UTF-8 throughout this module.  If we converted
+    # them local encoding on input, we would lose info writing them to
+    # the cache.
+    cachefile.write('\n')
+    for (name, (node, hist)) in cachetags.iteritems():
+        cachefile.write("%s %s\n" % (hex(node), name))
+
+    cachefile.rename()
+    cachefile.close()
--- a/mercurial/templatefilters.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/templatefilters.py	Thu Aug 06 18:48:00 2009 -0700
@@ -41,7 +41,7 @@
 
     delta = max(1, int(now - then))
     for t, s in agescales:
-        n = delta / s
+        n = delta // s
         if n >= 2 or s == 1:
             return fmt(t, n)
 
@@ -73,7 +73,7 @@
 def firstline(text):
     '''return the first line of text'''
     try:
-        return text.splitlines(1)[0].rstrip('\r\n')
+        return text.splitlines(True)[0].rstrip('\r\n')
     except IndexError:
         return ''
 
--- a/mercurial/transaction.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/transaction.py	Thu Aug 06 18:48:00 2009 -0700
@@ -118,6 +118,7 @@
 
     @active
     def close(self):
+        '''commit the transaction'''
         self.count -= 1
         if self.count != 0:
             return
@@ -131,6 +132,9 @@
 
     @active
     def abort(self):
+        '''abort the transaction (generally called on error, or when the
+        transaction is not explicitly committed before going out of
+        scope)'''
         self._abort()
 
     def _abort(self):
--- a/mercurial/ui.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/ui.py	Thu Aug 06 18:48:00 2009 -0700
@@ -269,30 +269,35 @@
             line = line[:-1]
         return line
 
-    def prompt(self, msg, choices=None, default="y"):
-        """Prompt user with msg, read response, and ensure it matches
-        one of the provided choices. choices is a sequence of acceptable
-        responses with the format: ('&None', 'E&xec', 'Sym&link')
-        No sequence implies no response checking. Responses are case
-        insensitive. If ui is not interactive, the default is returned.
+    def prompt(self, msg, default="y"):
+        """Prompt user with msg, read response.
+        If ui is not interactive, the default is returned.
         """
         if not self.interactive():
             self.write(msg, ' ', default, "\n")
             return default
+        try:
+            r = self._readline(msg + ' ')
+            if not r:
+                return default
+            return r
+        except EOFError:
+            raise util.Abort(_('response expected'))
+
+    def promptchoice(self, msg, choices, default=0):
+        """Prompt user with msg, read response, and ensure it matches
+        one of the provided choices. The index of the choice is returned.
+        choices is a sequence of acceptable responses with the format:
+        ('&None', 'E&xec', 'Sym&link') Responses are case insensitive. 
+        If ui is not interactive, the default is returned.
+        """
+        resps = [s[s.index('&')+1].lower() for s in choices]
         while True:
-            try:
-                r = self._readline(msg + ' ')
-                if not r:
-                    return default
-                if not choices:
-                    return r
-                resps = [s[s.index('&')+1].lower() for s in choices]
-                if r.lower() in resps:
-                    return r.lower()
-                else:
-                    self.write(_("unrecognized response\n"))
-            except EOFError:
-                raise util.Abort(_('response expected'))
+            r = self.prompt(msg, resps[default])
+            if r.lower() in resps:
+                return resps.index(r.lower())
+            self.write(_("unrecognized response\n"))
+
 
     def getpass(self, prompt=None, default=None):
         if not self.interactive(): return default
@@ -344,3 +349,33 @@
                 self.config("ui", "editor") or
                 os.environ.get("VISUAL") or
                 os.environ.get("EDITOR", "vi"))
+
+    def progress(self, topic, pos, item="", unit="", total=None):
+        '''show a progress message
+
+        With stock hg, this is simply a debug message that is hidden
+        by default, but with extensions or GUI tools it may be
+        visible. 'topic' is the current operation, 'item' is a
+        non-numeric marker of the current position (ie the currently
+        in-process file), 'pos' is the current numeric position (ie
+        revision, bytes, etc.), units is a corresponding unit label,
+        and total is the highest expected pos.
+
+        Multiple nested topics may be active at a time. All topics
+        should be marked closed by setting pos to None at termination.
+        '''
+
+        if pos == None or not self.debugflag:
+            return
+
+        if units:
+            units = ' ' + units
+        if item:
+            item = ' ' + item
+
+        if total:
+            pct = 100.0 * pos / total
+            ui.debug('%s:%s %s/%s%s (%4.2g%%)\n'
+                     % (topic, item, pos, total, units, pct))
+        else:
+            ui.debug('%s:%s %s%s\n' % (topic, item, pos, units))
--- a/mercurial/util.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/util.py	Thu Aug 06 18:48:00 2009 -0700
@@ -842,11 +842,9 @@
             self.audit_path = always
         self.createmode = None
 
-    def __getattr__(self, name):
-        if name == '_can_symlink':
-            self._can_symlink = checklink(self.base)
-            return self._can_symlink
-        raise AttributeError(name)
+    @propertycache
+    def _can_symlink(self):
+        return checklink(self.base)
 
     def _fixfilemode(self, name):
         if self.createmode is None:
@@ -969,8 +967,8 @@
     t, tz = date or makedate()
     if "%1" in format or "%2" in format:
         sign = (tz > 0) and "-" or "+"
-        minutes = abs(tz) / 60
-        format = format.replace("%1", "%c%02d" % (sign, minutes / 60))
+        minutes = abs(tz) // 60
+        format = format.replace("%1", "%c%02d" % (sign, minutes // 60))
         format = format.replace("%2", "%02d" % (minutes % 60))
     s = time.strftime(format, time.gmtime(float(t) - tz))
     return s
@@ -1274,7 +1272,9 @@
         pass
     return 80
 
-def wrap(line, hangindent, width=78):
+def wrap(line, hangindent, width=None):
+    if width is None:
+        width = termwidth() - 2
     padding = '\n' + ' ' * hangindent
     return padding.join(textwrap.wrap(line, width=width - hangindent))
 
--- a/mercurial/verify.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/verify.py	Thu Aug 06 18:48:00 2009 -0700
@@ -78,7 +78,7 @@
                 msg = _("rev %d points to unexpected changeset %d")
             err(None, msg % (i, lr), f)
             if linkrevs:
-                warn(_(" (expected %s)") % " ".join(map(str,linkrevs)))
+                warn(_(" (expected %s)") % " ".join(map(str, linkrevs)))
             lr = None # can't be trusted
 
         try:
@@ -147,7 +147,7 @@
     if havemf:
         for c,m in sorted([(c, m) for m in mflinkrevs for c in mflinkrevs[m]]):
             err(c, _("changeset refers to unknown manifest %s") % short(m))
-        del mflinkrevs
+        mflinkrevs = None # del is bad here due to scope issues
 
         for f in sorted(filelinkrevs):
             if f not in filenodes:
--- a/mercurial/win32.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/win32.py	Thu Aug 06 18:48:00 2009 -0700
@@ -18,7 +18,7 @@
 import errno, os, sys, pywintypes, win32con, win32file, win32process
 import winerror
 import osutil, encoding
-from win32com.shell import shell,shellcon
+from win32com.shell import shell, shellcon
 
 def os_link(src, dst):
     try:
--- a/mercurial/windows.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/mercurial/windows.py	Thu Aug 06 18:48:00 2009 -0700
@@ -126,6 +126,15 @@
 def normpath(path):
     return pconvert(os.path.normpath(path))
 
+def realpath(path):
+    '''
+    Returns the true, canonical file system path equivalent to the given
+    path.
+    '''
+    # TODO: There may be a more clever way to do this that also handles other,
+    # less common file systems.
+    return os.path.normpath(os.path.normcase(os.path.realpath(path)))
+
 def samestat(s1, s2):
     return False
 
--- a/setup.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/setup.py	Thu Aug 06 18:48:00 2009 -0700
@@ -143,7 +143,7 @@
             break
 
 if version:
-    f = file("mercurial/__version__.py", "w")
+    f = open("mercurial/__version__.py", "w")
     f.write('# this file is autogenerated by setup.py\n')
     f.write('version = "%s"\n' % version)
     f.close()
--- a/tests/killdaemons.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/killdaemons.py	Thu Aug 06 18:48:00 2009 -0700
@@ -4,7 +4,7 @@
 
 # Kill off any leftover daemon processes
 try:
-    fp = file(os.environ['DAEMON_PIDS'])
+    fp = open(os.environ['DAEMON_PIDS'])
     for line in fp:
         try:
             pid = int(line)
--- a/tests/run-tests.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/run-tests.py	Thu Aug 06 18:48:00 2009 -0700
@@ -119,6 +119,8 @@
         help="shortcut for --with-hg=<testdir>/../hg")
     parser.add_option("--pure", action="store_true",
         help="use pure Python code instead of C extensions")
+    parser.add_option("-3", "--py3k-warnings", action="store_true",
+        help="enable Py3k warnings on Python 2.6+")
 
     for option, default in defaults.items():
         defaults[option] = int(os.environ.get(*default))
@@ -171,6 +173,10 @@
     if options.interactive and options.jobs > 1:
         print '(--interactive overrides --jobs)'
         options.jobs = 1
+    if options.py3k_warnings:
+        if sys.version_info[:2] < (2, 6) or sys.version_info[:2] >= (3, 0):
+            print 'ERROR: Py3k warnings switch can only be used on Python 2.6+'
+            sys.exit(1)
 
     return (options, args)
 
@@ -299,6 +305,17 @@
     f.close()
     os.chmod(os.path.join(BINDIR, 'diffstat'), 0700)
 
+    if options.py3k_warnings and not options.anycoverage:
+        vlog("# Updating hg command to enable Py3k Warnings switch")
+        f = open(os.path.join(BINDIR, 'hg'), 'r')
+        lines = [line.rstrip() for line in f]
+        lines[0] += ' -3'
+        f.close()
+        f = open(os.path.join(BINDIR, 'hg'), 'w')
+        for line in lines:
+            f.write(line + '\n')
+        f.close()
+
     if options.anycoverage:
         vlog("# Installing coverage wrapper")
         os.environ['COVERAGE_FILE'] = COVERAGE_FILE
@@ -402,7 +419,7 @@
     vlog("# Test", test)
 
     # create a fresh hgrc
-    hgrc = file(HGRCPATH, 'w+')
+    hgrc = open(HGRCPATH, 'w+')
     hgrc.write('[ui]\n')
     hgrc.write('slash = True\n')
     hgrc.write('[defaults]\n')
@@ -432,7 +449,8 @@
     lctest = test.lower()
 
     if lctest.endswith('.py') or firstline == '#!/usr/bin/env python':
-        cmd = '%s "%s"' % (PYTHON, testpath)
+        py3kswitch = options.py3k_warnings and ' -3' or ''
+        cmd = '%s%s "%s"' % (PYTHON, py3kswitch, testpath)
     elif lctest.endswith('.bat'):
         # do not run batch scripts on non-windows
         if os.name != 'nt':
@@ -507,7 +525,7 @@
 
     # Kill off any leftover daemon processes
     try:
-        fp = file(DAEMON_PIDS)
+        fp = open(DAEMON_PIDS)
         for line in fp:
             try:
                 pid = int(line)
--- a/tests/test-add	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-add	Thu Aug 06 18:48:00 2009 -0700
@@ -20,7 +20,7 @@
 hg add b
 hg st
 
-hg ci -m 0
+hg ci -m 0 --traceback
 echo % should fail
 hg add a
 
--- a/tests/test-context.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-context.py	Thu Aug 06 18:48:00 2009 -0700
@@ -7,7 +7,7 @@
 os.chdir('test1')
 
 # create 'foo' with fixed time stamp
-f = file('foo', 'w')
+f = open('foo', 'w')
 f.write('foo\n')
 f.close()
 os.utime('foo', (1000, 1000))
--- a/tests/test-convert-cvs-branch	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-convert-cvs-branch	Thu Aug 06 18:48:00 2009 -0700
@@ -83,7 +83,8 @@
 
 cvscall -Q -d `pwd`/cvsmaster2 init >/dev/null 2>&1
 cd cvsmaster2
-export CVSROOT=`pwd`
+CVSROOT=`pwd`
+export CVSROOT
 mkdir foo
 cd ..
 cvscall -Q co -d cvswork2 foo
--- a/tests/test-convert.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-convert.out	Thu Aug 06 18:48:00 2009 -0700
@@ -3,6 +3,7 @@
 convert a foreign SCM repository to a Mercurial one.
 
     Accepted source formats [identifiers]:
+
     - Mercurial [hg]
     - CVS [cvs]
     - Darcs [darcs]
@@ -14,162 +15,160 @@
     - Perforce [p4]
 
     Accepted destination formats [identifiers]:
+
     - Mercurial [hg]
     - Subversion [svn] (history on branches is not preserved)
 
-    If no revision is given, all revisions will be converted.
-    Otherwise, convert will only import up to the named revision
-    (given in a format understood by the source).
+    If no revision is given, all revisions will be converted. Otherwise,
+    convert will only import up to the named revision (given in a format
+    understood by the source).
 
-    If no destination directory name is specified, it defaults to the
-    basename of the source with '-hg' appended. If the destination
-    repository doesn't exist, it will be created.
+    If no destination directory name is specified, it defaults to the basename
+    of the source with '-hg' appended. If the destination repository doesn't
+    exist, it will be created.
 
-    By default, all sources except Mercurial will use
-    --branchsort. Mercurial uses --sourcesort to preserve original
-    revision numbers order. Sort modes have the following effects:
-      --branchsort: convert from parent to child revision when
-        possible, which means branches are usually converted one after
-        the other. It generates more compact repositories.
-      --datesort: sort revisions by date. Converted repositories have
-        good-looking changelogs but are often an order of magnitude
-        larger than the same ones generated by --branchsort.
-      --sourcesort: try to preserve source revisions order, only
-        supported by Mercurial sources.
+    By default, all sources except Mercurial will use --branchsort. Mercurial
+    uses --sourcesort to preserve original revision numbers order. Sort modes
+    have the following effects:
+
+    --branchsort  convert from parent to child revision when possible, which
+                  means branches are usually converted one after the other. It
+                  generates more compact repositories.
+    --datesort    sort revisions by date. Converted repositories have good-
+                  looking changelogs but are often an order of magnitude
+                  larger than the same ones generated by --branchsort.
+    --sourcesort  try to preserve source revisions order, only supported by
+                  Mercurial sources.
 
     If <REVMAP> isn't given, it will be put in a default location
-    (<dest>/.hg/shamap by default). The <REVMAP> is a simple text file
-    that maps each source commit ID to the destination ID for that
-    revision, like so:
+    (<dest>/.hg/shamap by default). The <REVMAP> is a simple text file that
+    maps each source commit ID to the destination ID for that revision, like
+    so:
+
     <source ID> <destination ID>
 
-    If the file doesn't exist, it's automatically created. It's
-    updated on each commit copied, so convert-repo can be interrupted
-    and can be run repeatedly to copy new commits.
+    If the file doesn't exist, it's automatically created. It's updated on
+    each commit copied, so convert-repo can be interrupted and can be run
+    repeatedly to copy new commits.
 
-    The [username mapping] file is a simple text file that maps each
-    source commit author to a destination commit author. It is handy
-    for source SCMs that use unix logins to identify authors (eg:
-    CVS). One line per author mapping and the line format is:
-    srcauthor=whatever string you want
+    The [username mapping] file is a simple text file that maps each source
+    commit author to a destination commit author. It is handy for source SCMs
+    that use unix logins to identify authors (eg: CVS). One line per author
+    mapping and the line format is: srcauthor=whatever string you want
 
-    The filemap is a file that allows filtering and remapping of files
-    and directories. Comment lines start with '#'. Each line can
-    contain one of the following directives:
+    The filemap is a file that allows filtering and remapping of files and
+    directories. Comment lines start with '#'. Each line can contain one of
+    the following directives:
 
-      include path/to/file
+    include path/to/file
 
-      exclude path/to/file
+    exclude path/to/file
 
-      rename from/file to/file
+    rename from/file to/file
 
-    The 'include' directive causes a file, or all files under a
-    directory, to be included in the destination repository, and the
-    exclusion of all other files and directories not explicitly included.
-    The 'exclude' directive causes files or directories to be omitted.
-    The 'rename' directive renames a file or directory. To rename from
-    a subdirectory into the root of the repository, use '.' as the
-    path to rename to.
+    The 'include' directive causes a file, or all files under a directory, to
+    be included in the destination repository, and the exclusion of all other
+    files and directories not explicitly included. The 'exclude' directive
+    causes files or directories to be omitted. The 'rename' directive renames
+    a file or directory. To rename from a subdirectory into the root of the
+    repository, use '.' as the path to rename to.
 
-    The splicemap is a file that allows insertion of synthetic
-    history, letting you specify the parents of a revision. This is
-    useful if you want to e.g. give a Subversion merge two parents, or
-    graft two disconnected series of history together. Each entry
-    contains a key, followed by a space, followed by one or two
-    comma-separated values. The key is the revision ID in the source
-    revision control system whose parents should be modified (same
-    format as a key in .hg/shamap). The values are the revision IDs
-    (in either the source or destination revision control system) that
+    The splicemap is a file that allows insertion of synthetic history,
+    letting you specify the parents of a revision. This is useful if you want
+    to e.g. give a Subversion merge two parents, or graft two disconnected
+    series of history together. Each entry contains a key, followed by a
+    space, followed by one or two comma-separated values. The key is the
+    revision ID in the source revision control system whose parents should be
+    modified (same format as a key in .hg/shamap). The values are the revision
+    IDs (in either the source or destination revision control system) that
     should be used as the new parents for that node.
 
     The branchmap is a file that allows you to rename a branch when it is
     being brought in from whatever external repository. When used in
-    conjunction with a splicemap, it allows for a powerful combination
-    to help fix even the most badly mismanaged repositories and turn them
-    into nicely structured Mercurial repositories. The branchmap contains
-    lines of the form "original_branch_name new_branch_name".
-    "original_branch_name" is the name of the branch in the source
-    repository, and "new_branch_name" is the name of the branch is the
-    destination repository. This can be used to (for instance) move code
-    in one repository from "default" to a named branch.
+    conjunction with a splicemap, it allows for a powerful combination to help
+    fix even the most badly mismanaged repositories and turn them into nicely
+    structured Mercurial repositories. The branchmap contains lines of the
+    form "original_branch_name new_branch_name". "original_branch_name" is the
+    name of the branch in the source repository, and "new_branch_name" is the
+    name of the branch is the destination repository. This can be used to (for
+    instance) move code in one repository from "default" to a named branch.
 
     Mercurial Source
-    -----------------
+    ----------------
 
     --config convert.hg.ignoreerrors=False    (boolean)
         ignore integrity errors when reading. Use it to fix Mercurial
         repositories with missing revlogs, by converting from and to
         Mercurial.
     --config convert.hg.saverev=False         (boolean)
-        store original revision ID in changeset (forces target IDs to
-        change)
+        store original revision ID in changeset (forces target IDs to change)
     --config convert.hg.startrev=0            (hg revision identifier)
         convert start revision and its descendants
 
     CVS Source
     ----------
 
-    CVS source will use a sandbox (i.e. a checked-out copy) from CVS
-    to indicate the starting point of what will be converted. Direct
-    access to the repository files is not needed, unless of course the
-    repository is :local:. The conversion uses the top level directory
-    in the sandbox to find the CVS repository, and then uses CVS rlog
-    commands to find files to convert. This means that unless a
-    filemap is given, all files under the starting directory will be
-    converted, and that any directory reorganization in the CVS
-    sandbox is ignored.
+    CVS source will use a sandbox (i.e. a checked-out copy) from CVS to
+    indicate the starting point of what will be converted. Direct access to
+    the repository files is not needed, unless of course the repository is
+    :local:. The conversion uses the top level directory in the sandbox to
+    find the CVS repository, and then uses CVS rlog commands to find files to
+    convert. This means that unless a filemap is given, all files under the
+    starting directory will be converted, and that any directory
+    reorganization in the CVS sandbox is ignored.
 
     Because CVS does not have changesets, it is necessary to collect
-    individual commits to CVS and merge them into changesets. CVS
-    source uses its internal changeset merging code by default but can
-    be configured to call the external 'cvsps' program by setting:
-        --config convert.cvsps='cvsps -A -u --cvs-direct -q'
+    individual commits to CVS and merge them into changesets. CVS source uses
+    its internal changeset merging code by default but can be configured to
+    call the external 'cvsps' program by setting:
+
+    --config convert.cvsps='cvsps -A -u --cvs-direct -q'
+
     This option is deprecated and will be removed in Mercurial 1.4.
 
     The options shown are the defaults.
 
     Internal cvsps is selected by setting
-        --config convert.cvsps=builtin
+
+    --config convert.cvsps=builtin
+
     and has a few more configurable options:
-        --config convert.cvsps.cache=True     (boolean)
-            Set to False to disable remote log caching, for testing and
-            debugging purposes.
-        --config convert.cvsps.fuzz=60        (integer)
-            Specify the maximum time (in seconds) that is allowed
-            between commits with identical user and log message in a
-            single changeset. When very large files were checked in as
-            part of a changeset then the default may not be long
-            enough.
-        --config convert.cvsps.mergeto='{{mergetobranch ([-\w]+)}}'
-            Specify a regular expression to which commit log messages
-            are matched. If a match occurs, then the conversion
-            process will insert a dummy revision merging the branch on
-            which this log message occurs to the branch indicated in
-            the regex.
-        --config convert.cvsps.mergefrom='{{mergefrombranch ([-\w]+)}}'
-            Specify a regular expression to which commit log messages
-            are matched. If a match occurs, then the conversion
-            process will add the most recent revision on the branch
-            indicated in the regex as the second parent of the
-            changeset.
 
-    The hgext/convert/cvsps wrapper script allows the builtin
-    changeset merging code to be run without doing a conversion. Its
-    parameters and output are similar to that of cvsps 2.1.
+    --config convert.cvsps.cache=True         (boolean)
+        Set to False to disable remote log caching, for testing and debugging
+        purposes.
+    --config convert.cvsps.fuzz=60            (integer)
+        Specify the maximum time (in seconds) that is allowed between commits
+        with identical user and log message in a single changeset. When very
+        large files were checked in as part of a changeset then the default
+        may not be long enough.
+    --config convert.cvsps.mergeto='{{mergetobranch ([-\w]+)}}'
+        Specify a regular expression to which commit log messages are matched.
+        If a match occurs, then the conversion process will insert a dummy
+        revision merging the branch on which this log message occurs to the
+        branch indicated in the regex.
+    --config convert.cvsps.mergefrom='{{mergefrombranch ([-\w]+)}}'
+        Specify a regular expression to which commit log messages are matched.
+        If a match occurs, then the conversion process will add the most
+        recent revision on the branch indicated in the regex as the second
+        parent of the changeset.
+
+    The hgext/convert/cvsps wrapper script allows the builtin changeset
+    merging code to be run without doing a conversion. Its parameters and
+    output are similar to that of cvsps 2.1.
 
     Subversion Source
     -----------------
 
-    Subversion source detects classical trunk/branches/tags layouts.
-    By default, the supplied "svn://repo/path/" source URL is
-    converted as a single branch. If "svn://repo/path/trunk" exists it
-    replaces the default branch. If "svn://repo/path/branches" exists,
-    its subdirectories are listed as possible branches. If
-    "svn://repo/path/tags" exists, it is looked for tags referencing
-    converted branches. Default "trunk", "branches" and "tags" values
-    can be overridden with following options. Set them to paths
-    relative to the source URL, or leave them blank to disable auto
-    detection.
+    Subversion source detects classical trunk/branches/tags layouts. By
+    default, the supplied "svn://repo/path/" source URL is converted as a
+    single branch. If "svn://repo/path/trunk" exists it replaces the default
+    branch. If "svn://repo/path/branches" exists, its subdirectories are
+    listed as possible branches. If "svn://repo/path/tags" exists, it is
+    looked for tags referencing converted branches. Default "trunk",
+    "branches" and "tags" values can be overridden with following options. Set
+    them to paths relative to the source URL, or leave them blank to disable
+    auto detection.
 
     --config convert.svn.branches=branches    (directory name)
         specify the directory containing branches
@@ -178,9 +177,9 @@
     --config convert.svn.trunk=trunk          (directory name)
         specify the name of the trunk branch
 
-    Source history can be retrieved starting at a specific revision,
-    instead of being integrally converted. Only single branch
-    conversions are supported.
+    Source history can be retrieved starting at a specific revision, instead
+    of being integrally converted. Only single branch conversions are
+    supported.
 
     --config convert.svn.startrev=0           (svn revision number)
         specify start Subversion revision.
@@ -188,20 +187,18 @@
     Perforce Source
     ---------------
 
-    The Perforce (P4) importer can be given a p4 depot path or a
-    client specification as source. It will convert all files in the
-    source to a flat Mercurial repository, ignoring labels, branches
-    and integrations. Note that when a depot path is given you then
-    usually should specify a target directory, because otherwise the
-    target may be named ...-hg.
+    The Perforce (P4) importer can be given a p4 depot path or a client
+    specification as source. It will convert all files in the source to a flat
+    Mercurial repository, ignoring labels, branches and integrations. Note
+    that when a depot path is given you then usually should specify a target
+    directory, because otherwise the target may be named ...-hg.
 
-    It is possible to limit the amount of source history to be
-    converted by specifying an initial Perforce revision.
+    It is possible to limit the amount of source history to be converted by
+    specifying an initial Perforce revision.
 
     --config convert.p4.startrev=0            (perforce changelist number)
         specify initial Perforce revision.
 
-
     Mercurial Destination
     ---------------------
 
--- a/tests/test-dispatch.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-dispatch.out	Thu Aug 06 18:48:00 2009 -0700
@@ -5,13 +5,13 @@
 
 output the current or given revision of files
 
-    Print the specified files as they were at the given revision. If
-    no revision is given, the parent of the working directory is used,
-    or tip if no revision is checked out.
+    Print the specified files as they were at the given revision. If no
+    revision is given, the parent of the working directory is used, or tip if
+    no revision is checked out.
 
-    Output may be to a file, in which case the name of the file is
-    given using a format string. The formatting rules are the same as
-    for the export command, with the following additions:
+    Output may be to a file, in which case the name of the file is given using
+    a format string. The formatting rules are the same as for the export
+    command, with the following additions:
 
     %s   basename of file being printed
     %d   dirname of file being printed, or '.' if in repository root
--- a/tests/test-dispatch.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-dispatch.py	Thu Aug 06 18:48:00 2009 -0700
@@ -15,14 +15,14 @@
 os.chdir('test1')
 
 # create file 'foo', add and commit
-f = file('foo', 'wb')
+f = open('foo', 'wb')
 f.write('foo\n')
 f.close()
 testdispatch("add foo")
 testdispatch("commit -m commit1 -d 2000-01-01 foo")
 
 # append to file 'foo' and commit
-f = file('foo', 'ab')
+f = open('foo', 'ab')
 f.write('bar\n')
 f.close()
 testdispatch("commit -m commit2 -d 2000-01-02 foo")
--- a/tests/test-extdiff.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-extdiff.out	Thu Aug 06 18:48:00 2009 -0700
@@ -7,14 +7,13 @@
 
 use 'echo' to diff repository (or selected files)
 
-            Show differences between revisions for the specified
-            files, using the 'echo' program.
+    Show differences between revisions for the specified files, using the
+    'echo' program.
 
-            When two revision arguments are given, then changes are
-            shown between those revisions. If only one revision is
-            specified then that revision is compared to the working
-            directory, and, when no revisions are specified, the
-            working directory files are compared to its parent.
+    When two revision arguments are given, then changes are shown between
+    those revisions. If only one revision is specified then that revision is
+    compared to the working directory, and, when no revisions are specified,
+    the working directory files are compared to its parent.
 
 options:
 
--- a/tests/test-help.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-help.out	Thu Aug 06 18:48:00 2009 -0700
@@ -170,11 +170,10 @@
 
 add the specified files on the next commit
 
-    Schedule files to be version controlled and added to the
-    repository.
+    Schedule files to be version controlled and added to the repository.
 
-    The files will be added to the repository at the next commit. To
-    undo an add before that, see hg forget.
+    The files will be added to the repository at the next commit. To undo an
+    add before that, see hg forget.
 
     If no names are given, add all files to the repository.
 
@@ -190,11 +189,10 @@
 
 add the specified files on the next commit
 
-    Schedule files to be version controlled and added to the
-    repository.
+    Schedule files to be version controlled and added to the repository.
 
-    The files will be added to the repository at the next commit. To
-    undo an add before that, see hg forget.
+    The files will be added to the repository at the next commit. To undo an
+    add before that, see hg forget.
 
     If no names are given, add all files to the repository.
 
@@ -213,22 +211,21 @@
 
     Differences between files are shown using the unified diff format.
 
-    NOTE: diff may generate unexpected results for merges, as it will
-    default to comparing against the working directory's first parent
-    changeset if no revisions are specified.
+    NOTE: diff may generate unexpected results for merges, as it will default
+    to comparing against the working directory's first parent changeset if no
+    revisions are specified.
 
-    When two revision arguments are given, then changes are shown
-    between those revisions. If only one revision is specified then
-    that revision is compared to the working directory, and, when no
-    revisions are specified, the working directory files are compared
-    to its parent.
+    When two revision arguments are given, then changes are shown between
+    those revisions. If only one revision is specified then that revision is
+    compared to the working directory, and, when no revisions are specified,
+    the working directory files are compared to its parent.
 
-    Without the -a/--text option, diff will avoid generating diffs of
-    files it detects as binary. With -a, diff will generate a diff
-    anyway, probably with undesirable results.
+    Without the -a/--text option, diff will avoid generating diffs of files it
+    detects as binary. With -a, diff will generate a diff anyway, probably
+    with undesirable results.
 
-    Use the -g/--git option to generate diffs in the git extended diff
-    format. For more information, read 'hg help diffs'.
+    Use the -g/--git option to generate diffs in the git extended diff format.
+    For more information, read 'hg help diffs'.
 
 options:
 
@@ -252,26 +249,25 @@
 
 show changed files in the working directory
 
-    Show status of files in the repository. If names are given, only
-    files that match are shown. Files that are clean or ignored or
-    the source of a copy/move operation, are not listed unless
-    -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
-    Unless options described with "show only ..." are given, the
-    options -mardu are used.
+    Show status of files in the repository. If names are given, only files
+    that match are shown. Files that are clean or ignored or the source of a
+    copy/move operation, are not listed unless -c/--clean, -i/--ignored,
+    -C/--copies or -A/--all are given. Unless options described with "show
+    only ..." are given, the options -mardu are used.
 
-    Option -q/--quiet hides untracked (unknown and ignored) files
-    unless explicitly requested with -u/--unknown or -i/--ignored.
+    Option -q/--quiet hides untracked (unknown and ignored) files unless
+    explicitly requested with -u/--unknown or -i/--ignored.
 
-    NOTE: status may appear to disagree with diff if permissions have
-    changed or a merge has occurred. The standard diff format does not
-    report permission changes and diff only reports changes relative
-    to one merge parent.
+    NOTE: status may appear to disagree with diff if permissions have changed
+    or a merge has occurred. The standard diff format does not report
+    permission changes and diff only reports changes relative to one merge
+    parent.
 
-    If one revision is given, it is used as the base revision.
-    If two revisions are given, the differences between them are
-    shown.
+    If one revision is given, it is used as the base revision. If two
+    revisions are given, the differences between them are shown.
 
     The codes used to show the status of files are:
+
     M = modified
     A = added
     R = removed
--- a/tests/test-hook	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-hook	Thu Aug 06 18:48:00 2009 -0700
@@ -230,4 +230,22 @@
 
 hg showconfig hooks | sed -e 's/ at .*>/>/'
 
+echo '# test python hook configured with python:[file]:[hook] syntax'
+cd ..
+mkdir d
+cd d
+hg init repo
+mkdir hooks
+
+cd hooks
+cat > testhooks.py <<EOF
+def testhook(**args):
+    print 'hook works'
+EOF
+echo '[hooks]' > ../repo/.hg/hgrc
+echo "pre-commit.test = python:`pwd`/testhooks.py:testhook" >> ../repo/.hg/hgrc
+
+cd ../repo
+hg commit
+
 exit 0
--- a/tests/test-hook.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-hook.out	Thu Aug 06 18:48:00 2009 -0700
@@ -160,3 +160,6 @@
 Automatically installed hook
 committed changeset 1:52998019f6252a2b893452765fcb0a47351a5708
 hooks.commit.auto=<function autohook>
+# test python hook configured with python:[file]:[hook] syntax
+hook works
+nothing changed
--- a/tests/test-inotify	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-inotify	Thu Aug 06 18:48:00 2009 -0700
@@ -35,4 +35,39 @@
 hg status .
 cd ..
 
+#issue 1375
+#Testing that we can remove a folder and then add a file with the same name
+echo % issue 1375
+
+mkdir h
+echo h > h/h
+hg ci -Am t
+hg rm h
+
+echo h >h
+hg add h
+
+hg status
+hg ci -m0
+
+# Test for issue1735: inotify watches files in .hg/merge
+hg st
+
+echo a > a
+
+hg ci -Am a
+hg st
+
+echo b >> a
+hg ci -m ab
+hg st
+
+echo c >> a
+hg st
+
+hg up 0
+hg st
+
+HGMERGE=internal:local hg up
+hg st
 kill `cat hg.pid`
--- a/tests/test-inotify.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-inotify.out	Thu Aug 06 18:48:00 2009 -0700
@@ -32,3 +32,15 @@
 ? hg.pid
 M dir/x
 M x
+% issue 1375
+adding h/h
+adding hg.pid
+removing h/h
+A h
+R h/h
+M a
+merging a
+1 files updated, 1 files merged, 2 files removed, 0 files unresolved
+M a
+3 files updated, 1 files merged, 0 files removed, 0 files unresolved
+M a
--- a/tests/test-keyword.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-keyword.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,50 +1,49 @@
 % help
 keyword extension - expand keywords in tracked files
 
-This extension expands RCS/CVS-like or self-customized $Keywords$ in
-tracked text files selected by your configuration.
+This extension expands RCS/CVS-like or self-customized $Keywords$ in tracked
+text files selected by your configuration.
 
-Keywords are only expanded in local repositories and not stored in the
-change history. The mechanism can be regarded as a convenience for the
-current user or for archive distribution.
+Keywords are only expanded in local repositories and not stored in the change
+history. The mechanism can be regarded as a convenience for the current user
+or for archive distribution.
 
-Configuration is done in the [keyword] and [keywordmaps] sections of
-hgrc files.
+Configuration is done in the [keyword] and [keywordmaps] sections of hgrc
+files.
 
 Example:
 
-    [keyword]
-    # expand keywords in every python file except those matching "x*"
-    **.py =
-    x*    = ignore
+[keyword]
+# expand keywords in every python file except those matching "x*"
+**.py =
+x*    = ignore
 
-Note: the more specific you are in your filename patterns
-      the less you lose speed in huge repositories.
+NOTE: the more specific you are in your filename patterns the less you lose
+speed in huge repositories.
 
-For [keywordmaps] template mapping and expansion demonstration and
-control run "hg kwdemo".
+For [keywordmaps] template mapping and expansion demonstration and control run
+"hg kwdemo".
 
 An additional date template filter {date|utcdate} is provided.
 
-The default template mappings (view with "hg kwdemo -d") can be
-replaced with customized keywords and templates. Again, run "hg
-kwdemo" to control the results of your config changes.
+The default template mappings (view with "hg kwdemo -d") can be replaced with
+customized keywords and templates. Again, run "hg kwdemo" to control the
+results of your config changes.
 
-Before changing/disabling active keywords, run "hg kwshrink" to avoid
-the risk of inadvertently storing expanded keywords in the change
-history.
+Before changing/disabling active keywords, run "hg kwshrink" to avoid the risk
+of inadvertently storing expanded keywords in the change history.
 
-To force expansion after enabling it, or a configuration change, run
-"hg kwexpand".
+To force expansion after enabling it, or a configuration change, run "hg
+kwexpand".
 
-Also, when committing with the record extension or using mq's qrecord,
-be aware that keywords cannot be updated. Again, run "hg kwexpand" on
-the files in question to update keyword expansions after all changes
-have been checked in.
+Also, when committing with the record extension or using mq's qrecord, be
+aware that keywords cannot be updated. Again, run "hg kwexpand" on the files
+in question to update keyword expansions after all changes have been checked
+in.
 
-Expansions spanning more than one line and incremental expansions,
-like CVS' $Log$, are not supported. A keyword template map
-"Log = {desc}" expands to the first line of the changeset description.
+Expansions spanning more than one line and incremental expansions, like CVS'
+$Log$, are not supported. A keyword template map "Log = {desc}" expands to the
+first line of the changeset description.
 
 list of commands:
 
@@ -211,6 +210,7 @@
 +$Id$
 +tests for different changenodes
 % qpop
+popping mqtest.diff
 patch queue now empty
 % qgoto - should imply qpush
 applying mqtest.diff
@@ -219,6 +219,7 @@
 $Id: c,v 40a904bbbe4c 1970/01/01 00:00:01 user $
 tests for different changenodes
 % qpop and move on
+popping mqtest.diff
 patch queue now empty
 % copy
 % kwfiles added
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/test-minirst.py	Thu Aug 06 18:48:00 2009 -0700
@@ -0,0 +1,138 @@
+#!/usr/bin/env python
+
+from mercurial import minirst
+
+def debugformat(title, text, width):
+    print "%s formatted to fit within %d characters:" % (title, width)
+    print "-" * 70
+    print minirst.format(text, width)
+    print "-" * 70
+    print
+
+paragraphs = """
+This is some text in the first paragraph.
+
+  An indented paragraph
+  with just two lines.
+
+
+The third paragraph. It is followed by some
+random lines with spurious spaces.
+ 
+  
+   
+  
+ 
+No indention
+ here, despite
+the uneven left
+ margin.
+
+      Only the
+    left-most line
+  (this line!)
+    is significant
+      for the indentation
+
+"""
+
+debugformat('paragraphs', paragraphs, 60)
+debugformat('paragraphs', paragraphs, 30)
+
+
+definitions = """
+A Term
+  Definition. The indented
+  lines make up the definition.
+Another Term
+  Another definition. The final line in the
+   definition determines the indentation, so
+    this will be indented with four spaces.
+
+  A Nested/Indented Term
+    Definition.
+"""
+
+debugformat('definitions', definitions, 60)
+debugformat('definitions', definitions, 30)
+
+
+literals = r"""
+The fully minimized form is the most
+convenient form::
+
+  Hello
+    literal
+      world
+
+In the partially minimized form a paragraph
+simply ends with space-double-colon. ::
+
+  ////////////////////////////////////////
+  long un-wrapped line in a literal block
+  \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
+
+::
+
+  This literal block is started with '::',
+    the so-called expanded form. The paragraph
+      with '::' disappears in the final output.
+"""
+
+debugformat('literals', literals, 60)
+debugformat('literals', literals, 30)
+
+
+lists = """
+- This is the first list item.
+
+  Second paragraph in the first list item.
+
+- List items need not be separated
+  by a blank line.
+- And will be rendered without
+  one in any case.
+
+We can have indented lists:
+
+  - This is an indented list item
+
+  - Another indented list item::
+
+      - A literal block in the middle
+            of an indented list.
+
+      (The above is not a list item since we are in the literal block.)
+
+::
+
+  Literal block with no indentation.
+"""
+
+debugformat('lists', lists, 60)
+debugformat('lists', lists, 30)
+
+
+options = """
+There is support for simple option lists,
+but only with long options:
+
+--all      Output all.
+--both     Output both (this description is
+           quite long).
+--long     Output all day long.
+
+--par      This option has two paragraphs in its description.
+           This is the first.
+
+           This is the second.  Blank lines may be omitted between
+           options (as above) or left in (as here).
+
+The next paragraph looks like an option list, but lacks the two-space
+marker after the option. It is treated as a normal paragraph:
+
+--foo bar baz
+"""
+
+debugformat('options', options, 60)
+debugformat('options', options, 30)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/test-minirst.py.out	Thu Aug 06 18:48:00 2009 -0700
@@ -0,0 +1,209 @@
+paragraphs formatted to fit within 60 characters:
+----------------------------------------------------------------------
+This is some text in the first paragraph.
+
+  An indented paragraph with just two lines.
+
+The third paragraph. It is followed by some random lines
+with spurious spaces.
+
+No indention here, despite the uneven left margin.
+
+  Only the left-most line (this line!) is significant for
+  the indentation
+----------------------------------------------------------------------
+
+paragraphs formatted to fit within 30 characters:
+----------------------------------------------------------------------
+This is some text in the first
+paragraph.
+
+  An indented paragraph with
+  just two lines.
+
+The third paragraph. It is
+followed by some random lines
+with spurious spaces.
+
+No indention here, despite the
+uneven left margin.
+
+  Only the left-most line
+  (this line!) is significant
+  for the indentation
+----------------------------------------------------------------------
+
+definitions formatted to fit within 60 characters:
+----------------------------------------------------------------------
+A Term
+  Definition. The indented lines make up the definition.
+Another Term
+    Another definition. The final line in the definition
+    determines the indentation, so this will be indented
+    with four spaces.
+  A Nested/Indented Term
+    Definition.
+----------------------------------------------------------------------
+
+definitions formatted to fit within 30 characters:
+----------------------------------------------------------------------
+A Term
+  Definition. The indented
+  lines make up the
+  definition.
+Another Term
+    Another definition. The
+    final line in the
+    definition determines the
+    indentation, so this will
+    be indented with four
+    spaces.
+  A Nested/Indented Term
+    Definition.
+----------------------------------------------------------------------
+
+literals formatted to fit within 60 characters:
+----------------------------------------------------------------------
+The fully minimized form is the most convenient form:
+
+Hello
+  literal
+    world
+
+In the partially minimized form a paragraph simply ends with
+space-double-colon.
+
+////////////////////////////////////////
+long un-wrapped line in a literal block
+\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
+
+This literal block is started with '::',
+  the so-called expanded form. The paragraph
+    with '::' disappears in the final output.
+----------------------------------------------------------------------
+
+literals formatted to fit within 30 characters:
+----------------------------------------------------------------------
+The fully minimized form is
+the most convenient form:
+
+Hello
+  literal
+    world
+
+In the partially minimized
+form a paragraph simply ends
+with space-double-colon.
+
+////////////////////////////////////////
+long un-wrapped line in a literal block
+\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
+
+This literal block is started with '::',
+  the so-called expanded form. The paragraph
+    with '::' disappears in the final output.
+----------------------------------------------------------------------
+
+lists formatted to fit within 60 characters:
+----------------------------------------------------------------------
+- This is the first list item.
+
+  Second paragraph in the first list item.
+
+- List items need not be separated by a blank line.
+- And will be rendered without one in any case.
+
+We can have indented lists:
+
+  - This is an indented list item
+  - Another indented list item:
+
+    - A literal block in the middle
+          of an indented list.
+
+    (The above is not a list item since we are in the literal block.)
+
+Literal block with no indentation.
+----------------------------------------------------------------------
+
+lists formatted to fit within 30 characters:
+----------------------------------------------------------------------
+- This is the first list item.
+
+  Second paragraph in the
+  first list item.
+
+- List items need not be
+  separated by a blank line.
+- And will be rendered without
+  one in any case.
+
+We can have indented lists:
+
+  - This is an indented list
+    item
+  - Another indented list
+    item:
+
+    - A literal block in the middle
+          of an indented list.
+
+    (The above is not a list item since we are in the literal block.)
+
+Literal block with no indentation.
+----------------------------------------------------------------------
+
+options formatted to fit within 60 characters:
+----------------------------------------------------------------------
+There is support for simple option lists, but only with long
+options:
+
+--all      Output all.
+--both     Output both (this description is quite long).
+--long     Output all day long.
+--par      This option has two paragraphs in its
+           description. This is the first.
+
+           This is the second.  Blank lines may be omitted
+           between options (as above) or left in (as here).
+
+The next paragraph looks like an option list, but lacks the
+two-space marker after the option. It is treated as a normal
+paragraph:
+
+--foo bar baz
+----------------------------------------------------------------------
+
+options formatted to fit within 30 characters:
+----------------------------------------------------------------------
+There is support for simple
+option lists, but only with
+long options:
+
+--all      Output all.
+--both     Output both (this
+           description is
+           quite long).
+--long     Output all day
+           long.
+--par      This option has two
+           paragraphs in its
+           description. This
+           is the first.
+
+           This is the second.
+           Blank lines may be
+           omitted between
+           options (as above)
+           or left in (as
+           here).
+
+The next paragraph looks like
+an option list, but lacks the
+two-space marker after the
+option. It is treated as a
+normal paragraph:
+
+--foo bar baz
+----------------------------------------------------------------------
+
--- a/tests/test-mq	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq	Thu Aug 06 18:48:00 2009 -0700
@@ -107,9 +107,18 @@
 hg qpop
 checkundo qpop
 
-echo % qpush
+echo % qpush with dump of tag cache
 
+# Dump the tag cache to ensure that it has exactly one head after qpush.
+rm -f .hg/tags.cache
+hg tags > /dev/null
+echo ".hg/tags.cache (pre qpush):"
+sed 's/ [0-9a-f]*//' .hg/tags.cache
 hg qpush
+hg tags > /dev/null
+echo ".hg/tags.cache (post qpush):"
+sed 's/ [0-9a-f]*//' .hg/tags.cache
+
 checkundo qpush
 
 cd ..
--- a/tests/test-mq-caches.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-caches.out	Thu Aug 06 18:48:00 2009 -0700
@@ -5,6 +5,7 @@
 No branch cache
 
 # some regular revisions
+popping p1
 patch queue now empty
 tip: 1
 3f910abad313ff802d3a23a7529433872df9b3ae 1
@@ -43,6 +44,9 @@
 qbase: 1
 
 # detect an invalid cache
+popping p2
+popping p1
+popping p0
 patch queue now empty
 applying p0
 applying p1
--- a/tests/test-mq-eol.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-eol.out	Thu Aug 06 18:48:00 2009 -0700
@@ -9,12 +9,14 @@
 patch failed, unable to continue (try -v)
 patch failed, rejects left in working dir
 errors during apply, please fix and refresh eol.diff
+popping eol.diff
 patch queue now empty
 % invalid eol
 applying eol.diff
 patch failed, unable to continue (try -v)
 patch failed, rejects left in working dir
 errors during apply, please fix and refresh eol.diff
+popping eol.diff
 patch queue now empty
 % force LF
 applying eol.diff
@@ -42,6 +44,7 @@
 c<CR><LF>
 d<CR><LF>
 z
+popping eol.diff
 patch queue now empty
 % push again forcing LF and compare revisions
 applying eol.diff
@@ -51,6 +54,7 @@
 c<CR><LF>
 d<CR><LF>
 z
+popping eol.diff
 patch queue now empty
 % push again without LF and compare revisions
 applying eol.diff
@@ -60,4 +64,5 @@
 c<CR><LF>
 d<CR><LF>
 z
+popping eol.diff
 patch queue now empty
--- a/tests/test-mq-guards.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-guards.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,4 +1,7 @@
 adding x
+popping c.patch
+popping b.patch
+popping a.patch
 patch queue now empty
 % should fail
 abort: no patch named does-not-exist.patch
@@ -9,6 +12,7 @@
 % should guard a.patch
 % should print +a
 a.patch: +a
+popping a.patch
 patch queue now empty
 % should fail
 cannot push 'a.patch' - guarded by ['+a']
@@ -16,6 +20,7 @@
 % should push b.patch
 applying b.patch
 now at: b.patch
+popping b.patch
 patch queue now empty
 % test selection of an empty guard
 abort: guard cannot be an empty string
@@ -34,6 +39,9 @@
 % should push c.patch
 applying c.patch
 now at: c.patch
+popping c.patch
+popping b.patch
+popping a.patch
 patch queue now empty
 guards deactivated
 number of unguarded, unapplied patches has changed from 3 to 2
@@ -41,6 +49,8 @@
 applying b.patch
 applying c.patch
 now at: c.patch
+popping c.patch
+popping b.patch
 patch queue now empty
 number of unguarded, unapplied patches has changed from 1 to 2
 % should push a.patch, not b.patch
@@ -48,6 +58,8 @@
 now at: a.patch
 applying c.patch
 now at: c.patch
+popping c.patch
+popping a.patch
 patch queue now empty
 % should push b.patch
 applying b.patch
@@ -55,6 +67,8 @@
 applying c.patch
 now at: c.patch
 c.patch
+popping c.patch
+popping b.patch
 patch queue now empty
 number of unguarded, unapplied patches has changed from 2 to 3
 % should push a.patch, b.patch
@@ -62,6 +76,8 @@
 now at: a.patch
 applying b.patch
 now at: b.patch
+popping b.patch
+popping a.patch
 patch queue now empty
 number of unguarded, unapplied patches has changed from 3 to 2
 % list patches and guards
@@ -83,6 +99,8 @@
 now at: c.patch
 guards deactivated
 popping guarded patches
+popping c.patch
+popping b.patch
 patch queue now empty
 reapplying unguarded patches
 applying c.patch
@@ -100,6 +118,7 @@
 new.patch: +1 +2 -3
 b.patch: +2
 c.patch: unguarded
+popping d.patch
 now at: c.patch
 % should show new.patch and b.patch as Guarded, c.patch as Applied
 % and d.patch as Unapplied
@@ -112,6 +131,7 @@
 1 G b.patch
 2 A c.patch
 3 G d.patch
+popping c.patch
 patch queue now empty
 new.patch: +1 +2 -3
 b.patch: +2
--- a/tests/test-mq-header-date.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-header-date.out	Thu Aug 06 18:48:00 2009 -0700
@@ -42,6 +42,7 @@
 +2
 1: [mq]: 2.patch - test
 0: [mq]: 1.patch - test
+popping 2.patch
 now at: 1.patch
 ==== qnew -d -m
 # HG changeset patch
@@ -127,8 +128,10 @@
 2: Four - test
 1: Three (again) - test
 0: [mq]: 1.patch - test
+popping 4.patch
 now at: 3.patch
 ==== qnew with HG header
+popping 5.patch
 now at: 3.patch
 # HG changeset patch
 # Date 10 0
@@ -185,6 +188,7 @@
 2: [mq]: 5.patch - test
 1: Three (again) - test
 0: [mq]: 1.patch - test
+popping 6.patch
 now at: 5.patch
 ==== qnew -d
 adding 7
@@ -240,6 +244,7 @@
 2: [mq]: 5.patch - test
 1: Three (again) - test
 0: [mq]: 1.patch - test
+popping 8.patch
 now at: 7.patch
 ==== qnew -m
 adding 9
@@ -270,8 +275,13 @@
 2: [mq]: 5.patch - test
 1: Three (again) - test
 0: [mq]: 1.patch - test
+popping 9.patch
 now at: 7.patch
 ==== qpop -a / qpush -a
+popping 7.patch
+popping 5.patch
+popping 3.patch
+popping 1.patch
 patch queue now empty
 applying 1.patch
 applying 3.patch
--- a/tests/test-mq-header-from.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-header-from.out	Thu Aug 06 18:48:00 2009 -0700
@@ -131,6 +131,7 @@
 1: [mq]: 2.patch - jane
 0: [mq]: 1.patch - mary
 ==== qnew with HG header
+popping 5.patch
 now at: 4.patch
 now at: 5.patch
 # HG changeset patch
@@ -184,6 +185,11 @@
 1: [mq]: 2.patch - jane
 0: [mq]: 1.patch - mary
 ==== qpop -a / qpush -a
+popping 5.patch
+popping 4.patch
+popping 3.patch
+popping 2.patch
+popping 1.patch
 patch queue now empty
 applying 1.patch
 applying 2.patch
--- a/tests/test-mq-merge.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-merge.out	Thu Aug 06 18:48:00 2009 -0700
@@ -10,6 +10,8 @@
 applying rm_a
 now at: rm_a
 b
+popping rm_a
+popping .hg.patches.merge.marker
 patch queue now empty
 
 % init t2
--- a/tests/test-mq-missingfiles.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-missingfiles.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,4 +1,5 @@
 adding b
+popping changeb
 patch queue now empty
 % push patch with missing target
 applying changeb
@@ -26,6 +27,7 @@
 +c
 +c
 adding b
+popping changeb
 patch queue now empty
 % push git patch with missing target
 applying changeb
@@ -48,6 +50,7 @@
 
 % test push creating directory during git copy or rename
 adding a
+popping patch
 patch queue now empty
 applying patch
 now at: patch
--- a/tests/test-mq-pull-from-bundle.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-pull-from-bundle.out	Thu Aug 06 18:48:00 2009 -0700
@@ -13,6 +13,7 @@
 1: main: one updated.
 ====== Setup queue
 adding two
+popping two.patch
 patch queue now empty
 ====== Bundle queue
 1 changesets found
--- a/tests/test-mq-qdelete.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-qdelete.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,6 +1,7 @@
 adding base
 abort: qdelete requires at least one revision or patch name
 abort: cannot delete applied patch c
+popping c
 now at: b
 a
 b
@@ -8,6 +9,7 @@
 b
 series
 status
+popping b
 now at: a
 a
 b
@@ -30,6 +32,7 @@
 no patches applied
 abort: revision 0 is not managed
 abort: cannot delete revision 2 above applied patches
+popping c
 now at: b
 abort: unknown revision 'c'!
 applying c
--- a/tests/test-mq-qdiff.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-qdiff.out	Thu Aug 06 18:48:00 2009 -0700
@@ -26,6 +26,7 @@
 +patched
 % revert
 % qpop
+popping mqbase
 patch queue now empty
 % qdelete mqbase
 % commit 2
--- a/tests/test-mq-qfold.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-qfold.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,6 +1,8 @@
 % init
 adding a
 % fold in the middle of the queue
+popping p3
+popping p2
 now at: p1
 --- a/a
 +++ b/a
--- a/tests/test-mq-qgoto.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-qgoto.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,17 +1,24 @@
 adding a
+popping c.patch
+popping b.patch
 now at: a.patch
 applying b.patch
 applying c.patch
 now at: c.patch
+popping c.patch
 now at: b.patch
 
 % Using index
+popping b.patch
 now at: a.patch
 applying b.patch
 applying c.patch
 now at: c.patch
 
 % No warnings when using index
+popping bug141421
+popping bug314159
+popping c.patch
 now at: b.patch
 applying c.patch
 applying bug314159
--- a/tests/test-mq-qimport.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-qimport.out	Thu Aug 06 18:48:00 2009 -0700
@@ -28,12 +28,14 @@
 applying url.diff
 now at: url.diff
 foo
+popping url.diff
 patch queue now empty
 % qimport -f
 adding url.diff to series file
 applying url.diff
 now at: url.diff
 foo2
+popping url.diff
 patch queue now empty
 % build diff with CRLF
 adding b
--- a/tests/test-mq-qnew.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-qnew.out	Thu Aug 06 18:48:00 2009 -0700
@@ -20,6 +20,9 @@
 abort: patch "first.patch" already exists
 abort: patch "first.patch" already exists
 % qnew -f from a subdirectory
+popping first.patch
+popping mtest.patch
+popping test.patch
 patch queue now empty
 adding d/b
 M d/b
--- a/tests/test-mq-qpush-fail.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-qpush-fail.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,6 +1,9 @@
 adding foo
 % test qpush on empty series
 no patches in series
+popping bad-patch
+popping patch2
+popping patch1
 patch queue now empty
 applying patch1
 applying patch2
--- a/tests/test-mq-symlinks.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq-symlinks.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,9 +1,11 @@
 a -> a not a symlink
 a -> b
+popping symlink.patch
 now at: base.patch
 applying symlink.patch
 now at: symlink.patch
 a -> b
+popping removesl.patch
 now at: symlink.patch
 applying removesl.patch
 now at: removesl.patch
--- a/tests/test-mq.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-mq.out	Thu Aug 06 18:48:00 2009 -0700
@@ -2,11 +2,11 @@
 mq extension - manage a stack of patches
 
 This extension lets you work with a stack of patches in a Mercurial
-repository. It manages two stacks of patches - all known patches, and
-applied patches (subset of known patches).
+repository. It manages two stacks of patches - all known patches, and applied
+patches (subset of known patches).
 
-Known patches are represented as patch files in the .hg/patches
-directory. Applied patches are both patch files and changesets.
+Known patches are represented as patch files in the .hg/patches directory.
+Applied patches are both patch files and changesets.
 
 Common tasks (use "hg help command" for more details):
 
@@ -108,16 +108,26 @@
  a
 +a
 % qpop
+popping test.patch
 patch queue now empty
-% qpush
+% qpush with dump of tag cache
+.hg/tags.cache (pre qpush):
+1
+
 applying test.patch
 now at: test.patch
+.hg/tags.cache (post qpush):
+2
+
 % pop/push outside repo
+popping test.patch
 patch queue now empty
 applying test.patch
 now at: test.patch
 % qrefresh in subdir
 % pop/push -a in subdir
+popping test2.patch
+popping test.patch
 patch queue now empty
 applying test.patch
 applying test2.patch
@@ -125,6 +135,7 @@
 % qseries
 test.patch
 test2.patch
+popping test2.patch
 now at: test.patch
 0 A test.patch: foo bar
 1 U test2.patch: 
@@ -140,6 +151,7 @@
 % qnext
 all patches applied
 % pop, qnext, qprev, qapplied
+popping test2.patch
 now at: test.patch
 test2.patch
 only one patch applied
@@ -156,17 +168,24 @@
 % qpush/qpop with index
 applying test2.patch
 now at: test2.patch
+popping test2.patch
+popping test1b.patch
 now at: test.patch
 applying test1b.patch
 now at: test1b.patch
 applying test2.patch
 now at: test2.patch
+popping test2.patch
 now at: test1b.patch
+popping test1b.patch
 now at: test.patch
 applying test1b.patch
 applying test2.patch
 now at: test2.patch
 % push should succeed
+popping test2.patch
+popping test1b.patch
+popping test.patch
 patch queue now empty
 pushing to ../../k
 searching for changes
@@ -180,6 +199,9 @@
 applying test2.patch
 now at: test2.patch
   % pops all patches and succeeds
+popping test2.patch
+popping test1b.patch
+popping test.patch
 patch queue now empty
   qpop -a succeeds
   % does nothing and succeeds
@@ -193,6 +215,7 @@
 now at: test.patch
   qpush succeeds
   % pops a patch and succeeds
+popping test.patch
 patch queue now empty
   qpop succeeds
   % pushes up to test1b.patch and succeeds
@@ -213,6 +236,7 @@
 abort: patch test2.patch is not applied
   qpop test2.patch fails
   % pops up to test.patch and succeeds
+popping test1b.patch
 now at: test.patch
   qpop test.patch succeeds
   % pushes all patches and succeeds
@@ -269,6 +293,8 @@
 +f
 M a
 % qpush failure
+popping bar
+popping foo
 patch queue now empty
 applying foo
 applying bar
@@ -284,6 +310,7 @@
 1 qbase foo
 2 qtip bar tip
 % bad node in status
+popping bar
 now at: foo
 changeset:   0:cb9a9f314b8b
 mq status file refers to unknown node
@@ -308,6 +335,7 @@
 diff --git a/new b/copy
 copy from new
 copy to copy
+popping copy
 now at: new
 applying copy
 now at: copy
@@ -320,6 +348,7 @@
 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
 created new head
 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
+popping bar
 adding branch
 adding changesets
 adding manifests
@@ -354,6 +383,7 @@
 
 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
+popping bar
 adding branch
 adding changesets
 adding manifests
@@ -386,6 +416,7 @@
 % refresh omitting an added file
 C newfile
 A newfile
+popping baz
 now at: bar
 % create a git patch
 diff --git a/alexander b/alexander
@@ -393,6 +424,7 @@
 8ba2a2f3e77b55d03051ff9c24ad65e7  bucephalus
 diff --git a/bucephalus b/bucephalus
 % check binary patches can be popped and pushed
+popping addbucephalus
 now at: addalexander
 applying addbucephalus
 now at: addbucephalus
@@ -461,6 +493,7 @@
     rev 0: add foo
 patch repo:
     rev 0: checkpoint
+popping patch1
 patch queue now empty
 main repo:
     rev 0: add foo
@@ -475,12 +508,14 @@
     rev 0: checkpoint
 % test applying on an empty file (issue 1033)
 adding a
+popping changea
 patch queue now empty
 applying changea
 now at: changea
 % test qpush with --force, issue1087
 adding bye.txt
 adding hello.txt
+popping empty
 patch queue now empty
 % qpush should fail, local changes
 abort: local changes found, refresh first
@@ -510,6 +545,7 @@
 summary:     imported patch empty
 
 
+popping empty
 patch queue now empty
 % qpush should fail, local changes
 abort: local changes found, refresh first
@@ -539,4 +575,5 @@
 % test popping revisions not in working dir ancestry
 0 A empty
 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+popping empty
 patch queue now empty
--- a/tests/test-notify.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-notify.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,61 +1,60 @@
 notify extension - hooks for sending email notifications at commit/push time
 
-Subscriptions can be managed through hgrc. Default mode is to print
+Subscriptions can be managed through a hgrc file. Default mode is to print
 messages to stdout, for testing and configuring.
 
-To use, configure notify extension and enable in hgrc like this:
+To use, configure the notify extension and enable it in hgrc like this:
 
-   [extensions]
-   hgext.notify =
+[extensions]
+hgext.notify =
 
-   [hooks]
-   # one email for each incoming changeset
-   incoming.notify = python:hgext.notify.hook
-   # batch emails when many changesets incoming at one time
-   changegroup.notify = python:hgext.notify.hook
+[hooks]
+# one email for each incoming changeset
+incoming.notify = python:hgext.notify.hook
+# batch emails when many changesets incoming at one time
+changegroup.notify = python:hgext.notify.hook
 
-   [notify]
-   # config items go in here
+[notify]
+# config items go here
 
- config items:
+Required configuration items:
 
- REQUIRED:
-   config = /path/to/file # file containing subscriptions
+config = /path/to/file # file containing subscriptions
+
+Optional configuration items:
 
- OPTIONAL:
-   test = True            # print messages to stdout for testing
-   strip = 3              # number of slashes to strip for url paths
-   domain = example.com   # domain to use if committer missing domain
-   style = ...            # style file to use when formatting email
-   template = ...         # template to use when formatting email
-   incoming = ...         # template to use when run as incoming hook
-   changegroup = ...      # template when run as changegroup hook
-   maxdiff = 300          # max lines of diffs to include (0=none, -1=all)
-   maxsubject = 67        # truncate subject line longer than this
-   diffstat = True        # add a diffstat before the diff content
-   sources = serve        # notify if source of incoming changes in this list
-                          # (serve == ssh or http, push, pull, bundle)
-   [email]
-   from = user@host.com   # email address to send as if none given
-   [web]
-   baseurl = http://hgserver/... # root of hg web site for browsing commits
+test = True            # print messages to stdout for testing
+strip = 3              # number of slashes to strip for url paths
+domain = example.com   # domain to use if committer missing domain
+style = ...            # style file to use when formatting email
+template = ...         # template to use when formatting email
+incoming = ...         # template to use when run as incoming hook
+changegroup = ...      # template when run as changegroup hook
+maxdiff = 300          # max lines of diffs to include (0=none, -1=all)
+maxsubject = 67        # truncate subject line longer than this
+diffstat = True        # add a diffstat before the diff content
+sources = serve        # notify if source of incoming changes in this list
+                       # (serve == ssh or http, push, pull, bundle)
+[email]
+from = user@host.com   # email address to send as if none given
+[web]
+baseurl = http://hgserver/... # root of hg web site for browsing commits
 
- notify config file has same format as regular hgrc. it has two
- sections so you can express subscriptions in whatever way is handier
- for you.
+The notify config file has same format as a regular hgrc file. It has two
+sections so you can express subscriptions in whatever way is handier for you.
 
-   [usersubs]
-   # key is subscriber email, value is ","-separated list of glob patterns
-   user@host = pattern
+[usersubs]
+# key is subscriber email, value is ","-separated list of glob patterns
+user@host = pattern
 
-   [reposubs]
-   # key is glob pattern, value is ","-separated list of subscriber emails
-   pattern = user@host
+[reposubs]
+# key is glob pattern, value is ","-separated list of subscriber emails
+pattern = user@host
 
- glob patterns are matched against path to repository root.
+Glob patterns are matched against path to repository root.
 
- if you like, you can put notify config file in repository that users
- can push changes to, they can manage their own subscriptions.
+If you like, you can put notify config file in repository that users can push
+changes to, they can manage their own subscriptions.
 
 no commands defined
 % commit
--- a/tests/test-patchbomb.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-patchbomb.out	Thu Aug 06 18:48:00 2009 -0700
@@ -10,7 +10,7 @@
 X-Mercurial-Node: 8580ff50825a50c8f716709acdf8de0deddcd6ab
 Message-Id: <8580ff50825a50c8f716.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -42,7 +42,7 @@
 Subject: [PATCH 0 of 2] test
 Message-Id: <patchbomb.120@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:02:00 -0000
+Date: Thu, 01 Jan 1970 00:02:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -58,7 +58,7 @@
 In-Reply-To: <patchbomb.120@
 References: <patchbomb.120@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:02:01 -0000
+Date: Thu, 01 Jan 1970 00:02:01 +0000
 From: quux
 To: foo
 Cc: bar
@@ -86,7 +86,7 @@
 In-Reply-To: <patchbomb.120@
 References: <patchbomb.120@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:02:02 -0000
+Date: Thu, 01 Jan 1970 00:02:02 +0000
 From: quux
 To: foo
 Cc: bar
@@ -124,7 +124,7 @@
 Subject: test
 Message-Id: <patchbomb.180@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:03:00 -0000
+Date: Thu, 01 Jan 1970 00:03:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -157,13 +157,13 @@
 adding utf
 % no mime encoding for email --test
 % md5sum of 8-bit output
-1b28ee86c937a1f9e2bf6fc5eabd00a5  mailtest
+e726c29b3008e77994c7572563e57c34  mailtest
 % mime encoded mbox (base64)
 This patch series consists of 1 patches.
 
 
 Writing [PATCH] charset=utf-8; content-transfer-encoding: base64 ...
-From quux Thu Jan 01 00:04:01 1970
+From quux Thu Jan  1 00:04:01 1970
 Content-Type: text/plain; charset="utf-8"
 MIME-Version: 1.0
 Content-Transfer-Encoding: base64
@@ -171,7 +171,7 @@
 X-Mercurial-Node: c3c9e37db9f4fe4882cda39baf42fed6bad8b15a
 Message-Id: <c3c9e37db9f4fe4882cd.240@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:04:00 -0000
+Date: Thu, 01 Jan 1970 00:04:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -192,13 +192,13 @@
 adding qp
 % no mime encoding for email --test
 % md5sum of qp output
-7b5f11d50349b32eff4a9b2daaa82e7f  mailtest
+0402c7d033e04044e423bb04816f9dae  mailtest
 % mime encoded mbox (quoted-printable)
 This patch series consists of 1 patches.
 
 
 Writing [PATCH] charset=utf-8; content-transfer-encoding: quoted-printable ...
-From quux Thu Jan 01 00:04:01 1970
+From quux Thu Jan  1 00:04:01 1970
 Content-Type: text/plain; charset="us-ascii"
 MIME-Version: 1.0
 Content-Transfer-Encoding: quoted-printable
@@ -206,7 +206,7 @@
 X-Mercurial-Node: c655633f8c87700bb38cc6a59a2753bdc5a6c376
 Message-Id: <c655633f8c87700bb38c.240@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:04:00 -0000
+Date: Thu, 01 Jan 1970 00:04:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -249,7 +249,7 @@
 
 Writing [PATCH] charset=us-ascii; content-transfer-encoding: 8bit ...
 % md5sum of 8-bit output
-e61684fc0bcccba4204714be37951893  mboxfix
+0920ef519c29b6a1742047ad9f203fc5  mboxfix
 % test diffstat for single patch
 This patch series consists of 1 patches.
 
@@ -267,7 +267,7 @@
 X-Mercurial-Node: ff2c9fa2018b15fa74b33363bda9527323e2a99f
 Message-Id: <ff2c9fa2018b15fa74b3.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -319,7 +319,7 @@
 Subject: [PATCH 0 of 2] test
 Message-Id: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -339,7 +339,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:01 -0000
+Date: Thu, 01 Jan 1970 00:01:01 +0000
 From: quux
 To: foo
 Cc: bar
@@ -371,7 +371,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:02 -0000
+Date: Thu, 01 Jan 1970 00:01:02 +0000
 From: quux
 To: foo
 Cc: bar
@@ -404,7 +404,7 @@
 X-Mercurial-Node: ff2c9fa2018b15fa74b33363bda9527323e2a99f
 Message-Id: <ff2c9fa2018b15fa74b3.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -440,7 +440,7 @@
 X-Mercurial-Node: c655633f8c87700bb38cc6a59a2753bdc5a6c376
 Message-Id: <c655633f8c87700bb38c.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -495,7 +495,7 @@
 Subject: [PATCH 0 of 3] test
 Message-Id: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -510,7 +510,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:01 -0000
+Date: Thu, 01 Jan 1970 00:01:01 +0000
 From: quux
 To: foo
 Cc: bar
@@ -544,7 +544,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:02 -0000
+Date: Thu, 01 Jan 1970 00:01:02 +0000
 From: quux
 To: foo
 Cc: bar
@@ -579,7 +579,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:03 -0000
+Date: Thu, 01 Jan 1970 00:01:03 +0000
 From: quux
 To: foo
 Cc: bar
@@ -631,7 +631,7 @@
 X-Mercurial-Node: ff2c9fa2018b15fa74b33363bda9527323e2a99f
 Message-Id: <ff2c9fa2018b15fa74b3.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -676,7 +676,7 @@
 X-Mercurial-Node: c655633f8c87700bb38cc6a59a2753bdc5a6c376
 Message-Id: <c655633f8c87700bb38c.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -740,7 +740,7 @@
 Subject: [PATCH 0 of 3] test
 Message-Id: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -755,7 +755,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:01 -0000
+Date: Thu, 01 Jan 1970 00:01:01 +0000
 From: quux
 To: foo
 Cc: bar
@@ -798,7 +798,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:02 -0000
+Date: Thu, 01 Jan 1970 00:01:02 +0000
 From: quux
 To: foo
 Cc: bar
@@ -842,7 +842,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:03 -0000
+Date: Thu, 01 Jan 1970 00:01:03 +0000
 From: quux
 To: foo
 Cc: bar
@@ -906,7 +906,7 @@
 Subject: [PATCH 0 of 1] test
 Message-Id: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -922,7 +922,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:01 -0000
+Date: Thu, 01 Jan 1970 00:01:01 +0000
 From: quux
 To: foo
 Cc: bar
@@ -954,7 +954,7 @@
 Subject: [PATCH 0 of 2] test
 Message-Id: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -970,7 +970,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:01 -0000
+Date: Thu, 01 Jan 1970 00:01:01 +0000
 From: quux
 To: foo
 Cc: bar
@@ -998,7 +998,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:02 -0000
+Date: Thu, 01 Jan 1970 00:01:02 +0000
 From: quux
 To: foo
 Cc: bar
@@ -1028,7 +1028,7 @@
 X-Mercurial-Node: ff2c9fa2018b15fa74b33363bda9527323e2a99f
 Message-Id: <ff2c9fa2018b15fa74b3.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -1067,7 +1067,7 @@
 Subject: [PATCH 0 of 2] test
 Message-Id: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -1082,7 +1082,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:01 -0000
+Date: Thu, 01 Jan 1970 00:01:01 +0000
 From: quux
 To: foo
 Cc: bar
@@ -1116,7 +1116,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:02 -0000
+Date: Thu, 01 Jan 1970 00:01:02 +0000
 From: quux
 To: foo
 Cc: bar
@@ -1155,7 +1155,7 @@
 In-Reply-To: <baz>
 References: <baz>
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -1192,7 +1192,7 @@
 In-Reply-To: <baz>
 References: <baz>
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:00 -0000
+Date: Thu, 01 Jan 1970 00:01:00 +0000
 From: quux
 To: foo
 Cc: bar
@@ -1208,7 +1208,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:01 -0000
+Date: Thu, 01 Jan 1970 00:01:01 +0000
 From: quux
 To: foo
 Cc: bar
@@ -1236,7 +1236,7 @@
 In-Reply-To: <patchbomb.60@
 References: <patchbomb.60@
 User-Agent: Mercurial-patchbomb
-Date: Thu, 01 Jan 1970 00:01:02 -0000
+Date: Thu, 01 Jan 1970 00:01:02 +0000
 From: quux
 To: foo
 Cc: bar
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/test-path-normalization	Thu Aug 06 18:48:00 2009 -0700
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+hg clone --quiet $TESTDIR/test-path-normalization.hg t
+exec hg st -R t
Binary file tests/test-path-normalization.hg has changed
--- a/tests/test-qrecord.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-qrecord.out	Thu Aug 06 18:48:00 2009 -0700
@@ -28,8 +28,7 @@
 
 interactively record a new patch
 
-    See 'hg help qnew' & 'hg help record' for more information and
-    usage.
+    See 'hg help qnew' & 'hg help record' for more information and usage.
 
 options:
 
--- a/tests/test-rebase-mq.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-rebase-mq.out	Thu Aug 06 18:48:00 2009 -0700
@@ -79,6 +79,8 @@
 +mq1r1mq2
 
 % Adding one git-style patch and one normal
+popping f2.patch
+popping f.patch
 patch queue now empty
 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 % Git patch
--- a/tests/test-rebase-parameters.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-rebase-parameters.out	Thu Aug 06 18:48:00 2009 -0700
@@ -6,9 +6,9 @@
 
 move changeset (and descendants) to a different branch
 
-    Rebase uses repeated merging to graft changesets from one part of
-    history onto another. This can be useful for linearizing local
-    changes relative to a master development tree.
+    Rebase uses repeated merging to graft changesets from one part of history
+    onto another. This can be useful for linearizing local changes relative to
+    a master development tree.
 
     If a rebase is interrupted to manually resolve a merge, it can be
     continued with --continue/-c or aborted with --abort/-a.
@@ -34,9 +34,9 @@
 
 move changeset (and descendants) to a different branch
 
-    Rebase uses repeated merging to graft changesets from one part of
-    history onto another. This can be useful for linearizing local
-    changes relative to a master development tree.
+    Rebase uses repeated merging to graft changesets from one part of history
+    onto another. This can be useful for linearizing local changes relative to
+    a master development tree.
 
     If a rebase is interrupted to manually resolve a merge, it can be
     continued with --continue/-c or aborted with --abort/-a.
@@ -62,9 +62,9 @@
 
 move changeset (and descendants) to a different branch
 
-    Rebase uses repeated merging to graft changesets from one part of
-    history onto another. This can be useful for linearizing local
-    changes relative to a master development tree.
+    Rebase uses repeated merging to graft changesets from one part of history
+    onto another. This can be useful for linearizing local changes relative to
+    a master development tree.
 
     If a rebase is interrupted to manually resolve a merge, it can be
     continued with --continue/-c or aborted with --abort/-a.
@@ -90,9 +90,9 @@
 
 move changeset (and descendants) to a different branch
 
-    Rebase uses repeated merging to graft changesets from one part of
-    history onto another. This can be useful for linearizing local
-    changes relative to a master development tree.
+    Rebase uses repeated merging to graft changesets from one part of history
+    onto another. This can be useful for linearizing local changes relative to
+    a master development tree.
 
     If a rebase is interrupted to manually resolve a merge, it can be
     continued with --continue/-c or aborted with --abort/-a.
--- a/tests/test-record.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-record.out	Thu Aug 06 18:48:00 2009 -0700
@@ -3,15 +3,14 @@
 
 interactively select changes to commit
 
-    If a list of files is omitted, all changes reported by "hg status"
-    will be candidates for recording.
+    If a list of files is omitted, all changes reported by "hg status" will be
+    candidates for recording.
 
     See 'hg help dates' for a list of formats valid for -d/--date.
 
-    You will be prompted for whether to record changes to each
-    modified file, and for files with multiple changes, for each
-    change to use. For each query, the following responses are
-    possible:
+    You will be prompted for whether to record changes to each modified file,
+    and for files with multiple changes, for each change to use. For each
+    query, the following responses are possible:
 
     y - record this change
     n - skip this change
--- a/tests/test-revlog-ancestry.py	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-revlog-ancestry.py	Thu Aug 06 18:48:00 2009 -0700
@@ -10,7 +10,7 @@
     repo.commit(text=text, date="%d 0" % time)
 
 def addcommit(name, time):
-    f = file(name, 'w')
+    f = open(name, 'w')
     f.write('%s\n' % name)
     f.close()
     repo.add([name])
--- a/tests/test-tags	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-tags	Thu Aug 06 18:48:00 2009 -0700
@@ -1,24 +1,46 @@
 #!/bin/sh
 
+cacheexists() {
+    [ -f .hg/tags.cache ] && echo "tag cache exists" || echo "no tag cache"
+}
+
+# XXX need to test that the tag cache works when we strip an old head
+# and add a new one rooted off non-tip: i.e. node and rev of tip are the
+# same, but stuff has changed behind tip.
+
+echo "% setup"
 mkdir t
 cd t
 hg init
+cacheexists
 hg id
+cacheexists
 echo a > a
 hg add a
-hg commit -m "test" -d "1000000 0"
+hg commit -m "test"
 hg co
 hg identify
-T=`hg tip --debug | head -n 1 | cut -d : -f 3`
+cacheexists
+
+echo "% create local tag with long name"
+T=`hg identify --debug --id`
 hg tag -l "This is a local tag with a really long name!"
 hg tags
 rm .hg/localtags
+
+echo "% create a tag behind hg's back"
 echo "$T first" > .hgtags
 cat .hgtags
 hg add .hgtags
-hg commit -m "add tags" -d "1000000 0"
+hg commit -m "add tags"
 hg tags
 hg identify
+
+# repeat with cold tag cache
+rm -f .hg/tags.cache
+hg identify
+
+echo "% create a branch"
 echo bb > a
 hg status
 hg identify
@@ -28,89 +50,126 @@
 hg status
 echo 1 > b
 hg add b
-hg commit -m "branch" -d "1000000 0"
+hg commit -m "branch"
 hg id
+
+echo "% merge the two heads"
 hg merge 1
 hg id
 hg status
 
-hg commit -m "merge" -d "1000000 0"
+hg commit -m "merge"
 
-# create fake head, make sure tag not visible afterwards
+echo "% create fake head, make sure tag not visible afterwards"
 cp .hgtags tags
-hg tag -d "1000000 0" last
+hg tag last
 hg rm .hgtags
-hg commit -m "remove" -d "1000000 0"
+hg commit -m "remove"
 
 mv tags .hgtags
 hg add .hgtags
-hg commit -m "readd" -d "1000000 0"
+hg commit -m "readd"
 
 hg tags
 
-# invalid tags
+echo "% add invalid tags"
 echo "spam" >> .hgtags
 echo >> .hgtags
 echo "foo bar" >> .hgtags
 echo "$T invalid" | sed "s/..../a5a5/" >> .hg/localtags
-hg commit -m "tags" -d "1000000 0"
+echo "committing .hgtags:"
+cat .hgtags 
+hg commit -m "tags"
 
-# report tag parse error on other head
+echo "% report tag parse error on other head"
 hg up 3
 echo 'x y' >> .hgtags
-hg commit -m "head" -d "1000000 0"
+hg commit -m "head"
 
 hg tags
 hg tip
 
-# test tag precedence rules
+echo "% test tag precedence rules"
 cd ..
 hg init t2
 cd t2
 echo foo > foo
 hg add foo
-hg ci -m 'add foo' -d '1000000 0'      # rev 0
-hg tag -d '1000000 0' bar              # rev 1
+hg ci -m 'add foo'      # rev 0
+hg tag bar              # rev 1
 echo >> foo
-hg ci -m 'change foo 1' -d '1000000 0' # rev 2
+hg ci -m 'change foo 1' # rev 2
 hg up -C 1
-hg tag -r 1 -d '1000000 0' -f bar      # rev 3
+hg tag -r 1 -f bar      # rev 3
 hg up -C 1
 echo >> foo
-hg ci -m 'change foo 2' -d '1000000 0' # rev 4
+hg ci -m 'change foo 2' # rev 4
+hg tags
+hg tags         # repeat in case of cache effects
+
+dumptags() {
+    rev=$1
+    echo "rev $rev: .hgtags:"
+    hg cat -r$rev .hgtags
+}
+
+echo "% detailed dump of tag info"
+echo "heads:"
+hg heads -q             # expect 4, 3, 2
+dumptags 2
+dumptags 3
+dumptags 4
+echo ".hg/tags.cache:"
+[ -f .hg/tags.cache ] && cat .hg/tags.cache || echo "no such file"
+
+echo "% test tag removal"
+hg tag --remove bar     # rev 5
+hg tip -vp
+hg tags
+hg tags                 # again, try to expose cache bugs
+
+echo '% remove nonexistent tag'
+hg tag --remove foobar
+hg tip
+
+echo "% rollback undoes tag operation"
+hg rollback             # destroy rev 5 (restore bar)
+hg tags
 hg tags
 
-# test tag removal
-hg tag --remove -d '1000000 0' bar
-hg tip
-hg tags
-
-echo '% remove nonexistent tag'
-hg tag --remove -d '1000000 0' foobar
-hg tip
-
-# test tag rank
+echo "% test tag rank"
 cd ..
 hg init t3
 cd t3
 echo foo > foo
 hg add foo
-hg ci -m 'add foo' -d '1000000 0'       # rev 0
-hg tag -d '1000000 0' -f bar            # rev 1 bar -> 0
-hg tag -d '1000000 0' -f bar            # rev 2 bar -> 1
-hg tag -d '1000000 0' -fr 0 bar         # rev 3 bar -> 0
-hg tag -d '1000000 0' -fr 1 bar         # rev 3 bar -> 1
-hg tag -d '1000000 0' -fr 0 bar         # rev 4 bar -> 0
+hg ci -m 'add foo'       # rev 0
+hg tag -f bar            # rev 1 bar -> 0
+hg tag -f bar            # rev 2 bar -> 1
+hg tag -fr 0 bar         # rev 3 bar -> 0
+hg tag -fr 1 bar         # rev 4 bar -> 1
+hg tag -fr 0 bar         # rev 5 bar -> 0
 hg tags
 hg co 3
 echo barbar > foo
-hg ci -m 'change foo' -d '1000000 0'    # rev 0
+hg ci -m 'change foo'    # rev 6
+hg tags
+
+echo "% don't allow moving tag without -f"
+hg tag -r 3 bar
 hg tags
 
-hg tag -d '1000000 0' -r 3 bar         # should complain
-hg tags
+echo "% strip 1: expose an old head"
+hg --config extensions.mq= strip 5 > /dev/null 2>&1
+hg tags                  # partly stale cache
+hg tags                  # up-to-date cache
+echo "% strip 2: destroy whole branch, no old head exposed"
+hg --config extensions.mq= strip 4 > /dev/null 2>&1 
+hg tags                  # partly stale
+rm -f .hg/tags.cache
+hg tags                  # cold cache
 
-# test tag rank with 3 heads
+echo "% test tag rank with 3 heads"
 cd ..
 hg init t4
 cd t4
@@ -124,10 +183,11 @@
 hg tags
 hg up -qC 0
 hg tag -m 'retag rev 0' -fr 0 bar  # rev 4 bar -> 0, but bar stays at 2
-echo % bar should still point to rev 2
+echo "% bar should still point to rev 2"
 hg tags
 
 
+echo "% remove local as global and global as local"
 # test that removing global/local tags does not get confused when trying
 # to remove a tag of type X which actually only exists as a type Y
 cd ..
--- a/tests/test-tags.out	Wed Aug 05 17:19:37 2009 +0200
+++ b/tests/test-tags.out	Thu Aug 06 18:48:00 2009 -0700
@@ -1,78 +1,147 @@
+% setup
+no tag cache
 000000000000 tip
+no tag cache
 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
-0acdaf898367 tip
-tip                                0:0acdaf898367
-This is a local tag with a really long name!     0:0acdaf898367
-0acdaf8983679e0aac16e811534eb49d7ee1f2b4 first
-tip                                1:8a3ca90d111d
-first                              0:0acdaf898367
-8a3ca90d111d tip
+acb14030fe0a tip
+tag cache exists
+% create local tag with long name
+tip                                0:acb14030fe0a
+This is a local tag with a really long name!     0:acb14030fe0a
+% create a tag behind hg's back
+acb14030fe0a21b60322c440ad2d20cf7685a376 first
+tip                                1:b9154636be93
+first                              0:acb14030fe0a
+b9154636be93 tip
+b9154636be93 tip
+% create a branch
 M a
-8a3ca90d111d+ tip
+b9154636be93+ tip
 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-0acdaf898367+ first
-0acdaf898367+ first
+acb14030fe0a+ first
+acb14030fe0a+ first
 M a
 created new head
-8216907a933d tip
+c8edf04160c7 tip
+% merge the two heads
 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 (branch merge, don't forget to commit)
-8216907a933d+8a3ca90d111d+ tip
+c8edf04160c7+b9154636be93+ tip
 M .hgtags
-tip                                6:e2174d339386
-first                              0:0acdaf898367
+% create fake head, make sure tag not visible afterwards
+tip                                6:35ff301afafe
+first                              0:acb14030fe0a
+% add invalid tags
+committing .hgtags:
+acb14030fe0a21b60322c440ad2d20cf7685a376 first
+spam
+
+foo bar
+% report tag parse error on other head
 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 created new head
-.hgtags@c071f74ab5eb, line 2: cannot parse entry
-.hgtags@c071f74ab5eb, line 4: node 'foo' is not well formed
-.hgtags@4ca6f1b1a68c, line 2: node 'x' is not well formed
-tip                                8:4ca6f1b1a68c
-first                              0:0acdaf898367
-changeset:   8:4ca6f1b1a68c
-.hgtags@c071f74ab5eb, line 2: cannot parse entry
-.hgtags@c071f74ab5eb, line 4: node 'foo' is not well formed
-.hgtags@4ca6f1b1a68c, line 2: node 'x' is not well formed
+.hgtags@75d9f02dfe28, line 2: cannot parse entry
+.hgtags@75d9f02dfe28, line 4: node 'foo' is not well formed
+.hgtags@c4be69a18c11, line 2: node 'x' is not well formed
+tip                                8:c4be69a18c11
+first                              0:acb14030fe0a
+changeset:   8:c4be69a18c11
 tag:         tip
-parent:      3:b2ef3841386b
+parent:      3:ac5e980c4dc0
 user:        test
-date:        Mon Jan 12 13:46:40 1970 +0000
+date:        Thu Jan 01 00:00:00 1970 +0000
 summary:     head
 
+% test tag precedence rules
 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 created new head
-tip                                4:36195b728445
-bar                                1:b204a97e6e8d
-changeset:   5:1f98c77278de
+tip                                4:0c192d7d5e6b
+bar                                1:78391a272241
+tip                                4:0c192d7d5e6b
+bar                                1:78391a272241
+% detailed dump of tag info
+heads:
+4:0c192d7d5e6b
+3:6fa450212aeb
+2:7a94127795a3
+rev 2: .hgtags:
+bbd179dfa0a71671c253b3ae0aa1513b60d199fa bar
+rev 3: .hgtags:
+bbd179dfa0a71671c253b3ae0aa1513b60d199fa bar
+bbd179dfa0a71671c253b3ae0aa1513b60d199fa bar
+78391a272241d70354aa14c874552cad6b51bb42 bar
+rev 4: .hgtags:
+bbd179dfa0a71671c253b3ae0aa1513b60d199fa bar
+.hg/tags.cache:
+4 0c192d7d5e6b78a714de54a2e9627952a877e25a 0c04f2a8af31de17fab7422878ee5a2dadbc943d
+3 6fa450212aeb2a21ed616a54aea39a4a27894cd7 7d3b718c964ef37b89e550ebdafd5789e76ce1b0
+2 7a94127795a33c10a370c93f731fd9fea0b79af6 0c04f2a8af31de17fab7422878ee5a2dadbc943d
+
+78391a272241d70354aa14c874552cad6b51bb42 bar
+% test tag removal
+changeset:   5:5f6e8655b1c7
 tag:         tip
 user:        test
-date:        Mon Jan 12 13:46:40 1970 +0000
-summary:     Removed tag bar
+date:        Thu Jan 01 00:00:00 1970 +0000
+files:       .hgtags
+description:
+Removed tag bar
+
 
-tip                                5:1f98c77278de
+diff -r 0c192d7d5e6b -r 5f6e8655b1c7 .hgtags
+--- a/.hgtags	Thu Jan 01 00:00:00 1970 +0000
++++ b/.hgtags	Thu Jan 01 00:00:00 1970 +0000
+@@ -1,1 +1,3 @@
+ bbd179dfa0a71671c253b3ae0aa1513b60d199fa bar
++78391a272241d70354aa14c874552cad6b51bb42 bar
++0000000000000000000000000000000000000000 bar
+
+tip                                5:5f6e8655b1c7
+tip                                5:5f6e8655b1c7
 % remove nonexistent tag
 abort: tag 'foobar' does not exist
-changeset:   5:1f98c77278de
+changeset:   5:5f6e8655b1c7
 tag:         tip
 user:        test
-date:        Mon Jan 12 13:46:40 1970 +0000
+date:        Thu Jan 01 00:00:00 1970 +0000
 summary:     Removed tag bar
 
-tip                                5:e86d7ed95fd3
-bar                                0:b409d9da318e
+% rollback undoes tag operation
+rolling back last transaction
+tip                                4:0c192d7d5e6b
+bar                                1:78391a272241
+tip                                4:0c192d7d5e6b
+bar                                1:78391a272241
+% test tag rank
+tip                                5:85f05169d91d
+bar                                0:bbd179dfa0a7
 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 created new head
-tip                                6:b744fbe1f6dd
-bar                                0:b409d9da318e
+tip                                6:735c3ca72986
+bar                                0:bbd179dfa0a7
+% don't allow moving tag without -f
 abort: tag 'bar' already exists (use -f to force)
-tip                                6:b744fbe1f6dd
-bar                                0:b409d9da318e
+tip                                6:735c3ca72986
+bar                                0:bbd179dfa0a7
+% strip 1: expose an old head
+tip                                5:735c3ca72986
+bar                                1:78391a272241
+tip                                5:735c3ca72986
+bar                                1:78391a272241
+% strip 2: destroy whole branch, no old head exposed
+tip                                4:735c3ca72986
+bar                                0:bbd179dfa0a7
+tip                                4:735c3ca72986
+bar                                0:bbd179dfa0a7
+% test tag rank with 3 heads
 adding foo
 tip                                3:197c21bbbf2c
 bar                                2:6fa450212aeb
 % bar should still point to rev 2
 tip                                4:3b4b14ed0202
 bar                                2:6fa450212aeb
+% remove local as global and global as local
 adding foo
 abort: tag 'localtag' is not a global tag
 abort: tag 'globaltag' is not a local tag