emacs-diffs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Emacs-diffs] xwidget baba9e03: merge upstream


From: Joakim Verona
Subject: [Emacs-diffs] xwidget baba9e03: merge upstream
Date: Wed, 31 Dec 2014 11:28:35 +0000

branch: xwidget
commit baba9e039136e183e055169ddd7ca1e983fc734f
Merge: 4105b6a 2534676
Author: jave <address@hidden>
Commit: jave <address@hidden>

    merge upstream
---
 .gitignore                          |    1 +
 CONTRIBUTE                          |    4 +-
 ChangeLog                           |   51 ++-
 build-aux/git-hooks/commit-msg      |   20 +-
 doc/emacs/ChangeLog                 |    4 +
 doc/emacs/buffers.texi              |   11 +-
 doc/emacs/building.texi             |    2 +-
 doc/lispref/ChangeLog               |  121 +++++
 doc/lispref/abbrevs.texi            |    9 +
 doc/lispref/backups.texi            |    4 +
 doc/lispref/buffers.texi            |    2 +
 doc/lispref/commands.texi           |    9 +
 doc/lispref/compile.texi            |    1 +
 doc/lispref/control.texi            |    9 +-
 doc/lispref/customize.texi          |    4 +
 doc/lispref/debugging.texi          |    6 +
 doc/lispref/display.texi            |   91 +++-
 doc/lispref/files.texi              |    6 +
 doc/lispref/frames.texi             |    8 +
 doc/lispref/functions.texi          |    5 +-
 doc/lispref/hash.texi               |    2 +
 doc/lispref/help.texi               |    2 +
 doc/lispref/keymaps.texi            |    4 +
 doc/lispref/lists.texi              |    9 +
 doc/lispref/loading.texi            |    4 +
 doc/lispref/macros.texi             |    3 +
 doc/lispref/markers.texi            |    7 +
 doc/lispref/minibuf.texi            |    5 +
 doc/lispref/modes.texi              |    4 +-
 doc/lispref/nonascii.texi           |    5 +
 doc/lispref/os.texi                 |   18 +-
 doc/lispref/positions.texi          |    1 +
 doc/lispref/processes.texi          |    3 +
 doc/lispref/searching.texi          |    5 +
 doc/lispref/strings.texi            |    7 +
 doc/lispref/syntax.texi             |    7 +
 doc/lispref/text.texi               |    9 +
 doc/lispref/variables.texi          |    3 +
 doc/lispref/windows.texi            |    2 +
 doc/misc/efaq.texi                  |    2 +-
 doc/misc/smtpmail.texi              |    2 +-
 etc/ChangeLog                       |    8 +
 etc/NEWS                            |   15 +-
 etc/PROBLEMS                        |   15 +-
 etc/grep.txt                        |    6 +-
 etc/tutorials/TUTORIAL.es           |  230 +++++-----
 lib-src/ChangeLog                   |    8 +
 lib-src/Makefile.in                 |   12 +-
 lisp/ChangeLog                      |  332 ++++++++++++-
 lisp/Makefile.in                    |    7 +-
 lisp/comint.el                      |   16 +-
 lisp/desktop.el                     |    2 +-
 lisp/dired.el                       |    2 +-
 lisp/dnd.el                         |   21 +-
 lisp/emacs-lisp/find-func.el        |   65 ++-
 lisp/gnus/ChangeLog                 |    5 +
 lisp/gnus/gnus-cloud.el             |    9 +
 lisp/gnus/message.el                |   10 +-
 lisp/gnus/mm-decode.el              |    1 +
 lisp/gnus/nnvirtual.el              |    8 +-
 lisp/international/mule.el          |  167 +++++--
 lisp/language/misc-lang.el          |    3 +-
 lisp/menu-bar.el                    |   51 +--
 lisp/minibuffer.el                  |    5 +-
 lisp/net/eww.el                     |   18 +-
 lisp/net/shr.el                     |  104 +++--
 lisp/net/tramp-gw.el                |    9 +-
 lisp/net/tramp-sh.el                |   53 ++-
 lisp/net/tramp.el                   |  277 ++++++-----
 lisp/nxml/rng-uri.el                |    2 +-
 lisp/obsolete/pc-select.el          |   12 +-
 lisp/org/org-clock.el               |    4 +-
 lisp/org/org-ctags.el               |    8 +-
 lisp/org/ox-html.el                 |    2 +-
 lisp/org/ox-latex.el                |    2 +-
 lisp/org/ox-publish.el              |    2 +-
 lisp/org/ox.el                      |    6 +-
 lisp/progmodes/elisp-mode.el        |   95 ++--
 lisp/progmodes/etags.el             |    5 +
 lisp/progmodes/js.el                |    2 +-
 lisp/progmodes/python.el            |  591 ++++++++++++++++------
 lisp/progmodes/sh-script.el         |    2 +-
 lisp/progmodes/xref.el              |   28 +-
 lisp/saveplace.el                   |   44 +-
 lisp/simple.el                      |   10 +-
 lisp/startup.el                     |    2 +
 lisp/subr.el                        |    4 +-
 lisp/textmodes/tex-mode.el          |   50 ++-
 lisp/vc/compare-w.el                |   25 +-
 lisp/vc/vc-dir.el                   |   11 +
 lisp/vc/vc-git.el                   |    7 +-
 lisp/window.el                      |    7 +-
 src/ChangeLog                       |  120 +++++
 src/Makefile.in                     |   43 +-
 src/buffer.c                        |    4 +-
 src/composite.c                     |    3 +-
 src/decompress.c                    |   51 +--
 src/dispextern.h                    |    5 +-
 src/editfns.c                       |   16 +-
 src/filelock.c                      |    7 +-
 src/frame.c                         |    2 +-
 src/gnutls.c                        |  775 +++++++++++++++--------------
 src/image.c                         |  932 ++++++++++++++++++-----------------
 src/nsimage.m                       |    8 +-
 src/sysdep.c                        |  132 +-----
 src/term.c                          |    2 +-
 src/w32.h                           |   13 +
 src/xdisp.c                         |  171 +++----
 src/xml.c                           |   94 ++--
 src/xrdb.c                          |    5 +-
 src/xselect.c                       |   95 ++--
 src/xsettings.c                     |   94 ++--
 src/xterm.c                         |   22 +-
 src/xterm.h                         |    8 +-
 test/ChangeLog                      |   69 +++
 test/automated/data/flymake/test.pl |    2 +-
 test/automated/electric-tests.el    |   11 +-
 test/automated/let-alist.el         |    1 +
 test/automated/python-tests.el      |  509 ++++++++++++++-----
 test/automated/tramp-tests.el       |    7 +-
 120 files changed, 3866 insertions(+), 2187 deletions(-)

diff --git a/.gitignore b/.gitignore
index d05352e..97adfb95 100644
--- a/.gitignore
+++ b/.gitignore
@@ -48,6 +48,7 @@ makefile
 /confdefs.h
 /config.status
 /configure.lineno
+/conftest*
 src/config.h
 src/epaths.h
 
diff --git a/CONTRIBUTE b/CONTRIBUTE
index 3bc49cf..0e019d3 100644
--- a/CONTRIBUTE
+++ b/CONTRIBUTE
@@ -57,7 +57,7 @@ following modifications:
   the rationale for a change; that can be done in the commit message
   between the summary line and the file entries.
 
-** Changelog notes
+** ChangeLog notes
 
 - Emacs generally follows the GNU coding standards when it comes to
   ChangeLogs:
@@ -67,7 +67,7 @@ following modifications:
   now), because `...' is so widely used elsewhere in Emacs.
 
 - Some of the rules in the GNU coding standards section 5.2
-  "Commenting Your Work" also apply to Changelog entries: they must be
+  "Commenting Your Work" also apply to ChangeLog entries: they must be
   in English, and be complete sentences starting with a capital and
   ending with a period (except the summary line should not end in a
   period).
diff --git a/ChangeLog b/ChangeLog
index 90d7c0b..6557ef9 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,51 @@
+2014-12-29  Paul Eggert  <address@hidden>
+
+       system-name's returned value can vary
+       Also, the system-name variable is now obsolete.
+       Fixes Bug#19438.
+       * doc/lispref/os.texi (System Environment):
+       * etc/NEWS: Document this.
+       * doc/misc/efaq.texi:
+       (Displaying the current file name in the titlebar):
+       * lisp/desktop.el (desktop-save-frameset):
+       * lisp/dnd.el (dnd-get-local-file-uri):
+       * lisp/gnus/message.el (message-make-fqdn):
+       * lisp/gnus/nnvirtual.el (nnvirtual-retrieve-headers)
+       (nnvirtual-update-xref-header):
+       * lisp/nxml/rng-uri.el (rng-uri-file-name-1):
+       * lisp/org/org-clock.el (org-clock-save):
+       * src/filelock.c (current_lock_owner):
+       * src/xrdb.c (get_environ_db):
+       * src/xterm.c (same_x_server):
+       * src/xterm.c (x_term_init):
+       Prefer (system-name) to system-name, and avoid naming
+       locals 'system-name'.
+       * doc/misc/smtpmail.texi (Server workarounds): Fix grammar.
+       * lisp/startup.el (system-name): Now an obsolete variable.
+       * src/editfns.c (cached_system_name): New static var.
+       (init_and_cache_system_name): New function.
+       (init_editfns, Fsystem_name): Use it.
+       (syms_of_editfns): Initialize it and Vsystem_name to the same value.
+       * src/sysdep.c [HAVE_SOCKETS]: Don't include <sys/socket.h>, <netdb.h>.
+       (h_errno) [TRY_AGAIN && !HAVE_H_ERRNO]: Remove decl.
+       (init_system_name) [HAVE_SOCKETS]: Don't canonicalize the name.
+       Don't create a new string if the current value is already correct.
+
+2014-12-28  Paul Eggert  <address@hidden>
+
+       * build-aux/git-hooks/commit-msg: Allow tabs.
+       Treat them as if they were expanded to spaces, with tab stops
+       every 8 columns.
+
+2014-12-27  Paul Eggert  <address@hidden>
+
+       * .gitignore: Ignore /conftest*.
+
+2014-12-27  Stefan Monnier  <address@hidden>
+
+       * build-aux/git-hooks/commit-msg (at_sign): Bump up line-length limit
+       to 78.
+
 2014-12-25  Paul Eggert  <address@hidden>
 
        Prefer stpcpy to strcat
@@ -308,7 +356,8 @@
 
 2014-11-11  Eric S. Raymond  <address@hidden>
 
-       * Makefile.in: git transition - set VCWITNESS appropriately for git.
+       Git transition.
+       * Makefile.in (src): Set VCSWITNESS appropriately for git.
 
        All bzr revision IDS, and all CVS revision IDs for which a commit
        could be identified, were changed to time-date!committer version
diff --git a/build-aux/git-hooks/commit-msg b/build-aux/git-hooks/commit-msg
index 5eb994c..9b6179e 100755
--- a/build-aux/git-hooks/commit-msg
+++ b/build-aux/git-hooks/commit-msg
@@ -87,8 +87,17 @@ exec $awk '
     status = 1
   }
 
-  72 < length && $0 ~ space {
-    print "Line longer than 72 characters in commit message"
+  {
+    # Expand tabs to spaces for length calculations etc.
+    while (match($0, /\t/)) {
+      before_tab = substr($0, 1, RSTART - 1)
+      after_tab = substr($0, RSTART + 1)
+      $0 = sprintf("%s%*s%s", before_tab, 8 - (RSTART - 1) % 8, "", after_tab)
+    }
+  }
+
+  78 < length && $0 ~ space {
+    print "Line longer than 78 characters in commit message"
     status = 1
   }
 
@@ -103,12 +112,7 @@ exec $awk '
   }
 
   $0 ~ non_print {
-    if (gsub(/\t/, "")) {
-      print "Tab in commit message; please use spaces instead"
-    }
-    if ($0 ~ non_print) {
-      print "Unprintable character in commit message"
-    }
+    print "Unprintable character in commit message"
     status = 1
   }
 
diff --git a/doc/emacs/ChangeLog b/doc/emacs/ChangeLog
index 7081c19..0016ee0 100644
--- a/doc/emacs/ChangeLog
+++ b/doc/emacs/ChangeLog
@@ -1,3 +1,7 @@
+2014-12-27  Eli Zaretskii  <address@hidden>
+
+       * buffers.texi (Kill Buffer): Improve indexing.
+
 2014-12-24  Stephen Leake  <address@hidden>
 
        * trouble.texi: Move user-level information from CONTRIBUTE here.
diff --git a/doc/emacs/buffers.texi b/doc/emacs/buffers.texi
index 54a8498..f036d85 100644
--- a/doc/emacs/buffers.texi
+++ b/doc/emacs/buffers.texi
@@ -269,11 +269,16 @@ can also be used to copy text from one buffer to another.
 @section Killing Buffers
 
 @cindex killing buffers
address@hidden close buffer
address@hidden close file
   If you continue an Emacs session for a while, you may accumulate a
 large number of buffers.  You may then find it convenient to @dfn{kill}
-the buffers you no longer need.  On most operating systems, killing a
-buffer releases its space back to the operating system so that other
-programs can use it.  Here are some commands for killing buffers:
+the buffers you no longer need.  (Some other editors call this
+operation @dfn{close}, and talk about ``closing the buffer'' or
+``closing the file'' visited in the buffer.)  On most operating
+systems, killing a buffer releases its space back to the operating
+system so that other programs can use it.  Here are some commands for
+killing buffers:
 
 @table @kbd
 @item C-x k @var{bufname} @key{RET}
diff --git a/doc/emacs/building.texi b/doc/emacs/building.texi
index e0ed11f..e1993e5 100644
--- a/doc/emacs/building.texi
+++ b/doc/emacs/building.texi
@@ -1358,7 +1358,7 @@ searches through each directory in the Emacs Lisp load 
path, trying to
 find a file matching that library name.  If the library name is
 @address@hidden, it tries looking for files named
 @address@hidden, @address@hidden, and @address@hidden  The
-default behaviour is to load the first file found.  This command
+default behavior is to load the first file found.  This command
 prefers @file{.elc} files over @file{.el} files because compiled files
 load and run faster.  If it finds that @address@hidden is newer
 than @address@hidden, it issues a warning, in case someone made
diff --git a/doc/lispref/ChangeLog b/doc/lispref/ChangeLog
index 2d964cf..c9f576a 100644
--- a/doc/lispref/ChangeLog
+++ b/doc/lispref/ChangeLog
@@ -1,3 +1,118 @@
+2014-12-30  Martin Rudalics  <address@hidden>
+
+       * display.texi (Temporary Displays): Amend description of
+       `with-temp-buffer-window'.  Add descriptions for
+       `with-current-buffer-window', `with-displayed-buffer-window' and
+       `temp-buffer-resize-mode', `temp-buffer-max-height' and
+       `temp-buffer-max-width'.
+
+2014-12-27  Glenn Morris  <address@hidden>
+
+       * control.texi (Pattern matching case statement):
+       * os.texi (Desktop Notifications):
+       * modes.texi (Defining Minor Modes, SMIE Lexer): Markup fixes.
+
+2014-12-27  Eli Zaretskii  <address@hidden>
+
+       * windows.texi (Recombining Windows): Index subject of sections.
+
+       * variables.texi (Variables with Restricted Values)
+       (Generalized Variables): Index subject of sections.
+
+       * text.texi (Buffer Contents, Examining Properties)
+       (Changing Properties, Property Search, Substitution): Index
+       subject of sections.
+
+       * syntax.texi (Motion and Syntax, Parsing Expressions)
+       (Motion via Parsing, Position Parse, Control Parsing): Index
+       subject of sections.
+
+       * strings.texi (Predicates for Strings, Creating Strings)
+       (Modifying Strings, Text Comparison): Index subject of sections.
+
+       * searching.texi (Syntax of Regexps, Regexp Special)
+       (Regexp Functions, Regexp Functions): Index subject of sections.
+
+       * processes.texi (Subprocess Creation, Process Information): Index
+       subject of sections.
+
+       * positions.texi (Screen Lines): Index subject of sections.
+
+       * nonascii.texi (Scanning Charsets, Specifying Coding Systems):
+       Index subject of sections.
+
+       * minibuf.texi (Text from Minibuffer, Object from Minibuffer)
+       (Multiple Queries, Minibuffer Contents): Index subject of
+       sections.
+
+       * markers.texi (Predicates on Markers, Creating Markers)
+       (Information from Markers, Moving Markers): Index subject of
+       sections.
+
+       * macros.texi (Defining Macros, Problems with Macros): Index
+       subject of sections.
+
+       * loading.texi (Loading Non-ASCII, Where Defined): Index subject
+       of sections.
+
+       * lists.texi (List-related Predicates, List Variables, Setcar)
+       (Setcdr, Plist Access): Index subject of sections.
+
+       * keymaps.texi (Controlling Active Maps, Scanning Keymaps)
+       (Modifying Menus): Index subject of sections.
+
+       * help.texi (Accessing Documentation, Help Functions): Index
+       subject of sections.
+
+       * hash.texi (Hash Access): Index subject of sections.
+
+       * functions.texi (Core Advising Primitives)
+       (Advising Named Functions, Porting old advices): Index subject of
+       sections.
+
+       * frames.texi (Creating Frames, Initial Parameters)
+       (Position Parameters, Buffer Parameters, Minibuffers and Frames)
+       (Pop-Up Menus, Drag and Drop): Index subject of sections.
+
+       * files.texi (Visiting Functions, Kinds of Files)
+       (Unique File Names): Index subject of sections.
+
+       * display.texi (Refresh Screen, Echo Area Customization)
+       (Warning Variables, Warning Options, Delayed Warnings)
+       (Temporary Displays, Managing Overlays, Overlay Properties)
+       (Finding Overlays, Size of Displayed Text, Defining Faces)
+       (Attribute Functions, Displaying Faces, Face Remapping)
+       (Basic Faces, Font Lookup, Fontsets, Replacing Specs)
+       (Defining Images, Showing Images): Index subject of sections.
+
+       * debugging.texi (Debugging, Explicit Debug)
+       (Invoking the Debugger, Excess Open, Excess Close): Index subject
+       of sections.
+
+       * customize.texi (Defining New Types, Applying Customizations)
+       (Custom Themes): Index subject of sections.
+
+       * control.texi (Sequencing, Combining Conditions)
+       (Processing of Errors, Cleanups): Index subject of sections.
+
+       * compile.texi (Eval During Compile): Index subject of sections.
+
+       * commands.texi (Using Interactive, Distinguish Interactive)
+       (Command Loop Info, Classifying Events, Event Mod)
+       (Invoking the Input Method): Index subject of sections.
+
+       * buffers.texi (Buffer List, Buffer Gap): Index subject of sections.
+
+       * backups.texi (Making Backups, Numbered Backups, Backup Names)
+       (Reverting): Index subject of sections.
+
+       * abbrevs.texi (Abbrev Tables, Defining Abbrevs, Abbrev Files)
+       (Abbrev Expansion, Standard Abbrev Tables, Abbrev Properties)
+       (Abbrev Table Properties): Index subject of sections.
+
+       * os.texi (Time of Day, Time Conversion, Time Parsing)
+       (Time Calculations, Idle Timers): Index subject of sections.
+
 2014-12-25  Martin Rudalics  <address@hidden>
 
        * windows.texi (Windows): Resync @menu order with @node order.
@@ -37,6 +152,12 @@
 
        * display.texi (Low-Level Font): Document font-info and query-font.
 
+2014-12-18  Stefan Monnier  <address@hidden>
+
+        * display.texi (Forcing Redisplay): Remove references to
+        redisplay-dont-pause and redisplay-preemption-period (which doesn't
+        even exist).
+
 2014-12-16  Nicolas Petton  <address@hidden>
 
        * sequences.texi (Seq Library): Add documentation for seq.el.
diff --git a/doc/lispref/abbrevs.texi b/doc/lispref/abbrevs.texi
index 73a3f5f..c00af61 100644
--- a/doc/lispref/abbrevs.texi
+++ b/doc/lispref/abbrevs.texi
@@ -59,6 +59,7 @@ expanded in the buffer.  For the user-level commands for 
abbrevs, see
 
 @node Abbrev Tables
 @section Abbrev Tables
address@hidden abbrev tables
 
   This section describes how to create and manipulate abbrev tables.
 
@@ -126,6 +127,7 @@ to add these to @var{name} separately.)
 
 @node Defining Abbrevs
 @section Defining Abbrevs
address@hidden defining abbrevs
 
   @code{define-abbrev} is the low-level basic function for defining an
 abbrev in an abbrev table.
@@ -181,6 +183,7 @@ callers.
 
 @node Abbrev Files
 @section Saving Abbrevs in Files
address@hidden save abbrevs in files
 
   A file of saved abbrev definitions is actually a file of Lisp code.
 The abbrevs are saved in the form of a Lisp program to define the same
@@ -232,6 +235,9 @@ define the same abbrevs.  If @var{filename} is @code{nil} 
or omitted,
 
 @node Abbrev Expansion
 @section Looking Up and Expanding Abbreviations
address@hidden looking up abbrevs
address@hidden expanding abbrevs
address@hidden abbrevs, looking up and expanding
 
   Abbrevs are usually expanded by certain interactive commands,
 including @code{self-insert-command}.  This section describes the
@@ -367,6 +373,7 @@ definitions of @code{local-abbrev-table} and 
@code{text-mode-abbrev-table}.
 
 @node Standard Abbrev Tables
 @section Standard Abbrev Tables
address@hidden standard abbrev tables
 
   Here we list the variables that hold the abbrev tables for the
 preloaded major modes of Emacs.
@@ -409,6 +416,7 @@ Properties}.
 
 @node Abbrev Properties
 @section Abbrev Properties
address@hidden abbrev properties
 
 Abbrevs have properties, some of which influence the way they work.
 You can provide them as arguments to @code{define-abbrev}, and
@@ -449,6 +457,7 @@ modifies the capitalization of the expansion.
 
 @node Abbrev Table Properties
 @section Abbrev Table Properties
address@hidden abbrev table properties
 
 Like abbrevs, abbrev tables have properties, some of which influence
 the way they work.  You can provide them as arguments to
diff --git a/doc/lispref/backups.texi b/doc/lispref/backups.texi
index 63f8f22..ca30f3e 100644
--- a/doc/lispref/backups.texi
+++ b/doc/lispref/backups.texi
@@ -50,6 +50,7 @@ don't want them any more, or Emacs can delete them 
automatically.
 
 @node Making Backups
 @subsection Making Backup Files
address@hidden making backup files
 
 @defun backup-buffer
   This function makes a backup of the file visited by the current
@@ -238,6 +239,7 @@ The default is 200.
 
 @node Numbered Backups
 @subsection Making and Deleting Numbered Backup Files
address@hidden numbered backups
 
   If a file's name is @file{foo}, the names of its numbered backup
 versions are @address@hidden, for various integers @var{v}, like
@@ -299,6 +301,7 @@ file.  The default address@hidden
 
 @node Backup Names
 @subsection Naming Backup Files
address@hidden naming backup files
 
   The functions in this section are documented mainly because you can
 customize the naming conventions for backup files by redefining them.
@@ -668,6 +671,7 @@ not initialize @code{auto-save-list-file-name}.
 
 @node Reverting
 @section Reverting
address@hidden reverting buffers
 
   If you have made extensive changes to a file and then change your mind
 about them, you can get rid of them by reading in the previous version
diff --git a/doc/lispref/buffers.texi b/doc/lispref/buffers.texi
index 5ac2d67..7c4fb87 100644
--- a/doc/lispref/buffers.texi
+++ b/doc/lispref/buffers.texi
@@ -762,6 +762,7 @@ signal an error if the current buffer is read-only.
 @node Buffer List
 @section The Buffer List
 @cindex buffer list
address@hidden listing all buffers
 
   The @dfn{buffer list} is a list of all live buffers.  The order of the
 buffers in this list is based primarily on how recently each buffer has
@@ -1215,6 +1216,7 @@ in the text it is swapped with will not interfere with 
auto-saving.
 
 @node Buffer Gap
 @section The Buffer Gap
address@hidden buffer gap
 
   Emacs buffers are implemented using an invisible @dfn{gap} to make
 insertion and deletion faster.  Insertion works by filling in part of
diff --git a/doc/lispref/commands.texi b/doc/lispref/commands.texi
index e5db4d8..c2b7038 100644
--- a/doc/lispref/commands.texi
+++ b/doc/lispref/commands.texi
@@ -147,6 +147,7 @@ code.
 @node Using Interactive
 @subsection Using @code{interactive}
 @cindex arguments, interactive entry
address@hidden interactive spec, using
 
   This section describes how to write the @code{interactive} form that
 makes a Lisp function an interactively-callable command, and how to
@@ -747,6 +748,8 @@ part of the prompt.
 
 @node Distinguish Interactive
 @section Distinguish Interactive Calls
address@hidden distinguish interactive calls
address@hidden is this call interactive
 
   Sometimes a command should display additional visual feedback (such
 as an informative message in the echo area) for interactive calls
@@ -835,6 +838,7 @@ Here is another example that contrasts direct and indirect 
calls to
 
 @node Command Loop Info
 @section Information from the Command Loop
address@hidden command loop variables
 
 The editor command loop sets several Lisp variables to keep status
 records for itself and for commands that are run.  With the exception of
@@ -1859,6 +1863,7 @@ bind it to the @code{signal usr1} event sequence:
 @node Classifying Events
 @subsection Classifying Events
 @cindex event type
address@hidden classifying events
 
   Every event has an @dfn{event type}, which classifies the event for
 key binding purposes.  For a keyboard event, the event type equals the
@@ -2584,6 +2589,9 @@ then continues to wait for a valid input character, or 
keyboard-quit.
 
 @node Event Mod
 @subsection Modifying and Translating Input Events
address@hidden modifiers of events
address@hidden translating input events
address@hidden event translation
 
   Emacs modifies every event it reads according to
 @code{extra-keyboard-modifiers}, then translates it through
@@ -2665,6 +2673,7 @@ at the level of @code{read-key-sequence}.
 
 @node Invoking the Input Method
 @subsection Invoking the Input Method
address@hidden invoking input method
 
   The event-reading functions invoke the current input method, if any
 (@pxref{Input Methods}).  If the value of @code{input-method-function}
diff --git a/doc/lispref/compile.texi b/doc/lispref/compile.texi
index fe492df..cb6cba9 100644
--- a/doc/lispref/compile.texi
+++ b/doc/lispref/compile.texi
@@ -347,6 +347,7 @@ it does nothing.  It always returns @var{function}.
 
 @node Eval During Compile
 @section Evaluation During Compilation
address@hidden eval during compilation
 
   These features permit you to write code to be evaluated during
 compilation of a program.
diff --git a/doc/lispref/control.texi b/doc/lispref/control.texi
index ea21233..1e9f346 100644
--- a/doc/lispref/control.texi
+++ b/doc/lispref/control.texi
@@ -44,6 +44,8 @@ structure constructs (@pxref{Macros}).
 
 @node Sequencing
 @section Sequencing
address@hidden sequencing
address@hidden sequential execution
 
   Evaluating forms in the order they appear is the most common way
 control passes from one form to another.  In some contexts, such as in a
@@ -368,8 +370,8 @@ that location.
 More specifically, a Q-pattern can take the following forms:
 @table @code
 @item (@var{qpattern1} . @var{qpattern2})
-This pattern matches any cons cell whose @code{car} matches @var{QPATTERN1} and
-whose @code{cdr} matches @var{PATTERN2}.
+This pattern matches any cons cell whose @code{car} matches @var{qpattern1} and
+whose @code{cdr} matches @var{pattern2}.
 @item address@hidden @var{qpattern2} @dots{} @var{qpatternm}]
 This pattern matches a vector of length @var{M} whose 0..(@var{M}-1)th
 elements match @var{qpattern1}, @var{qpattern2} @dots{} @var{qpatternm},
@@ -405,6 +407,7 @@ the variable @code{x}.
 
 @node Combining Conditions
 @section Constructs for Combining Conditions
address@hidden combining conditions
 
   This section describes three constructs that are often used together
 with @code{if} and @code{cond} to express complicated conditions.  The
@@ -962,6 +965,7 @@ concept of continuable errors.
 
 @node Processing of Errors
 @subsubsection How Emacs Processes Errors
address@hidden processing of errors
 
 When an error is signaled, @code{signal} searches for an active
 @dfn{handler} for the error.  A handler is a sequence of Lisp
@@ -1367,6 +1371,7 @@ and their conditions.
 
 @node Cleanups
 @subsection Cleaning Up from Nonlocal Exits
address@hidden nonlocal exits, cleaning up
 
   The @code{unwind-protect} construct is essential whenever you
 temporarily put a data structure in an inconsistent state; it permits
diff --git a/doc/lispref/customize.texi b/doc/lispref/customize.texi
index 0c6497f..cdf599b 100644
--- a/doc/lispref/customize.texi
+++ b/doc/lispref/customize.texi
@@ -1227,6 +1227,8 @@ arguments, which will be used when creating the 
@code{radio-button} or
 
 @node Defining New Types
 @subsection Defining New Types
address@hidden customization types, define new
address@hidden define new customization types
 
 In the previous sections we have described how to construct elaborate
 type specifications for @code{defcustom}.  In some cases you may want
@@ -1296,6 +1298,7 @@ its @code{:type} argument only when needed.
 
 @node Applying Customizations
 @section Applying Customizations
address@hidden applying customizations
 
 The following functions are responsible for installing the user's
 customization settings for variables and faces, respectively.  When
@@ -1353,6 +1356,7 @@ evaluated.  @var{comment} is a string describing the 
customization.
 @node Custom Themes
 @section Custom Themes
 
address@hidden custom themes
   @dfn{Custom themes} are collections of settings that can be enabled
 or disabled as a unit.  @xref{Custom Themes,,, emacs, The GNU Emacs
 Manual}.  Each Custom theme is defined by an Emacs Lisp source file,
diff --git a/doc/lispref/debugging.texi b/doc/lispref/debugging.texi
index 66f12a0..0b3c47f 100644
--- a/doc/lispref/debugging.texi
+++ b/doc/lispref/debugging.texi
@@ -5,6 +5,7 @@
 @c See the file elisp.texi for copying conditions.
 @node Debugging
 @chapter Debugging Lisp Programs
address@hidden debugging lisp programs
 
   There are several ways to find and investigate problems in an Emacs
 Lisp program.
@@ -284,6 +285,8 @@ not currently set up to break on entry.
 
 @node Explicit Debug
 @subsection Explicit Entry to the Debugger
address@hidden debugger, explicit entry
address@hidden force entry to debugger
 
   You can cause the debugger to be called at a certain point in your
 program by writing the expression @code{(debug)} at that point.  To do
@@ -456,6 +459,7 @@ Toggle the display of local variables of the current stack 
frame.
 
 @node Invoking the Debugger
 @subsection Invoking the Debugger
address@hidden invoking lisp debugger
 
   Here we describe in full detail the function @code{debug} that is used
 to invoke the debugger.
@@ -707,6 +711,7 @@ find the mismatch.)
 
 @node Excess Open
 @subsection Excess Open Parentheses
address@hidden excess open parentheses
 
   The first step is to find the defun that is unbalanced.  If there is
 an excess open parenthesis, the way to do this is to go to the end of
@@ -741,6 +746,7 @@ anything.
 
 @node Excess Close
 @subsection Excess Close Parentheses
address@hidden excess close parentheses
 
   To deal with an excess close parenthesis, first go to the beginning
 of the file, then type @kbd{C-u -1 C-M-u} to find the end of the first
diff --git a/doc/lispref/display.texi b/doc/lispref/display.texi
index 48860c8..14a98f3 100644
--- a/doc/lispref/display.texi
+++ b/doc/lispref/display.texi
@@ -39,6 +39,8 @@ that Emacs presents to the user.
 
 @node Refresh Screen
 @section Refreshing the Screen
address@hidden refresh the screen
address@hidden screen refresh
 
   The function @code{redraw-frame} clears and redisplays the entire
 contents of a given frame (@pxref{Frames}).  This is useful if the
@@ -534,6 +536,7 @@ are logged that share a common prefix ending in @samp{...}.
 
 @node Echo Area Customization
 @subsection Echo Area Customization
address@hidden echo area customization
 
   These variables control details of how the echo area works.
 
@@ -661,6 +664,7 @@ specify a specific warning type.
 
 @node Warning Variables
 @subsection Warning Variables
address@hidden warning variables
 
   Programs can customize how their warnings appear by binding
 the variables described in this section.
@@ -738,6 +742,7 @@ all.
 
 @node Warning Options
 @subsection Warning Options
address@hidden warning options
 
   These variables are used by users to control what happens
 when a Lisp program reports a warning.
@@ -771,6 +776,7 @@ that warning is not logged.
 
 @node Delayed Warnings
 @subsection Delayed Warnings
address@hidden delayed warnings
 
 Sometimes, you may wish to avoid showing a warning while a command is
 running, and only show it only after the end of the command.  You can
@@ -1094,6 +1100,8 @@ You can use a display table to substitute other text for 
the ellipsis
 
 @node Temporary Displays
 @section Temporary Displays
address@hidden temporary display
address@hidden temporary buffer display
 
   Temporary displays are used by Lisp programs to put output into a
 buffer and then present it to the user for perusal rather than for
@@ -1186,12 +1194,6 @@ it prints into the buffer named @var{buffer-or-name} and 
displays that
 buffer in some window.  Unlike @code{with-output-to-temp-buffer},
 however, it does not automatically switch that buffer to Help mode.
 
-Like @code{with-output-to-temp-buffer} it neither makes the buffer
-specified by @var{buffer-or-name} current when executing @var{body}.
address@hidden with-current-buffer-window
-The otherwise identical macro @code{with-current-buffer-window} can be
-used to execute @var{body} with that buffer current.
-
 The argument @var{buffer-or-name} specifies the temporary buffer.  It
 can be either a buffer, which must already exist, or a string, in which
 case a buffer of that name is created, if necessary.  The buffer is
@@ -1199,14 +1201,14 @@ marked as unmodified and read-only when 
@code{with-temp-buffer-window}
 exits.
 
 This macro does not call @code{temp-buffer-show-function}.  Rather, it
-passes the @var{action} argument to @code{display-buffer} in order to
-display the buffer.
+passes the @var{action} argument to @code{display-buffer}
+(@pxref{Choosing Window}) in order to display the buffer.
 
 The value of the last form in @var{body} is returned, unless the
 argument @var{quit-function} is specified.  In that case, it is called
 with two arguments: the window showing the buffer and the result of
address@hidden  The final return value is then whatever
address@hidden returns.
address@hidden  The final return value is then whatever @var{quit-function}
+returns.
 
 @vindex temp-buffer-window-setup-hook
 @vindex temp-buffer-window-show-hook
@@ -1215,6 +1217,56 @@ and @code{temp-buffer-window-show-hook} in place of the 
analogous hooks
 run by @code{with-output-to-temp-buffer}.
 @end defmac
 
+The two constructs described next are mostly identical to
address@hidden but differ from it as specified:
+
address@hidden with-current-buffer-window buffer-or-name action quit-function 
&rest body
+This macro is like @code{with-temp-buffer-window} but unlike that makes
+the buffer specified by @var{buffer-or-name} current for running
address@hidden
address@hidden defmac
+
address@hidden with-displayed-buffer-window buffer-or-name action quit-function 
&rest body
+This macro is like @code{with-current-buffer-window} but unlike that
+displays the buffer specified by @var{buffer-or-name} @emph{before}
+running @var{body}.
address@hidden defmac
+
+A window showing a temporary buffer can be fit to the size of that
+buffer using the following mode:
+
address@hidden temp-buffer-resize-mode
+When this minor mode is enabled, windows showing a temporary buffer are
+automatically resized to fit their buffer's contents.
+
+A window is resized if and only if it has been specially created for the
+buffer.  In particular, windows that have shown another buffer before
+are not resized.  By default, this mode uses @code{fit-window-to-buffer}
+(@pxref{Resizing Windows}) for resizing.  You can specify a different
+function by customizing the options @code{temp-buffer-max-height} and
address@hidden below.
address@hidden defopt
+
address@hidden temp-buffer-max-height
+This option specifies the maximum height (in lines) of a window
+displaying a temporary buffer when @code{temp-buffer-resize-mode} is
+enabled.  It can also be a function to be called to choose the height
+for such a buffer.  It gets one argument, the buffer, and should return
+a positive integer.  At the time the function is called, the window to
+be resized is selected.
address@hidden defopt
+
address@hidden temp-buffer-max-width
+This option specifies the maximum width of a window (in columns)
+displaying a temporary buffer when @code{temp-buffer-resize-mode} is
+enabled.  It can also be a function to be called to choose the width for
+such a buffer.  It gets one argument, the buffer, and should return a
+positive integer.  At the time the function is called, the window to be
+resized is selected.
address@hidden defopt
+
+The following function uses the current buffer for temporal display:
+
 @defun momentary-string-display string position &optional char message
 This function momentarily displays @var{string} in the current buffer at
 @var{position}.  It has no effect on the undo list or on the buffer's
@@ -1305,6 +1357,8 @@ inside the overlay or outside, and likewise for the end 
of the overlay.
 
 @node Managing Overlays
 @subsection Managing Overlays
address@hidden managing overlays
address@hidden overlays, managing
 
   This section describes the functions to create, delete and move
 overlays, and to examine their contents.  Overlay changes are not
@@ -1465,6 +1519,7 @@ faster if you do @code{(overlay-recenter (point-max))} 
first.
 
 @node Overlay Properties
 @subsection Overlay Properties
address@hidden overlay properties
 
   Overlay properties are like text properties in that the properties that
 alter how a character is displayed can come from either source.  But in
@@ -1717,6 +1772,8 @@ Properties}.
 
 @node Finding Overlays
 @subsection Searching for Overlays
address@hidden searching for overlays
address@hidden overlays, searching for
 
 @defun overlays-at pos &optional sorted
 This function returns a list of all the overlays that cover the character at
@@ -1784,6 +1841,8 @@ changes.
 
 @node Size of Displayed Text
 @section Size of Displayed Text
address@hidden size of text on display
address@hidden character width on display
 
 Since not all characters have the same width, these functions let you
 check the width of a character.  @xref{Primitive Indent}, and
@@ -2274,6 +2333,7 @@ suitable for use with @code{:stipple} (see above).  It 
returns
 
 @node Defining Faces
 @subsection Defining Faces
address@hidden defining faces
 
 @cindex face spec
   The usual way to define a face is through the @code{defface} macro.
@@ -2448,6 +2508,7 @@ Any other value of @var{spec-type} is reserved for 
internal use.
 
 @node Attribute Functions
 @subsection Face Attribute Functions
address@hidden face attributes, access and modification
 
   This section describes functions for directly accessing and
 modifying the attributes of a named face.
@@ -2649,6 +2710,8 @@ a address@hidden @code{:inverse-video} attribute.
 
 @node Displaying Faces
 @subsection Displaying Faces
address@hidden displaying faces
address@hidden face merging
 
   When Emacs displays a given piece of text, the visual appearance of
 the text may be determined by faces drawn from different sources.  If
@@ -2704,6 +2767,7 @@ at the next level of face merging.
 
 @node Face Remapping
 @subsection Face Remapping
address@hidden face remapping
 
   The variable @code{face-remapping-alist} is used for buffer-local or
 global changes in the appearance of a face.  For instance, it is used
@@ -2901,6 +2965,7 @@ usually assign faces to around 400 to 600 characters at 
each call.
 
 @node Basic Faces
 @subsection Basic Faces
address@hidden basic faces
 
 If your Emacs Lisp program needs to assign some faces to text, it is
 often a good idea to use certain existing faces or inherit from them,
@@ -3067,6 +3132,8 @@ nominal heights and widths would suggest.
 
 @node Font Lookup
 @subsection Looking Up Fonts
address@hidden font lookup
address@hidden looking up fonts
 
 @defun x-list-fonts name &optional reference-face frame maximum width
 This function returns a list of available font names that match
@@ -3124,6 +3191,7 @@ encoding of the font.
 
 @node Fontsets
 @subsection Fontsets
address@hidden fontset
 
   A @dfn{fontset} is a list of fonts, each assigned to a range of
 character codes.  An individual font cannot display the whole range of
@@ -4237,6 +4305,7 @@ display specifications and what they mean.
 
 @node Replacing Specs
 @subsection Display Specs That Replace The Text
address@hidden replacing display specs
 
   Some kinds of display specifications specify something to display
 instead of the text that has the property.  These are called
@@ -5113,6 +5182,7 @@ Supports the @code{:index} property.  @xref{Multi-Frame 
Images}.
 
 @node Defining Images
 @subsection Defining Images
address@hidden define image
 
   The functions @code{create-image}, @code{defimage} and
 @code{find-image} provide convenient ways to create image descriptors.
@@ -5240,6 +5310,7 @@ Here is an example of using 
@code{image-load-path-for-library}:
 
 @node Showing Images
 @subsection Showing Images
address@hidden show image
 
   You can use an image descriptor by setting up the @code{display}
 property yourself, but it is easier to use the functions in this
diff --git a/doc/lispref/files.texi b/doc/lispref/files.texi
index b79d5df..55da631 100644
--- a/doc/lispref/files.texi
+++ b/doc/lispref/files.texi
@@ -81,6 +81,8 @@ computer program, however, it is good to keep the distinction 
in mind.
 
 @node Visiting Functions
 @subsection Functions for Visiting Files
address@hidden visiting files, functions for
address@hidden how to visit files
 
   This section describes the functions normally used to visit files.
 For historical reasons, these functions have names starting with
@@ -948,6 +950,8 @@ Unix.  These conventions are also followed by 
@code{file-attributes}
 
 @node Kinds of Files
 @subsection Distinguishing Kinds of Files
address@hidden file classification
address@hidden classification of file types
 
   This section describes how to distinguish various kinds of files, such
 as directories, symbolic links, and ordinary files.
@@ -2300,6 +2304,8 @@ through the immediately preceding @samp{/}).
 
 @node Unique File Names
 @subsection Generating Unique File Names
address@hidden unique file names
address@hidden temporary files
 
   Some programs need to write temporary files.  Here is the usual way to
 construct a name for such a file:
diff --git a/doc/lispref/frames.texi b/doc/lispref/frames.texi
index 0bded22..c1da337 100644
--- a/doc/lispref/frames.texi
+++ b/doc/lispref/frames.texi
@@ -106,6 +106,7 @@ for @code{framep} above.
 
 @node Creating Frames
 @section Creating Frames
address@hidden frame creation
 
 To create a new frame, call the function @code{make-frame}.
 
@@ -484,6 +485,7 @@ parameter values to frames that will be created henceforth.
 
 @node Initial Parameters
 @subsection Initial Frame Parameters
address@hidden parameters of initial frame
 
 You can specify the parameters for the initial startup frame by
 setting @code{initial-frame-alist} in your init file (@pxref{Init
@@ -623,6 +625,7 @@ named, this parameter will be @code{nil}.
 @node Position Parameters
 @subsubsection Position Parameters
 @cindex window position on display
address@hidden frame position
 
   Position parameters' values are normally measured in pixels, but on
 text terminals they count characters or lines instead.
@@ -833,6 +836,8 @@ integer).  @xref{Line Height}, for more information.
 
 @node Buffer Parameters
 @subsubsection Buffer Parameters
address@hidden frame, which buffers to display
address@hidden buffers to display on frame
 
   These frame parameters, meaningful on all kinds of terminals, deal
 with which buffers have been, or should, be displayed in the frame.
@@ -1663,6 +1668,7 @@ is used whenever that frame is selected.  If the frame 
has a minibuffer,
 you can get it with @code{minibuffer-window} (@pxref{Definition of
 minibuffer-window}).
 
address@hidden frame without a minibuffer
 However, you can also create a frame with no minibuffer.  Such a frame
 must use the minibuffer window of some other frame.  When you create the
 frame, you can explicitly specify the minibuffer window to use (in some
@@ -2070,6 +2076,7 @@ allows to know if the pointer has been hidden.
 
 @node Pop-Up Menus
 @section Pop-Up Menus
address@hidden menus, popup
 
   A Lisp program can pop up a menu so that the user can choose an
 alternative with the mouse.  On a text terminal, if the mouse is not
@@ -2334,6 +2341,7 @@ clipboard as empty.
 
 @node Drag and Drop
 @section Drag and Drop
address@hidden drag and drop
 
 @vindex x-dnd-test-function
 @vindex x-dnd-known-types
diff --git a/doc/lispref/functions.texi b/doc/lispref/functions.texi
index 0ac084b..9555c21 100644
--- a/doc/lispref/functions.texi
+++ b/doc/lispref/functions.texi
@@ -1214,7 +1214,8 @@ ways to do it.  The added function is also called a piece 
of @emph{advice}.
 @end menu
 
 @node Core Advising Primitives
address@hidden Primitives to manipulate advice
address@hidden Primitives to manipulate advices
address@hidden advice, add and remove
 
 @defmac add-function where place function &optional props
 This macro is the handy way to add the advice @var{function} to the function
@@ -1316,6 +1317,7 @@ the current prefix argument.
 
 @node Advising Named Functions
 @subsection Advising Named Functions
address@hidden advising named functions
 
 A common use of advice is for named functions and macros.
 You could just use @code{add-function} as in:
@@ -1508,6 +1510,7 @@ More specifically, the composition of the two functions 
behaves like:
 
 @node Porting old advice
 @subsection Adapting code using the old defadvice
address@hidden old advices, porting
 
 A lot of code uses the old @code{defadvice} mechanism, which is largely made
 obsolete by the new @code{advice-add}, whose implementation and semantics is
diff --git a/doc/lispref/hash.texi b/doc/lispref/hash.texi
index 536777a..323a2ed 100644
--- a/doc/lispref/hash.texi
+++ b/doc/lispref/hash.texi
@@ -188,6 +188,8 @@ Such objects may be added to the hash table after it is 
created.
 
 @node Hash Access
 @section Hash Table Access
address@hidden accessing hash tables
address@hidden hash table access
 
   This section describes the functions for accessing and storing
 associations in a hash table.  In general, any Lisp object can be used
diff --git a/doc/lispref/help.texi b/doc/lispref/help.texi
index 20fb0e6..2e3b51e 100644
--- a/doc/lispref/help.texi
+++ b/doc/lispref/help.texi
@@ -90,6 +90,7 @@ hyperlinks in the @file{*Help*} buffer.)
 
 @node Accessing Documentation
 @section Access to Documentation Strings
address@hidden accessing documentation strings
 
 @defun documentation-property symbol property &optional verbatim
 This function returns the documentation string recorded in
@@ -507,6 +508,7 @@ address@hidden, the return value is always a vector.
 
 @node Help Functions
 @section Help Functions
address@hidden help functions
 
   Emacs provides a variety of built-in help functions, all accessible to
 the user as subcommands of the prefix @kbd{C-h}.  For more information
diff --git a/doc/lispref/keymaps.texi b/doc/lispref/keymaps.texi
index e652da0..91dc5ea 100644
--- a/doc/lispref/keymaps.texi
+++ b/doc/lispref/keymaps.texi
@@ -782,6 +782,7 @@ Lookup}.
 
 @node Controlling Active Maps
 @section Controlling the Active Keymaps
address@hidden active keymap, controlling
 
 @defvar global-map
 This variable contains the default global keymap that maps Emacs
@@ -1806,6 +1807,8 @@ local map.
 
 @node Scanning Keymaps
 @section Scanning Keymaps
address@hidden scanning keymaps
address@hidden keymaps, scanning
 
   This section describes functions used to scan all the current keymaps
 for the sake of printing help information.
@@ -2775,6 +2778,7 @@ function keys.
 
 @node Modifying Menus
 @subsection Modifying Menus
address@hidden menu modification
 
   When you insert a new item in an existing menu, you probably want to
 put it in a particular place among the menu's existing items.  If you
diff --git a/doc/lispref/lists.texi b/doc/lispref/lists.texi
index 21be5cc..e438335 100644
--- a/doc/lispref/lists.texi
+++ b/doc/lispref/lists.texi
@@ -84,6 +84,8 @@ structure made out of cons cells as a @dfn{list structure}.
 
 @node List-related Predicates
 @section Predicates on Lists
address@hidden predicates for lists
address@hidden list predicates
 
   The following predicates test whether a Lisp object is an atom,
 whether it is a cons cell or is a list, or whether it is the
@@ -662,6 +664,8 @@ Some examples:
 
 @node List Variables
 @section Modifying List Variables
address@hidden modify a list
address@hidden list modification
 
   These functions, and one macro, provide convenient ways
 to modify a list which is stored in a variable.
@@ -818,6 +822,8 @@ new @sc{car} or @sc{cdr}.
 
 @node Setcar
 @subsection Altering List Elements with @code{setcar}
address@hidden replace list element
address@hidden list, replace element
 
   Changing the @sc{car} of a cons cell is done with @code{setcar}.  When
 used on a list, @code{setcar} replaces one element of a list with a
@@ -923,6 +929,7 @@ x2:              |
 
 @node Setcdr
 @subsection Altering the CDR of a List
address@hidden replace part of list
 
   The lowest-level primitive for modifying a @sc{cdr} is @code{setcdr}:
 
@@ -1759,6 +1766,8 @@ and later discarded; this is not possible with a property 
list.
 
 @node Plist Access
 @subsection Property Lists Outside Symbols
address@hidden plist access
address@hidden accessing plist properties
 
   The following functions can be used to manipulate property lists.
 They all compare property names using @code{eq}.
diff --git a/doc/lispref/loading.texi b/doc/lispref/loading.texi
index a07c2e8..a0393c9 100644
--- a/doc/lispref/loading.texi
+++ b/doc/lispref/loading.texi
@@ -419,6 +419,8 @@ the shadowed files as a string.
 
 @node Loading Non-ASCII
 @section Loading address@hidden Characters
address@hidden loading, and non-ASCII characters
address@hidden non-ASCII characters in loaded files
 
   When Emacs Lisp programs contain string constants with address@hidden
 characters, these can be represented within Emacs either as unibyte
@@ -907,6 +909,8 @@ with a call to @code{provide}.  The order of the elements 
in the
 
 @node Where Defined
 @section Which File Defined a Certain Symbol
address@hidden symbol, where defined
address@hidden where was a symbol defined
 
 @defun symbol-file symbol &optional type
 This function returns the name of the file that defined @var{symbol}.
diff --git a/doc/lispref/macros.texi b/doc/lispref/macros.texi
index 9be12fa..8a4741c 100644
--- a/doc/lispref/macros.texi
+++ b/doc/lispref/macros.texi
@@ -194,6 +194,8 @@ During Compile}).
 
 @node Defining Macros
 @section Defining Macros
address@hidden defining macros
address@hidden macro, how to define
 
   A Lisp macro object is a list whose @sc{car} is @code{macro}, and
 whose @sc{cdr} is a function.  Expansion of the macro works
@@ -253,6 +255,7 @@ Form}.
 
 @node Problems with Macros
 @section Common Problems Using Macros
address@hidden macro caveats
 
   Macro expansion can have counterintuitive consequences.  This
 section describes some important consequences that can lead to
diff --git a/doc/lispref/markers.texi b/doc/lispref/markers.texi
index 51b87ab..5902a3a 100644
--- a/doc/lispref/markers.texi
+++ b/doc/lispref/markers.texi
@@ -118,6 +118,8 @@ m1
 
 @node Predicates on Markers
 @section Predicates on Markers
address@hidden predicates for markers
address@hidden markers, predicates for
 
   You can test an object to see whether it is a marker, or whether it is
 either an integer or a marker.  The latter test is useful in connection
@@ -141,6 +143,8 @@ integer or floating point) or a marker, @code{nil} 
otherwise.
 
 @node Creating Markers
 @section Functions that Create Markers
address@hidden creating markers
address@hidden marker creation
 
   When you create a new marker, you can make it point nowhere, or point
 to the present position of point, or to the beginning or end of the
@@ -269,6 +273,7 @@ if they both point nowhere.
 
 @node Information from Markers
 @section Information from Markers
address@hidden marker information
 
   This section describes the functions for accessing the components of a
 marker object.
@@ -342,6 +347,8 @@ specify the insertion type, create them with insertion type
 
 @node Moving Markers
 @section Moving Marker Positions
address@hidden moving markers
address@hidden marker, how to move position
 
   This section describes how to change the position of an existing
 marker.  When you do this, be sure you know whether the marker is used
diff --git a/doc/lispref/minibuf.texi b/doc/lispref/minibuf.texi
index 57ae0e9..e6d6ad0 100644
--- a/doc/lispref/minibuf.texi
+++ b/doc/lispref/minibuf.texi
@@ -107,6 +107,7 @@ are available in batch mode.
 
 @node Text from Minibuffer
 @section Reading Text Strings with the Minibuffer
address@hidden minibuffer input, reading text strings
 
   The most basic primitive for minibuffer input is
 @code{read-from-minibuffer}, which can be used to read either a string
@@ -390,6 +391,7 @@ following bindings, in addition to those of 
@code{minibuffer-local-map}:
 
 @node Object from Minibuffer
 @section Reading Lisp Objects with the Minibuffer
address@hidden minibuffer input, reading lisp objects
 
   This section describes functions for reading Lisp objects with the
 minibuffer.
@@ -2044,6 +2046,7 @@ Do you really want to remove everything? (yes or no)
 
 @node Multiple Queries
 @section Asking Multiple Y-or-N Questions
address@hidden multiple yes-or-no questions
 
   When you have a series of similar questions to ask, such as ``Do you
 want to save this buffer'' for each buffer in turn, you should use
@@ -2285,6 +2288,8 @@ default value is 0.25.
 
 @node Minibuffer Contents
 @section Minibuffer Contents
address@hidden access minibuffer contents
address@hidden minibuffer contents, accessing
 
   These functions access the minibuffer prompt and contents.
 
diff --git a/doc/lispref/modes.texi b/doc/lispref/modes.texi
index d67bac6..509982a 100644
--- a/doc/lispref/modes.texi
+++ b/doc/lispref/modes.texi
@@ -1490,7 +1490,7 @@ A positive prefix argument enables the mode, any other 
prefix argument
 disables it.  From Lisp, an argument of @code{toggle} toggles the mode,
 whereas an omitted or @code{nil} argument enables the mode.
 This makes it easy to enable the minor mode in a major mode hook, for example.
-If @var{doc} is nil, the macro supplies a default documentation string
+If @var{doc} is @code{nil}, the macro supplies a default documentation string
 explaining the above.
 
 By default, it also defines a variable named @var{mode}, which is set to
@@ -3659,7 +3659,7 @@ For example:
 Notice how those lexers return the empty string when in front of
 parentheses.  This is because SMIE automatically takes care of the
 parentheses defined in the syntax table.  More specifically if the lexer
-returns nil or an empty string, SMIE tries to handle the corresponding
+returns @code{nil} or an empty string, SMIE tries to handle the corresponding
 text as a sexp according to syntax tables.
 
 @node SMIE Tricks
diff --git a/doc/lispref/nonascii.texi b/doc/lispref/nonascii.texi
index 902eb40..fedf933 100644
--- a/doc/lispref/nonascii.texi
+++ b/doc/lispref/nonascii.texi
@@ -783,6 +783,8 @@ of them is @code{nil}, it defaults to the first or last 
codepoint of
 
 @node Scanning Charsets
 @section Scanning for Character Sets
address@hidden scanning for character sets
address@hidden character set, searching
 
   Sometimes it is useful to find out which character set a particular
 character belongs to.  One use for this is in determining which coding
@@ -1620,6 +1622,9 @@ contents (as it usually does), it should examine the 
contents of
 
 @node Specifying Coding Systems
 @subsection Specifying a Coding System for One Operation
address@hidden specify coding system
address@hidden force coding system for operation
address@hidden coding system for operation
 
   You can specify the coding system for a specific operation by binding
 the variables @code{coding-system-for-read} and/or
diff --git a/doc/lispref/os.texi b/doc/lispref/os.texi
index b709447..91bd190 100644
--- a/doc/lispref/os.texi
+++ b/doc/lispref/os.texi
@@ -917,13 +917,6 @@ This function returns the name of the machine you are 
running on, as a
 string.
 @end defun
 
-  The symbol @code{system-name} is a variable as well as a function.  In
-fact, the function returns whatever value the variable
address@hidden currently holds.  Thus, you can set the variable
address@hidden in case Emacs is confused about the name of your
-system.  The variable is also useful for constructing frame titles
-(@pxref{Frame Titles}).
-
 @c FIXME seems like this section is not the best place for this option?
 @defopt mail-host-address
 If this variable is address@hidden, it is used instead of
@@ -1208,6 +1201,7 @@ return value is @code{nil}.
 
 @node Time of Day
 @section Time of Day
address@hidden time of day
 
   This section explains how to determine the current time and time
 zone.
@@ -1320,6 +1314,7 @@ time zone.
 @node Time Conversion
 @section Time Conversion
 @cindex calendrical information
address@hidden time conversion
 
   These functions convert time values (@pxref{Time of Day}) into
 calendrical information and vice versa.
@@ -1415,6 +1410,9 @@ on others, years as early as 1901 do work.
 
 @node Time Parsing
 @section Parsing and Formatting Times
address@hidden time parsing
address@hidden time formatting
address@hidden formatting time values
 
   These functions convert time values to text in a string, and vice versa.
 Time values are lists of two to four integers (@pxref{Time of Day}).
@@ -1643,6 +1641,9 @@ interactively, it prints the duration in the echo area.
 
 @node Time Calculations
 @section Time Calculations
address@hidden time calculations
address@hidden comparing time values
address@hidden calendrical computations
 
   These functions perform calendrical computations using time values
 (@pxref{Time of Day}).
@@ -1823,6 +1824,7 @@ cause anything special to happen.
 
 @node Idle Timers
 @section Idle Timers
address@hidden idle timers
 
   Here is how to set up a timer that runs when Emacs is idle for a
 certain length of time.  Aside from how to set them up, idle timers
@@ -2529,7 +2531,7 @@ The server's version number.
 The specification version the server is compliant with.
 @end table
 
-If @var{SPEC_VERSION} is @code{nil}, the server supports a
+If @var{spec_version} is @code{nil}, the server supports a
 specification prior to @samp{"1.0"}.
 @end defun
 
diff --git a/doc/lispref/positions.texi b/doc/lispref/positions.texi
index 032baa9..24ff5d8 100644
--- a/doc/lispref/positions.texi
+++ b/doc/lispref/positions.texi
@@ -465,6 +465,7 @@ beginning or end of a line.
 
 @node Screen Lines
 @subsection Motion by Screen Lines
address@hidden screen lines, moving by
 
   The line functions in the previous section count text lines, delimited
 only by newline characters.  By contrast, these functions count screen
diff --git a/doc/lispref/processes.texi b/doc/lispref/processes.texi
index 0952cc1..856831d 100644
--- a/doc/lispref/processes.texi
+++ b/doc/lispref/processes.texi
@@ -63,6 +63,8 @@ Processes}.
 
 @node Subprocess Creation
 @section Functions that Create Subprocesses
address@hidden create subprocess
address@hidden process creation
 
   There are three primitives that create a new subprocess in which to run
 a program.  One of them, @code{start-process}, creates an asynchronous
@@ -734,6 +736,7 @@ happen sooner or later).
 
 @node Process Information
 @section Process Information
address@hidden process information
 
   Several functions return information about processes.
 
diff --git a/doc/lispref/searching.texi b/doc/lispref/searching.texi
index 992ad00..19c515f 100644
--- a/doc/lispref/searching.texi
+++ b/doc/lispref/searching.texi
@@ -257,6 +257,8 @@ it easier to verify even very complex regexps.
 
 @node Syntax of Regexps
 @subsection Syntax of Regular Expressions
address@hidden regexp syntax
address@hidden syntax of regular expressions
 
   Regular expressions have a syntax in which a few characters are
 special constructs and the rest are @dfn{ordinary}.  An ordinary
@@ -294,6 +296,7 @@ need to use one of the special regular expression 
constructs.
 
 @node Regexp Special
 @subsubsection Special Characters in Regular Expressions
address@hidden regexp, special characters in
 
   Here is a list of the characters that are special in a regular
 expression.
@@ -894,6 +897,7 @@ beyond the minimum needed to end a sentence.
 
   These functions operate on regular expressions.
 
address@hidden quote special characters in regexp
 @defun regexp-quote string
 This function returns a regular expression whose only exact match is
 @var{string}.  Using this regular expression in @code{looking-at} will
@@ -924,6 +928,7 @@ whitespace:
 @end example
 @end defun
 
address@hidden optimize regexp
 @defun regexp-opt strings &optional paren
 This function returns an efficient regular expression that will match
 any of the strings in the list @var{strings}.  This is useful when you
diff --git a/doc/lispref/strings.texi b/doc/lispref/strings.texi
index 1ecc567..026c7a7 100644
--- a/doc/lispref/strings.texi
+++ b/doc/lispref/strings.texi
@@ -92,6 +92,8 @@ representations and to encode and decode character codes.
 
 @node Predicates for Strings
 @section Predicates for Strings
address@hidden predicates for strings
address@hidden string predicates
 
 For more information about general sequence and array predicates,
 see @ref{Sequences Arrays Vectors}, and @ref{Arrays}.
@@ -113,6 +115,8 @@ character (i.e., an integer), @code{nil} otherwise.
 
 @node Creating Strings
 @section Creating Strings
address@hidden creating strings
address@hidden string creation
 
   The following functions create strings, either from scratch, or by
 putting strings together, or by taking them apart.
@@ -367,6 +371,8 @@ usual value is @address@hidden"[ \f\t\n\r\v]+"}}.
 
 @node Modifying Strings
 @section Modifying Strings
address@hidden modifying strings
address@hidden string modification
 
   The most basic way to alter the contents of an existing string is with
 @code{aset} (@pxref{Array Functions}).  @code{(aset @var{string}
@@ -400,6 +406,7 @@ zeros.  It may also change @var{string}'s length.
 @node Text Comparison
 @section Comparison of Characters and Strings
 @cindex string equality
address@hidden text comparison
 
 @defun char-equal character1 character2
 This function returns @code{t} if the arguments represent the same
diff --git a/doc/lispref/syntax.texi b/doc/lispref/syntax.texi
index 25e6089..33577e7 100644
--- a/doc/lispref/syntax.texi
+++ b/doc/lispref/syntax.texi
@@ -592,6 +592,8 @@ in turn, repeatedly, until they all return @code{nil}.
 
 @node Motion and Syntax
 @section Motion and Syntax
address@hidden moving across syntax classes
address@hidden skipping characters of certain syntax
 
   This section describes functions for moving across characters that
 have certain syntax classes.
@@ -631,6 +633,8 @@ expression prefix syntax class, and characters with the 
@samp{p} flag.
 
 @node Parsing Expressions
 @section Parsing Expressions
address@hidden parsing expressions
address@hidden scanning expressions
 
   This section describes functions for parsing and scanning balanced
 expressions.  We will refer to such expressions as @dfn{sexps},
@@ -673,6 +677,7 @@ result, Emacs treats them as four consecutive empty string 
constants.
 
 @node Motion via Parsing
 @subsection Motion Commands Based on Parsing
address@hidden motion based on parsing
 
   This section describes simple point-motion functions that operate
 based on parsing expressions.
@@ -738,6 +743,7 @@ cannot exceed that many.
 
 @node Position Parse
 @subsection Finding the Parse State for a Position
address@hidden parse state for a position
 
   For syntactic analysis, such as in indentation, often the useful
 thing is to compute the syntactic state corresponding to a given buffer
@@ -919,6 +925,7 @@ nicely.
 
 @node Control Parsing
 @subsection Parameters to Control Parsing
address@hidden parsing, control parameters
 
 @defvar multibyte-syntax-as-symbol
 If this variable is address@hidden, @code{scan-sexps} treats all
diff --git a/doc/lispref/text.texi b/doc/lispref/text.texi
index 06d1381..379fb29 100644
--- a/doc/lispref/text.texi
+++ b/doc/lispref/text.texi
@@ -162,6 +162,7 @@ the end of a line.
 
 @node Buffer Contents
 @section Examining Buffer Contents
address@hidden buffer portion as string
 
   This section describes functions that allow a Lisp program to
 convert any portion of the text in the buffer into a string.
@@ -2679,6 +2680,8 @@ along with the characters; this includes such diverse 
functions as
 
 @node Examining Properties
 @subsection Examining Text Properties
address@hidden examining text properties
address@hidden text properties, examining
 
   The simplest way to examine text properties is to ask for the value of
 a particular property of a particular character.  For that, use
@@ -2770,6 +2773,8 @@ used instead.  Here is an example:
 
 @node Changing Properties
 @subsection Changing Text Properties
address@hidden changing text properties
address@hidden text properties, changing
 
   The primitives for changing properties apply to a specified range of
 text in a buffer or string.  The function @code{set-text-properties}
@@ -2933,6 +2938,8 @@ buffer but does not copy its properties.
 
 @node Property Search
 @subsection Text Property Search Functions
address@hidden searching text properties
address@hidden text properties, searching
 
   In typical use of text properties, most of the time several or many
 consecutive characters have the same value for a property.  Rather than
@@ -3991,6 +3998,8 @@ coalesced whenever possible.  @xref{Property Search}.
 
 @node Substitution
 @section Substituting for a Character Code
address@hidden replace characters in region
address@hidden substitute characters
 
   The following functions replace characters within a specified region
 based on their character codes.
diff --git a/doc/lispref/variables.texi b/doc/lispref/variables.texi
index e890dbc..b3466e6 100644
--- a/doc/lispref/variables.texi
+++ b/doc/lispref/variables.texi
@@ -1951,6 +1951,7 @@ foo
 
 @node Variables with Restricted Values
 @section Variables with Restricted Values
address@hidden lisp variables defined in C, restrictions
 
   Ordinary Lisp variables can be assigned any value that is a valid
 Lisp object.  However, certain Lisp variables are not defined in Lisp,
@@ -1987,6 +1988,8 @@ Attempting to assign them any other value will result in 
an error:
 @node Generalized Variables
 @section Generalized Variables
 
address@hidden generalized variable
address@hidden place form
 A @dfn{generalized variable} or @dfn{place form} is one of the many places
 in Lisp memory where values can be stored.  The simplest place form is
 a regular Lisp variable.  But the @sc{car}s and @sc{cdr}s of lists, elements
diff --git a/doc/lispref/windows.texi b/doc/lispref/windows.texi
index 7c8d0b0..a172a4a 100644
--- a/doc/lispref/windows.texi
+++ b/doc/lispref/windows.texi
@@ -1252,6 +1252,8 @@ are the opposite of what they are in those other 
functions.
 
 @node Recombining Windows
 @section Recombining Windows
address@hidden recombining windows
address@hidden windows, recombining
 
 When deleting the last sibling of a window @var{W}, its parent window
 is deleted too, with @var{W} replacing it in the window tree.  This
diff --git a/doc/misc/efaq.texi b/doc/misc/efaq.texi
index 0159101..71c5ae0 100644
--- a/doc/misc/efaq.texi
+++ b/doc/misc/efaq.texi
@@ -1469,7 +1469,7 @@ machine at which Emacs was invoked.  This is done by 
setting
 @code{frame-title-format} to the default value of
 
 @lisp
-(multiple-frames "%b" ("" invocation-name "@@" system-name))
+(multiple-frames "%b" ("" invocation-name "@@" (system-name)))
 @end lisp
 
 To modify the behavior such that frame titlebars contain the buffer's
diff --git a/doc/misc/smtpmail.texi b/doc/misc/smtpmail.texi
index f539cd0..9cddbfa 100644
--- a/doc/misc/smtpmail.texi
+++ b/doc/misc/smtpmail.texi
@@ -368,7 +368,7 @@ implement support for common requirements.
 @vindex smtpmail-local-domain
   The variable @code{smtpmail-local-domain} controls the hostname sent
 in the first @code{EHLO} or @code{HELO} command sent to the server.
-It should only be set if the @code{system-name} function returns a
+It should be set only if the @code{system-name} function returns a
 name that isn't accepted by the server.  Do not set this variable
 unless your server complains.
 
diff --git a/etc/ChangeLog b/etc/ChangeLog
index 814b94d..3c48c51 100644
--- a/etc/ChangeLog
+++ b/etc/ChangeLog
@@ -1,3 +1,11 @@
+2014-12-30  Paul Eggert  <address@hidden>
+
+       * PROBLEMS: Omit obsolete mention of FQDNs.
+
+2014-12-27  Álvar Ibeas  <address@hidden>  (tiny change)
+
+       * tutorials/TUTORIAL.es: Improve style consistency.  Spelling fixes.
+
 2014-12-25  Karl Fogel  <address@hidden>
 
        * NEWS: Mention new buffer display behavior for `shell'.
diff --git a/etc/NEWS b/etc/NEWS
index 14933aa..ae0cb70 100644
--- a/etc/NEWS
+++ b/etc/NEWS
@@ -401,10 +401,13 @@ and comments.
 the color range from `vc-annotate-color-map' is applied to the
 background or to the foreground.
 
-*** compare-windows now compares text with the most recently used window
+*** `compare-windows' now compares text with the most recently used window
 instead of the next window.  The new option 
`compare-windows-get-window-function'
 allows to customize this.
 
+*** Two new faces `compare-windows-removed' and `compare-windows-added'
+replace the obsolete face `compare-windows'.
+
 ** Calculator: decimal display mode uses "," groups, so it's more
 fitting for use in money calculations; factorial works with
 non-integer inputs.
@@ -453,6 +456,11 @@ easier binding, which is now unoccupied (`M-,').
 alias for a private variable.  `xref-push-marker-stack' and
 `xref-pop-marker-stack' should be used to mutate it instead.
 
+** etags
+As a result of the above, these commands are now obsolete:
+`find-tag-other-window', `find-tag-other-frame', `find-tag-regexp',
+`tags-apropos' and `tags-loop-continue'.
+
 ** Obsolete packages
 
 ---
@@ -533,6 +541,11 @@ optional repeat-count argument.
 
 ** Function `sort' can deal with vectors.
 
+** Function `system-name' now returns an updated value if the current
+system's name has changed or if the Emacs process has changed systems,
+and to avoid long waits it no longer consults DNS to canonicalize the
+name.  The variable `system-name' is now obsolete.
+
 ---
 ** New utilities in subr-x.el:
 *** New macros `if-let' and `when-let' allow defining bindings and to
diff --git a/etc/PROBLEMS b/etc/PROBLEMS
index 67a26b9..e1463f1 100644
--- a/etc/PROBLEMS
+++ b/etc/PROBLEMS
@@ -364,8 +364,8 @@ For example, (system-name) returns some variation on
 "localhost.localdomain", rather the name you were expecting.
 
 You need to configure your machine with a fully qualified domain name,
-(i.e. a name with at least one ".") either in /etc/hosts,
-/etc/hostname, the NIS, or wherever your system calls for specifying this.
+(i.e., a name with at least one "."), either in /etc/hostname
+or wherever your system calls for specifying this.
 
 If you cannot fix the configuration, you can set the Lisp variable
 mail-host-address to the value you want.
@@ -457,17 +457,6 @@ problem by adding this to your .cshrc file:
         endif
     endif
 
-*** Emacs startup on GNU/Linux systems (and possibly other systems) is slow.
-
-This can happen if the system is misconfigured and Emacs can't get the
-full qualified domain name, FQDN.  You should have your FQDN in the
-/etc/hosts file, something like this:
-
-127.0.0.1      localhost
-129.187.137.82 nuc04.t30.physik.tu-muenchen.de nuc04
-
-The way to set this up may vary on non-GNU systems.
-
 *** Attempting to visit remote files via ange-ftp fails.
 
 If the error message is "ange-ftp-file-modtime: Specified time is not
diff --git a/etc/grep.txt b/etc/grep.txt
index 523b1fa..b96a916 100644
--- a/etc/grep.txt
+++ b/etc/grep.txt
@@ -39,7 +39,7 @@ grep -nH --color=always -e "INFO tree" ../info/*
 
 * GNU grep 2.5.1 on lines starting with a number and colon
 
-grep -nH -e "Universal Time" ../lispref/*
+grep -nH --color=always -e "Universal Time" ../doc/lispref/*
 ../lispref/os.texi:1010:0:00 January 1, 1970 UTC (Coordinated 
Universal Time)
 
 * GNU grep 2.5.1 with context lines
@@ -78,8 +78,8 @@ bzr grep --color=always -in "org-element-map"
 lisp/org/org.el:21047:                    
(org-element-map
 
 * git-grep
-  with `[diff "el"] xfuncname = "^(\\(.*)$"' in .gitconfig
-  and `*.el diff=el' in .gitattributes
+  with `[diff "lisp"] xfuncname = "^(\\(.*)$"' in .gitconfig
+  and `*.el diff=lisp' in .gitattributes
 
 git --no-pager grep -inH -p -e "org-element-map"
 lisp/org/org.el=20969=(defun org-fill-paragraph (&optional 
justify)
diff --git a/etc/tutorials/TUTORIAL.es b/etc/tutorials/TUTORIAL.es
index 604aaf7..0983e5d 100644
--- a/etc/tutorials/TUTORIAL.es
+++ b/etc/tutorials/TUTORIAL.es
@@ -16,7 +16,7 @@ ocasión, usaremos las siguientes abreviaturas.
 Nota importante: para terminar la sesión de Emacs teclee C-x C-c (dos
 caracteres).  Para cancelar un comando parcialmente introducido,
 teclee C-g.
-Los caracteres ">>" en el margen izquierdo indican instrucciones para
+Los caracteres «>>» en el margen izquierdo indican instrucciones para
 que usted trate de usar un comando.  Por ejemplo:
 <<Blank lines inserted around following line by help-with-tutorial>>
 [Mitad de página en blanco para propósitos didácticos.  El texto continúa 
abajo]
@@ -67,11 +67,11 @@ Es útil moverse de una pantalla completa a otra pero, ¿cómo 
moverse a
 un lugar específico dentro del texto en la pantalla?
 
 Puede hacerlo de diversas formas.  Puede usar las teclas de flechas,
-pero es mas eficiente mantener las manos en la posición estándar y
+pero es más eficiente mantener las manos en la posición estándar y
 usar los comandos C-p, C-b, C-f, y C-n.  Estos caracteres son
 equivalentes a las cuatro teclas de flechas, de esta manera:
 
-                       Línea anterior, C-P
+                       Línea anterior, C-p
                                :
                                :
    Atrás, C-b.... Posición actual del cursor .... Adelante, C-f
@@ -111,7 +111,7 @@ C-f puede moverse a través de una nueva línea igual que C-b.
 
 Cuando pase el tope o el final de la pantalla, se mostrará el texto
 más allá del borde de la pantalla.  Esto recibe el nombre de
-"desplazamiento".  Esto le permite a Emacs mover el cursor al lugar
+«desplazamiento».  Esto le permite a Emacs mover el cursor al lugar
 especificado en el texto sin moverlo fuera de la pantalla.
 
 >> Intente mover el cursor fuera del borde de la pantalla con C-n, y
@@ -133,10 +133,10 @@ dirección opuesta.
 
 Note el paralelo entre C-f y C-b de un lado y M-f y M-b del otro.  Muy
 frecuentemente los caracteres Meta se usan para operaciones
-relacionadas, con las unidades definidas por el lenguaje (palabras,
+relacionadas con las unidades definidas por el lenguaje (palabras,
 oraciones y párrafos), mientras los caracteres Control operan sobre
 unidades básicas que son independientes de lo que está editando
-(caracteres, líneas, etc).
+(caracteres, líneas, etc.).
 
 Este paralelo se aplica entre líneas y oraciones: C-a y C-e para
 moverse al comienzo o al final de la línea; y M-a y M-e para mover al
@@ -149,7 +149,7 @@ Vea cómo la repetición de C-a no hace nada, pero la 
repetición de M-a
 sigue moviendo una oración más.  Aunque no son muy análogas, cada una
 parece natural.
 
-La ubicación del cursor en el texto se llama también "punto".  En
+La ubicación del cursor en el texto se llama también «punto».  En
 otras palabras, el cursor muestra sobre la pantalla donde está
 situado el punto dentro del texto.
 
@@ -178,7 +178,7 @@ Otros dos comandos importantes de movimiento del cursor son 
M-< (META
 Menor que), el cual se mueve al comienzo del texto entero, y M-> (META
 Mayor que), el cual se mueve al final del texto entero.
 
-En la mayoría de las terminales, el "<" está sobre la coma, por lo
+En la mayoría de las terminales, el «<» está sobre la coma, por lo
 tanto tiene que usar la tecla shift para teclearlo.  En estas
 terminales tendrá que usar la tecla shift también al teclear M-<; sin
 la tecla shift, usted estaría escribiendo M-coma.
@@ -207,7 +207,7 @@ una tecla META (o EDIT o ALT), hay una manera alternativa 
para
 ingresar un argumento numérico: teclear los dígitos mientras presiona
 la tecla META.  Recomendamos aprender el método C-u porque éste
 funciona en cualquier terminal.  El argumento numérico es también
-llamado un "argumento prefijo", porque usted teclea el argumento antes
+llamado un «argumento prefijo», porque usted teclea el argumento antes
 del comando al que se aplica.
 
 Por ejemplo, C-u 8 C-f mueve hacia adelante ocho caracteres.
@@ -253,7 +253,7 @@ comienzo de un comando que no quiere finalizar.
 
 >> Escriba C-u 100 para hacer un argumento numérico de 100, y luego
    pruebe C-g.
-   Ahora pruebe C-f.  Esto deberá mover sólo un carácter, ya que
+   Ahora pruebe C-f.  Esto deberá mover solo un carácter, ya que
    canceló el argumento con C-g.
 
 Si ha tecleado <ESC> por error, puede desecharlo con un C-g.
@@ -262,7 +262,7 @@ Si ha tecleado <ESC> por error, puede desecharlo con un C-g.
 * COMANDOS DESACTIVADOS
 -----------------------
 
-Algunos comandos de Emacs están "desactivados" de manera que los
+Algunos comandos de Emacs están «desactivados» de manera que los
 usuarios principiantes no puedan usarlos accidentalmente.
 
 Si teclea uno de los comandos desactivados, Emacs muestra un mensaje
@@ -271,7 +271,7 @@ continuar y ejecutar el comando.
 
 Si realmente quiere intentar el comando, teclee Espacio como repuesta
 a la pregunta.  Normalmente, si no quiere ejecutar el comando
-desactivado, conteste la pregunta con "n".
+desactivado, conteste la pregunta con «n».
 
 >> Escriba C-x C-l (que es un comando desactivado), a continuación
    escriba n para responder la pregunta.
@@ -280,7 +280,7 @@ desactivado, conteste la pregunta con "n".
 * VENTANAS
 ----------
 
-Emacs puede tener varias "ventanas", cada una mostrando su propio texto.
+Emacs puede tener varias «ventanas», cada una mostrando su propio texto.
 Explicaremos después cómo usar múltiples ventanas.  Ahora mismo
 queremos explicar cómo deshacerse de ventanas adicionales y volver a
 la edición básica en una ventana.  Es sencillo:
@@ -310,15 +310,15 @@ cuatro caracteres.
 
 Si quiere insertar un texto, basta con que lo teclee.  Los caracteres
 normales, como A, 7, *, etc. se insertan nada más teclearlos.  Teclee
-<Return> (la tecla "Enter" o "Intro") para insertar un carácter de
+<Return> (la tecla «Enter» o «Intro») para insertar un carácter de
 nueva línea.
 
 Para borrar el carácter que precede al cursor, oprima <DEL>. Es una
-tecla alargada, normalmente etiquetada como "Backspace" o "Del", o con
+tecla alargada, normalmente etiquetada como «Backspace» o «Del», o con
 una flecha apuntando a la izquierda; la misma que suele utilizar fuera
 de Emacs para borrar el último carácter introducido.
 
-Puede haber otra tecla llamada "Del" o "Supr" en otra parte, pero ésa
+Puede haber otra tecla llamada «Del» o «Supr» en otra parte, pero ésa
 no es <DEL>.
 
 >> Haga esto ahora: teclee unos pocos caracteres, después bórrelos
@@ -327,9 +327,9 @@ no es <DEL>.
    personal de él.
 
 Cuando una línea de texto se hace muy grande para una sola línea de la
-pantalla, la línea de texto "continúa" en una segunda línea en la
+pantalla, la línea de texto «continúa» en una segunda línea en la
 pantalla. Si está usando un entorno gráfico, se mostrarán pequeñas
-flechas curvas en las estrechas franjas vacías (los "márgenes" derecho
+flechas curvas en las estrechas franjas vacías (los «márgenes» derecho
 e izquierdo) a cada lado del área de texto, para indicar que la línea
 continúa. Si está utilizando una terminal, la continuación se señala
 mediante una barra invertida («\») en la última columna de la derecha.
@@ -357,13 +357,13 @@ circundante, puede además insertar espacio en blanco tras 
el carácter
 de fin de línea, de forma que, al seguir tecleando en la línea recién
 creada, el texto que tecleamos quede alineado con el de la línea
 anterior.  Este comportamiento (que la pulsación de una tecla no solo
-inserte el carácter correspondiente) se denomina "eléctrico".
+inserte el carácter correspondiente) se denomina «eléctrico».
 
->> Veamos un ejemplo de comportamiento "eléctrico" de <Return>
+>> Veamos un ejemplo de comportamiento «eléctrico» de <Return>
    Teclee <Return> al final de esta línea.
 
 Fíjese que, tras insertar el carácter de nueva línea, Emacs inserta
-también espacios para que el cursor se sitúe bajo la "T" de "Teclee".
+también espacios para que el cursor se sitúe bajo la «T» de «Teclee».
 
 Recuerde que a la mayoría de los comandos de Emacs se les puede dar un
 factor de repetición; esto incluye los caracteres de texto.  Repetir
@@ -375,7 +375,7 @@ Ya ha aprendido la manera más básica de teclear algo en 
Emacs y
 corregir errores.  Puede borrar por palabras o por líneas.  He aquí un
 resumen de las operaciones de borrado:
 
-       <DEL>           borra el carácter justo antes que el cursor
+       <DEL>           borra el carácter justo antes del cursor
        C-d             borra el siguiente carácter después del cursor
 
        M-<DEL>         Elimina la palabra inmediatamente antes del
@@ -389,29 +389,29 @@ Note que <DEL> y C-d, comparados con M-<DEL> y M-d, 
extienden el
 paralelismo iniciado por C-f y M-f (bien, <DEL> no es realmente una
 tecla de control, pero no nos preocuparemos de eso ahora).  C-k y M-k,
 en cierta forma, son como C-e y M-e, en que las líneas de unos
-corresponden a sentencias en los otros.
+corresponden a oraciones en los otros.
 
 También puede eliminar un segmento contiguo de texto con un método
 uniforme.  Muévase a un extremo de ese segmento de texto, y teclee C-@
-o C-SPC (cualquiera de los dos).  (SPC es la barra espaciadora.)
+o C-<SPC> (cualquiera de los dos).  (<SPC> es la barra espaciadora.)
 Luego, mueva el cursor al otro extremo del texto que desea eliminar.
 Al hacerlo, Emacs resaltará el texto situado entre el cursor y la
-posición en la que tecleó C-SPC.  Finalmente, teclee C-w.  Eso elimina
+posición en la que tecleó C-<SPC>.  Finalmente, teclee C-w.  Eso elimina
 todo el texto entre las dos posiciones.
 
 >> Mueva el cursor a la letra T del inicio del párrafo anterior.
->> Teclee C-SPC.  Emacs debe mostrar el mensaje "Mark set" en la parte
+>> Teclee C-<SPC>.  Emacs debe mostrar el mensaje «Mark set» en la parte
    de abajo de la pantalla.
->> Mueva el cursor a la x en "extremo", en la segunda línea del
+>> Mueva el cursor a la x en «extremo», en la segunda línea del
    párrafo.
 >> Teclee C-w.  Esto eliminará el texto que comienza desde la T, y
    termina justo antes de la x.
 
-La diferencia entre "eliminar" y "borrar" es que el texto "eliminado"
+La diferencia entre «eliminar» y «borrar» es que el texto «eliminado»
 puede ser reinsertado (en cualquier posición), mientras que las cosas
-"borradas" no pueden ser reinsertadas (sin embargo, es posible
+«borradas» no pueden ser reinsertadas (sin embargo, es posible
 deshacer el borrado; ver más abajo).  La reinserción de texto
-eliminado se llama "yanking" o "pegar".  Generalmente, los comandos
+eliminado se llama «yanking» o «pegar».  Generalmente, los comandos
 que pueden quitar mucho texto lo eliminan (para que pueda pegarlo de
 nuevo) mientras que los comandos que quitan solo un carácter, o solo
 líneas en blanco y espacios, borran (y por tanto no se puede pegar lo
@@ -426,17 +426,17 @@ borran.  Con un argumento, eliminan.
 Note que al teclear C-k una sola vez elimina el contenido de la línea,
 y un segundo C-k elimina la línea misma, y hace que todas las otras
 líneas se muevan hacia arriba.  C-k trata un argumento numérico
-especialmente: Elimina ese número de líneas y TAMBIÉN sus
+especialmente: elimina ese número de líneas y TAMBIÉN sus
 contenidos.  Esto no es una simple repetición.  C-u 2 C-k elimina dos
 líneas y sus nuevas líneas, tecleando C-k dos veces no hace esto.
 
-Reinsertar texto eliminado se denomina "yanking" o "pegar".  (Piense
+Reinsertar texto eliminado se denomina «yanking» o «pegar».  (Piense
 en ello como pegar de nuevo, o traer de vuelta, algún texto que le fue
 quitado.)  Puede pegar el texto eliminado, ya sea el lugar en que fue
 eliminado, o en otra parte del buffer, o hasta en un archivo
 diferente.  Puede pegar el texto varias veces, lo que hace varias
 copias de él.  Algunos editores se refieren a eliminar y reinsertar
-como "cortar" y "pegar" (consulte el Glosario en el manual de Emacs).
+como «cortar» y «pegar» (consulte el Glosario en el manual de Emacs).
 
 El comando para pegar es C-y.  Reinserta el último texto eliminado, en
 la posición actual del cursor.
@@ -460,7 +460,7 @@ Después de haber tecleado C-y para conseguir la eliminación 
más
 reciente, tecleando M-y reemplaza el texto pegado con la eliminación
 previa.  Tecleando M-y una y otra vez traerá las eliminaciones
 anteriores.  Cuando haya encontrado el texto que buscaba, no tiene que
-hacer nada para conservarlo.  Sólo siga con su edición, dejando el
+hacer nada para conservarlo.  Solo siga con su edición, dejando el
 texto pegado en donde está.
 
 Si teclea M-y suficientes veces, regresa al punto inicial (la
@@ -513,29 +513,29 @@ si puede pegarlo con C-y; no hay diferencia alguna para 
deshacer.
 
 Para que pueda hacer permanente el texto que edite, lo debe colocar en
 un archivo.  De otra manera, éste se perderá cuando cierre Emacs.
-Para poder poner su texto en un archivo, debe "encontrar" el archivo
-antes de ingresar el texto.  (Esto se llama también "visitar" el
+Para poder poner su texto en un archivo, debe «encontrar» el archivo
+antes de ingresar el texto.  (Esto se llama también «visitar» el
 archivo.)
 
 Encontrar un archivo significa que puede ver su contenido dentro de
 Emacs.  En cierta forma, es como si estuviera editando el archivo
 mismo.  Sin embargo los cambios que haga mediante Emacs no serán
-permanentes hasta que "guarde" el archivo.  Esto es para evitar dejar
+permanentes hasta que «guarde» el archivo.  Esto es para evitar dejar
 un archivo a medio cambiar en el sistema cuando no quiera.  Incluso
 cuando guarde, Emacs dejará el archivo original bajo un nombre
 cambiado en caso de que luego decida que sus cambios fueron un error.
 
 Si mira cerca del final de la pantalla podrá ver una línea que
-comienza con guiones, y empieza con " -:--- TUTORIAL.es" o algo así.
+comienza con guiones, y empieza con « U:--- TUTORIAL.es» o algo así.
 Esta parte de la pantalla normalmente muestra el nombre del archivo
 que está visitando.  En este momento está visitando su propia copia
-del tutorial de Emacs, que se llama "TUTORIAL.es".  Cuando encuentre
+del tutorial de Emacs, que se llama «TUTORIAL.es».  Cuando encuentre
 un archivo con Emacs, el nombre de ese archivo aparecerá en ese mismo
 punto.
 
-Una cosa especial acerca del comando para encontrar un archivo, es que
+Una cosa especial acerca del comando para encontrar un archivo es que
 tendrá que decir qué nombre de archivo desea.  Decimos que el comando
-"lee un argumento" (en este caso, el argumento es el nombre del
+«lee un argumento» (en este caso, el argumento es el nombre del
 archivo).  Después de teclear el comando:
 
        C-x C-f   Encontrar un archivo
@@ -565,19 +565,19 @@ comando
 
 Esto copia el texto dentro de Emacs al archivo.  La primera vez que
 haga esto, Emacs renombrará el archivo original con un nuevo nombre
-para que éste no se pierda.  El nuevo nombre se hace agregando "~" al
+para que éste no se pierda.  El nuevo nombre se hace agregando «~» al
 final del nombre del archivo original. Cuando guardar haya terminado,
 Emacs mostrará el nombre del archivo escrito.
 
 >> Teclee C-x C-s TUTORIAL.es <Return>
    Esto guardará el tutorial en un archivo llamado TUTORIAL.es, y
-   mostrará "Wrote ...TUTORIAL.es" al final de la pantalla.
+   mostrará «Wrote ...TUTORIAL.es» al final de la pantalla.
 
 Puede encontrar un archivo existente, para verlo o editarlo.  También
 puede hacerlo con un archivo que no exista.  Ésta es la forma de crear
 un archivo en Emacs: encuentre el archivo, que está inicialmente vacío,
 luego comience a insertar el texto para ese archivo.  Cuando invoque
-"guardar" el archivo, Emacs creará realmente el archivo con el texto
+«guardar» el archivo, Emacs creará realmente el archivo con el texto
 que ha insertado.  De ahí en adelante, puede considerar que está
 editando un archivo existente.
 
@@ -591,7 +591,7 @@ C-f.  De esta forma puede mantener un gran número de 
archivos dentro
 de Emacs.
 
 Emacs almacena cada texto del archivo dentro de un objeto llamado
-"buffer".  Al encontrar un archivo se crea un nuevo buffer dentro de
+«buffer».  Al encontrar un archivo se crea un nuevo buffer dentro de
 Emacs.  Para mirar la lista de los buffers que existen actualmente,
 teclee:
 
@@ -605,14 +605,14 @@ una ventana de Emacs es siempre parte de algún buffer.
 
 >> Teclee C-x 1 para deshacerse de la lista de buffers.
 
-Cuando tenga varios buffers, solo uno de ellos es "actual" en algún
+Cuando tenga varios buffers, solo uno de ellos es «actual» en algún
 momento.  Ese buffer es el que actualmente edita.  Si quiere editar
-otro buffer, necesita "cambiar" a él.  Si quiere cambiar a un buffer
+otro buffer, necesita «cambiar» a él.  Si quiere cambiar a un buffer
 que corresponde a un archivo, puede hacerlo visitando el archivo de
 nuevo con C-x C-f.  Pero existe una manera más rápida: use el comando
 C-x b.  En ese comando, necesita teclear el nombre de buffer.
 
->> Cree un archivo llamado "foo" tecleando C-x C-f foo <Return>.
+>> Cree un archivo llamado «foo» tecleando C-x C-f foo <Return>.
    Después teclee C-x b TUTORIAL.es <Return> para regresar a este
    tutorial.
 
@@ -622,12 +622,12 @@ esto no es así siempre.  La lista de buffers que hace con 
C-x C-b
 muestra el nombre de cada buffer y de su archivo correspondiente.
 
 Algunos buffers no corresponden a un archivo.  El buffer llamado
-"*Buffer List*", que contiene la lista de buffers que ha creado con
+«*Buffer List*», que contiene la lista de buffers que ha creado con
 C-x C-b, no tiene archivo.  Este buffer TUTORIAL.es al principio no
 tenía archivo, pero ahora sí, porque en la sección anterior tecleó
 C-x C-s y lo guardó en un archivo.
 
-El buffer llamado "*Messages*" tampoco tiene un archivo
+El buffer llamado «*Messages*» tampoco tiene un archivo
 correspondiente.  Este buffer contiene los mensajes que han aparecido
 en la línea de abajo durante su sesión de Emacs.
 
@@ -649,7 +649,7 @@ guardado.  Le pregunta, por cada buffer, si quiere 
guardarlo o no.
 
 >> Inserte una línea de texto, luego teclee C-x s.
    Debería preguntarle si desea guardar el buffer llamado TUTORIAL.es.
-   Conteste si a la pregunta tecleando "y".
+   Conteste «sí» a la pregunta tecleando «y».
 
 
 * EXTENDER EL CONJUNTO DE COMANDOS
@@ -675,14 +675,14 @@ Si está utilizando una pantalla gráfica, no necesita 
ningún comando
 especial para cambiar de Emacs a otra aplicación.  Puede hacerlo con
 el ratón, o mediante el gestor de ventanas.  Sin embargo, si está
 usando una terminal que solo puede mostrar una aplicación a la vez,
-tendrá que "suspender" Emacs para poder acceder a otras aplicaciones.
+tendrá que «suspender» Emacs para poder acceder a otras aplicaciones.
 
 C-z es el comando para salir de Emacs *temporalmente*: para que pueda
 regresar a la misma sesión de Emacs después.  Cuando Emacs está
-ejecutándose en una terminal, C-z "suspende" Emacs; esto es, se
+ejecutándose en una terminal, C-z «suspende» Emacs; esto es, se
 regresa al intérprete de comandos pero no se destruye Emacs.  En los
 intérpretes de comandos más comunes, puede reanudar Emacs con el
-comando "fg" o con "%emacs".
+comando «fg» o con «%emacs».
 
 El momento para usar C-x C-c es cuando está listo para salir del
 sistema.  Es además el paso correcto para salir de un Emacs invocado
@@ -706,7 +706,7 @@ con menos frecuencia, o únicamente en ciertos modos.  Un 
ejemplo es el
 comando replace-string, el cual substituye una cadena de caracteres
 por otra en todo el buffer.  Cuando teclea M-x, Emacs le pregunta al
 final de la pantalla con M-x y debe escribir el nombre del comando; en
-este caso "replace-string".  Solo teclee "repl s<TAB>" y Emacs
+este caso «replace-string».  Solo teclee «repl s<TAB>» y Emacs
 completará el nombre.  (<TAB> es la tecla del tabulador, que
 habitualmenté está situada sobre la tecla de bloquear mayúsculas o la
 de shift, en el lado izquierdo del teclado.)  Para aceptar el comando
@@ -721,7 +721,7 @@ Debe terminar cada argumento con <Return>.
    M-x repl s<Return>cambiado<Return>alterado<Return>.
 
    Note cómo ha cambiado la línea: ha substituido la palabra
-   "cambiado" por "alterado" en cada ocurrencia, después de la
+   «cambiado» por «alterado» en cada ocurrencia, después de la
    posición inicial del cursor.
 
 
@@ -730,10 +730,10 @@ Debe terminar cada argumento con <Return>.
 
 Si ha hecho cambios en un archivo, pero no los ha guardado, éstos
 podrían perderse si su computadora falla.  Para protegerlo de esto,
-Emacs periódicamente escribe un archivo "auto guardado" para cada
+Emacs escribe periódicamente un archivo «auto guardado» para cada
 archivo que está editando.  El nombre del archivo auto guardado tiene
 un # al principio y al final; por ejemplo, si su archivo se llama
-"hola.c", su archivo auto guardado es "#hola.c#".  Cuando guarda por
+«hola.c», su archivo auto guardado es «#hola.c#».  Cuando guarda por
 la vía normal, Emacs borra su archivo de auto guardado.
 
 Si la computadora falla, puede recuperar su edición de auto guardado
@@ -748,16 +748,16 @@ para seguir adelante y recuperar la información de auto 
guardado.
 
 Si Emacs ve que usted está tecleando comandos de multicaracteres
 lentamente, se los muestra al final de la pantalla en un área llamada
-"área de eco".  El área de eco contiene la línea final de la pantalla.
+«área de eco».  El área de eco contiene la línea final de la pantalla.
 
 
 * LÍNEA DE MODO
 ---------------
 
 La línea inmediatamente encima del área de eco recibe el nombre de
-"línea de modo" o "mode line".  La línea de modo dice algo así:
+«línea de modo» o «mode line».  La línea de modo dice algo así:
 
- -:**-  TUTORIAL.es       63% L749    (Fundamental)
+ U:**-  TUTORIAL.es       63% L749    (Fundamental)
 
 Esta línea da información útil acerca del estado de Emacs y del texto
 que está editando.
@@ -766,9 +766,9 @@ Ya sabe qué significa el nombre del archivo: es el archivo 
que usted
 ha encontrado.  NN% indica su posición actual en el texto; esto
 significa que NN por ciento del texto está encima de la parte superior
 de la pantalla.  Si el principio del archivo está en la pantalla, éste
-dirá "Top" en vez de " 0%".  Si el final del texto está en la
-pantalla, dirá "Bot".  Si está mirando un texto tan pequeño que cabe
-entero en la pantalla, el modo de línea dirá "All".
+dirá «Top» en vez de « 0%».  Si el final del texto está en la
+pantalla, dirá «Bot».  Si está mirando un texto tan pequeño que cabe
+entero en la pantalla, el modo de línea dirá «All».
 
 La L y los dígitos señalan la posición de otra forma: indican el
 número de línea actual del punto.
@@ -780,13 +780,13 @@ parte de la línea de modo no muestra asteriscos, solo 
guiones.
 La parte de la línea de modo dentro de los paréntesis es para
 indicarle en qué modo de edición está.  El modo por omisión es
 Fundamental, el cual está usando ahora.  Éste es un ejemplo de un
-"modo mayor".
+«modo mayor».
 
 Emacs tiene diferentes modos mayores.  Algunos están hechos para
 editar diferentes lenguajes y/o clases de texto, tales como modo de
 Lisp, modo de Texto, etc.  En cualquier momento uno y solo un modo
 mayor está activo, y su nombre siempre se puede encontrar en la línea
-de modo, justo en donde "Fundamental" está ahora.
+de modo, justo en donde «Fundamental» está ahora.
 
 Cada modo mayor hace que algunos comandos actúen diferente.  Por
 ejemplo, hay comandos para crear comentarios en un programa, y como
@@ -808,7 +808,7 @@ modo Fundamental, M-f y M-b trataban los apóstrofes como 
separadores
 de palabras.
 
 Los modos mayores normalmente hacen cambios sutiles como el anterior:
-la mayoría de comandos hacen "el mismo trabajo" en cada modo mayor,
+la mayoría de comandos hacen «el mismo trabajo» en cada modo mayor,
 pero funcionan de forma un poco diferente.
 
 Para ver la documentación del modo mayor actual, teclee C-h m.
@@ -840,11 +840,11 @@ Puede activar el modo Auto Fill al hacer M-x 
auto-fill-mode <Return>.
 Cuando el modo esté activado, puede desactivarlo nuevamente usando M-x
 auto-fill-mode <Return>.  Si el modo está desactivado, este comando lo
 activa, y si el modo está activado, este comando lo desactiva.
-Decimos que el comando "cambia el modo".
+Decimos que el comando «cambia el modo».
 
 >> teclee M-x auto-fill-mode <Return> ahora.  Luego inserte una línea
-   de "asdf " repetidas veces hasta que la vea dividida en dos líneas.
-   Debe intercalar espacios porque Auto Fill sólo rompe líneas en los
+   de «asdf » repetidas veces hasta que la vea dividida en dos líneas.
+   Debe intercalar espacios porque Auto Fill solo rompe líneas en los
    espacios.
 
 El margen está normalmente puesto en 70 caracteres, pero puede
@@ -867,48 +867,48 @@ ese párrafo.
 * BUSCAR
 --------
 
-Emacs puede hacer búsquedas de cadenas (una "cadena" es un grupo de
+Emacs puede hacer búsquedas de cadenas (una «cadena» es un grupo de
 caracteres contiguos) hacia adelante a través del texto o hacia atrás
 en el mismo.  La búsqueda de una cadena es un comando de movimiento de
 cursor; mueve el cursor al próximo lugar donde esa cadena aparece.
 
-El comando de búsqueda de Emacs es "incremental".  Esto significa que
+El comando de búsqueda de Emacs es «incremental».  Esto significa que
 la búsqueda ocurre mientras teclea la cadena para buscarla.
 
 El comando para iniciar una búsqueda es C-s para búsqueda hacia
 adelante, y C-r para la búsqueda hacia atrás.  ¡PERO ESPERE!  No los
 intente aún.
 
-Cuando teclee C-s verá que la cadena "I-search" aparece como una
+Cuando teclee C-s verá que la cadena «I-search» aparece como una
 petición en el área de eco.  Esto le indica que Emacs está en lo que
 se conoce como búsqueda incremental, esperando que teclee lo que
 quiere buscar.  <Return> termina una búsqueda.
 
 >> Ahora teclee C-s para comenzar la búsqueda.  LENTAMENTE, una letra
-   a la vez, teclee la palabra "cursor", haciendo pausa después de
+   a la vez, teclee la palabra «cursor», haciendo pausa después de
    cada carácter para notar lo que pasa con el cursor.
-   Ahora ha buscado "cursor", una vez.
+   Ahora ha buscado «cursor», una vez.
 >> Teclee C-s de nuevo, para buscar la siguiente ocurrencia de
-   "cursor".
+   «cursor».
 >> Ahora teclee <DEL> cuatro veces y vea como se mueve el cursor.
 >> Teclee <Return> para terminar la búsqueda.
 
-¿Vió lo que ocurrió?  Emacs, en una búsqueda incremental, trata de ir
+¿Vio lo que ocurrió?  Emacs, en una búsqueda incremental, trata de ir
 a la ocurrencia de la cadena que ha tecleado hasta el momento.  Para
-ir a la próxima ocurrencia de "cursor" solo teclee C-s de nuevo.  Si
+ir a la próxima ocurrencia de «cursor» solo teclee C-s de nuevo.  Si
 tal ocurrencia no existe, Emacs pita y le dice que la búsqueda actual
-está fallando ("failing").  C-g también termina la búsqueda.
+está fallando («failing»).  C-g también termina la búsqueda.
 
 Si se encuentra en medio de una búsqueda incremental y teclea <DEL>,
-la búsqueda "vuelve" a un punto anterior.  Si teclea <DEL> justo
+la búsqueda «vuelve» a un punto anterior.  Si teclea <DEL> justo
 después de teclear C-s para avanzar hasta la siguiente ocurrencia de
 la cadena buscada, el cursor retrocede a una ocurrencia previa.  Si no
 hay ocurrencias previas, <DEL> borra el último carácter de la cadena
-buscada.  Por ejemplo, suponga que ha tecleado "c", para buscar la
-primera ocurrencia de "c".  Ahora, si teclea "u", el cursor se moverá
-a la primera ocurrencia de "cu".  Ahora teclee <DEL>.  Esto borra la
-"u" de la cadena buscada, y el cursor vuelve a la primera ocurrencia
-de "c".
+buscada.  Por ejemplo, suponga que ha tecleado «c», para buscar la
+primera ocurrencia de «c».  Ahora, si teclea «u», el cursor se moverá
+a la primera ocurrencia de «cu».  Ahora teclee <DEL>.  Esto borra la
+«u» de la cadena buscada, y el cursor vuelve a la primera ocurrencia
+de «c».
 
 Si está en medio de una búsqueda y teclea un carácter control o meta
 (con algunas pocas excepciones: los caracteres que son especiales en
@@ -926,8 +926,8 @@ la búsqueda se invierte.
 
 Una de las características agradables de Emacs es que se puede mostrar
 más de una ventana en la pantalla al mismo tiempo.  (Note que Emacs
-usa el término "marcos", descrito en la siguiente sección, para
-referirse a lo que otras aplicaciones llaman "ventanas".  El manual de
+usa el término «marcos», descrito en la siguiente sección, para
+referirse a lo que otras aplicaciones llaman «ventanas».  El manual de
 Emacs contiene un Glosario de términos.)
 
 >> Mueva el cursor a esta línea y teclee C-l C-l.
@@ -939,7 +939,7 @@ Emacs contiene un Glosario de términos.)
 >> Teclee C-M-v para desplazar la ventana inferior.
    (Si no tiene una tecla META real, teclee ESC C-v.)
 
->> Teclee C-x o ("o" para "otro") para mover el cursor a la ventana
+>> Teclee C-x o («o» para «otro») para mover el cursor a la ventana
    inferior.
 >> Use C-v y M-v en la ventana inferior para desplazarla.
    Siga leyendo estas direcciones en la ventana superior.
@@ -949,7 +949,7 @@ Emacs contiene un Glosario de términos.)
    El cursor en la ventana superior está justo donde estaba antes.
 
 Puede continuar usando C-x o para cambiar entre las ventanas.  La
-"ventana seleccionada", donde tiene lugar casi toda la edición, es la
+«ventana seleccionada», donde tiene lugar casi toda la edición, es la
 que tiene un cursor muy visible que parpadea cuando usted no está
 tecleando.  Las otras ventanas tienen su propia posición del cursor;
 si está ejecutando Emacs en una pantalla gráfica, esos cursores se
@@ -962,7 +962,7 @@ C-M-v.
 
 C-M-v es un ejemplo de un carácter CONTROL-META.  Si tiene una tecla
 META (o Alt), puede teclear C-M-v pulsando a la vez CONTROL y META
-mientras teclea v.  No importa qué tecla "vaya primero", CONTROL o
+mientras teclea v.  No importa qué tecla «vaya primero», CONTROL o
 META, porque las dos teclas actúan modificando los caracteres que
 teclea.
 
@@ -975,8 +975,8 @@ sí mismo, no es una tecla modificadora.
    ventana de abajo.
 
 (Si hubiera tecleado C-x 1 en la ventana inferior, esto eliminaría la
-superior.  Piense en este comando como "mantener sólo una
-ventana--aquella en la cual estoy.")
+superior.  Piense en este comando como «mantener solo una
+ventana —aquella en la cual estoy—».)
 
 No tiene por qué mostrarse el mismo buffer en ambas ventanas.  Si usa
 C-x C-f para encontrar un archivo en una ventana, la otra ventana no
@@ -997,10 +997,10 @@ diferentes:
 * MÚLTIPLES MARCOS
 ------------------
 
-Emacs puede crear también múltiples "marcos".  Marco es como
-denominamos a un grupo de ventanas, junto con sus menus, barras de
+Emacs puede crear también múltiples «marcos».  Marco es como
+denominamos a un grupo de ventanas, junto con sus menús, barras de
 desplazamiento, áreas de eco, etc.  En entornos gráficos, lo que Emacs
-denomina "marco" es lo que otras aplicaciones llaman "ventana".  En
+denomina «marco» es lo que otras aplicaciones llaman «ventana».  En
 entornos gráficos, es posible mostrar varios marcos al mismo tiempo.
 En una terminal, solo se puede mostrar un marco a la vez.
 
@@ -1015,7 +1015,7 @@ El primer marco no tiene nada de especial.
 
 También puede destruir un marco mediante el método normal que ofrezca
 el entorno gráfico (a menudo, pinchando con el ratón en un botón
-etiquetado como "X" en alguna de las esquinas superiores del marco).
+etiquetado como «X» en alguna de las esquinas superiores del marco).
 Si al hacer eso destruye el último marco de Emacs, la aplicación
 termina.
 
@@ -1023,24 +1023,24 @@ termina.
 * NIVELES RECURSIVOS DE EDICIÓN
 --------------------------------
 
-Algunas veces entrará a lo que es llamado un "nivel recursivo de
-edición".  Esto se indica en la línea de modo mediante corchetes en la
+Algunas veces entrará a lo que es llamado un «nivel recursivo de
+edición».  Esto se indica en la línea de modo mediante corchetes en la
 línea de modo, rodeando los paréntesis del nombre del modo mayor.  Por
 ejemplo, probablemente vea [(Fundamental)] en vez de (Fundamental).
 
 Para salir de los niveles recursivos de edición, teclee ESC ESC ESC.
-Éste es un comando de "salida" para todo propósito.  También lo puede
+Éste es un comando de «salida» para todo propósito.  También lo puede
 usar para eliminar ventanas extras, y salir del minibuffer.
 
 >> Teclee M-x para entrar a un minibuffer; luego teclee ESC ESC ESC
    para salir.
 
-No se puede usar C-g para salir de los "niveles recursivos de
-edición".  Esto es porque C-g es usado para cancelar comandos y
+No se puede usar C-g para salir de los «niveles recursivos de
+edición».  Esto es porque C-g es usado para cancelar comandos y
 argumentos DENTRO del nivel recursivo de edición.
 
 
-* CONSEGUIR MAS AYUDA
+* CONSEGUIR MÁS AYUDA
 ---------------------
 
 En este tutorial hemos tratado de ofrecer suficiente información para
@@ -1048,8 +1048,8 @@ que empiece a usar Emacs.  Hay tanto disponible en Emacs 
que sería
 imposible explicar todo aquí.  Sin embargo, quizá desee aprender más
 sobre Emacs, ya que tiene muchas otras características útiles.  Emacs
 provee comandos para leer documentación acerca de los comandos de
-Emacs.  Todos estos comandos de "ayuda" comienzan con el carácter
-Control-h, que es llamado "el carácter de Ayuda (Help)".
+Emacs.  Todos estos comandos de «ayuda» comienzan con el carácter
+Control-h, que es llamado «el carácter de Ayuda (Help)».
 
 Para usar las funciones de ayuda, teclee el carácter C-h, y luego un
 carácter que especifica qué tipo de ayuda quiere.  Si está REALMENTE
@@ -1069,12 +1069,12 @@ una descripción muy breve del comando.
 
          C-p runs the command previous-line
 
-Esto le dice el "nombre de la función".  Ya que los nombres de las
+Esto le dice el «nombre de la función».  Ya que los nombres de las
 funciones se eligen para indicar lo que hace el comando, pueden servir
 como una breve documentación: suficiente para recordarle los comandos
 que ha aprendido.
 
-Los comandos de múltiples caracteres tales como C-x C-s y (sí no tiene
+Los comandos de múltiples caracteres tales como C-x C-s y (si no tiene
 las teclas META o EDIT o ALT) <ESC>v también están permitidos después
 de C-h c.
 
@@ -1113,7 +1113,7 @@ pregunte por ella.
 >> Teclee C-h a file <Return>.
 
 Esto muestra en otra ventana una lista de todos los comandos M-x con
-la palabra "file" en sus nombres.  Verá los comandos de caracteres
+la palabra «file» en sus nombres.  Verá los comandos de caracteres
 listados junto a los nombres de los comandos correspondientes (por
 ejemplo, C-x C-f junto a find-file).
 
@@ -1123,7 +1123,7 @@ ejemplo, C-x C-f junto a find-file).
 >> Teclee C-x 1 para borrar la ventana de ayuda.
 
    C-h i        Leer los manuales incluidos (alias Info).  Este comando
-                lo pone en un buffer especial llamado "*info*" donde
+                lo pone en un buffer especial llamado «*info*» donde
                 puede leer manuales de los paquetes instalados en su
                 sistema. Teclee m emacs <Return> para leer el manual
                 de Emacs.  Si nunca ha usado Info, teclee ? y Emacs y
@@ -1137,22 +1137,22 @@ ejemplo, C-x C-f junto a find-file).
 ---------------------
 
 Puede aprender más acerca de Emacs leyendo su manual, ya sea como
-libro o en el propio Emacs (use el menú Ayuda, "Help", o teclee C-h
+libro o en el propio Emacs (use el menú Ayuda, «Help», o teclee C-h
 r).  Dos características que pueden gustarle son la completación, que
 ahorra teclear, y dired, que simplifica el manejo de archivos.
 
 La completación es una manera de ahorrar teclear innecesariamente.
-Por ejemplo, si quiere cambiarse al buffer "*Messages*", puede teclear
+Por ejemplo, si quiere cambiarse al buffer «*Messages*», puede teclear
 C-x b *M<Tab> y Emacs encontrará el resto del nombre del buffer tan
 lejos como pueda determinar de lo que ya haya tecleado.  La
 completación también funciona con nombres de comandos y de archivos.
 La completación se describe en el Info del manual de Emacs en el nodo
-llamado "Completion".
+llamado «Completion».
 
 Dired le permite listar los archivos en un directorio (y opcionalmente
 sus subdirectorios), moverse alrededor de esa lista, visitar,
 renombrar, borrar y aparte de eso operar en los archivos.  Dired está
-descrito en el manual de Emacs en el nodo llamado "Dired".
+descrito en el manual de Emacs en el nodo llamado «Dired».
 
 El manual también describe otras características de Emacs.
 
@@ -1164,7 +1164,7 @@ Para salir permanentemente de Emacs use C-x C-c.
 
 Este tutorial intenta ser comprensible para todos los usuarios nuevos,
 así que si encuentra algo que no esté claro, no se quede parado
-culpándose a sí mismo: ¡Quéjese!
+culpándose a sí mismo: ¡quéjese!
 
 
 * COPIA
@@ -1200,7 +1200,7 @@ La versión en español ha sido actualizada por:
        Rafael Sepúlveda <address@hidden>
        Juanma Barranquero <address@hidden>
 
-Por favor, en caso de duda, sólo es válido el original en inglés de la
+Por favor, en caso de duda, solo es válido el original en inglés de la
 siguiente nota de derechos de reproducción (que puede encontrar en el
 archivo TUTORIAL).
 
@@ -1220,7 +1220,7 @@ Copyright (C) 1985, 1996, 1998, 2001-2014 Free Software 
Foundation, Inc.
 Las condiciones para copiar Emacs mismo son más complejas, pero con el
 mismo espíritu.  Por favor lea el archivo COPYING y luego distribuya
 copias de GNU Emacs a sus amigos.  ¡Ayude a erradicar el
-obstruccionismo del software ("propietariedad") usando, escribiendo, y
+obstruccionismo del software («propietariedad») usando, escribiendo, y
 compartiendo software libre!
 
 --- end of TUTORIAL.es ---
diff --git a/lib-src/ChangeLog b/lib-src/ChangeLog
index 600cc67..07a72ec 100644
--- a/lib-src/ChangeLog
+++ b/lib-src/ChangeLog
@@ -1,3 +1,11 @@
+2014-12-27  Eli Zaretskii  <address@hidden>
+
+       * Makefile.in (etags_libs, ebrowse${EXEEXT}, profile${EXEEXT})
+       (make-docfile${EXEEXT}, movemail${EXEEXT})
+       (update-game-score${EXEEXT}): Put $(NTLIB) before $(LOADLIBES),
+       since GCC sometimes calls stpcpy when it sees strcpy, under
+       optimization switches.
+
 2014-12-14  Paul Eggert  <address@hidden>
 
        * etags.c (analyze_regex): Rename from analyse_regex.
diff --git a/lib-src/Makefile.in b/lib-src/Makefile.in
index cae0898..13a7a05 100644
--- a/lib-src/Makefile.in
+++ b/lib-src/Makefile.in
@@ -321,7 +321,7 @@ regex.o: $(srcdir)/../src/regex.c $(srcdir)/../src/regex.h 
$(config_h)
 
 etags_deps = ${srcdir}/etags.c regex.o $(NTLIB) $(config_h)
 etags_cflags = -DEMACS_NAME="\"GNU Emacs\"" -DVERSION="\"${version}\"" -o $@
-etags_libs = regex.o $(LOADLIBES) $(NTLIB)
+etags_libs = regex.o $(NTLIB) $(LOADLIBES)
 
 etags${EXEEXT}: ${etags_deps}
        $(AM_V_CCLD)$(CC) ${ALL_CFLAGS} $(etags_cflags) $< $(etags_libs)
@@ -336,18 +336,18 @@ ctags${EXEEXT}: ${srcdir}/ctags.c ${etags_deps}
 ebrowse${EXEEXT}: ${srcdir}/ebrowse.c ${srcdir}/../lib/min-max.h $(NTLIB) \
                    $(config_h)
        $(AM_V_CCLD)$(CC) ${ALL_CFLAGS} -DVERSION="\"${version}\"" \
-         $< $(LOADLIBES) $(NTLIB) -o $@
+         $< $(NTLIB) $(LOADLIBES) -o $@
 
 profile${EXEEXT}: ${srcdir}/profile.c $(NTLIB) $(config_h)
        $(AM_V_CCLD)$(CC) ${ALL_CFLAGS} $< \
-         $(LOADLIBES) $(NTLIB) $(LIB_CLOCK_GETTIME) -o $@
+         $(NTLIB) $(LOADLIBES) $(LIB_CLOCK_GETTIME) -o $@
 
 make-docfile${EXEEXT}: ${srcdir}/make-docfile.c $(NTLIB) $(config_h)
-       $(AM_V_CCLD)$(CC) ${ALL_CFLAGS} $< $(LOADLIBES) $(NTLIB) -o $@
+       $(AM_V_CCLD)$(CC) ${ALL_CFLAGS} $< $(NTLIB) $(LOADLIBES) -o $@
 
 movemail${EXEEXT}: ${srcdir}/movemail.c pop.o $(NTLIB) $(config_h)
        $(AM_V_CCLD)$(CC) ${ALL_CFLAGS} ${MOVE_FLAGS} $< pop.o \
-         $(LOADLIBES) $(NTLIB) $(LIBS_MOVE) -o $@
+         $(NTLIB) $(LOADLIBES) $(LIBS_MOVE) -o $@
 
 pop.o: ${srcdir}/pop.c ${srcdir}/pop.h ${srcdir}/../lib/min-max.h $(config_h)
        $(AM_V_CC)$(CC) -c ${CPP_CFLAGS} ${MOVE_FLAGS} $<
@@ -378,7 +378,7 @@ hexl${EXEEXT}: ${srcdir}/hexl.c $(NTLIB) $(config_h)
 update-game-score${EXEEXT}: ${srcdir}/update-game-score.c $(NTLIB) $(config_h)
        $(AM_V_CCLD)$(CC) ${ALL_CFLAGS} \
          -DHAVE_SHARED_GAME_DIR="\"$(gamedir)\"" \
-         $< $(LOADLIBES) $(NTLIB) -o $@
+         $< $(NTLIB) $(LOADLIBES) -o $@
 
 emacsclient.res: ../nt/emacsclient.rc $(NTINC)/../icons/emacs.ico
        $(WINDRES) -O coff --include-dir=$(NTINC)/.. -o $@ $<
diff --git a/lisp/ChangeLog b/lisp/ChangeLog
index 4c6b23d..4203e05 100644
--- a/lisp/ChangeLog
+++ b/lisp/ChangeLog
@@ -1,3 +1,324 @@
+2014-12-30  Paul Eggert  <address@hidden>
+
+       * Makefile.in (semantic): Simplify.
+
+2014-12-30  Juri Linkov  <address@hidden>
+
+       * net/eww.el (eww-isearch-next-buffer): New function.
+       (eww-mode): Set multi-isearch-next-buffer-function to it.
+
+2014-12-30  Dmitry Gutov  <address@hidden>
+
+       * progmodes/xref.el (xref-find-definitions): Mention "no
+       identifier at point" case in the docstring.
+
+       * menu-bar.el (menu-bar-goto-uses-etags-p): New function.
+       (menu-bar-goto-menu): Use it to show or hide the `set-tags-name'
+       and `separator-tag-file' items.
+
+2014-12-29  Paul Eggert  <address@hidden>
+
+       * obsolete/pc-select.el (pc-selection-mode): Use system-type.
+       This is instead of system-name, which is both wrong here and obsolete.
+
+2014-12-29  Dmitry Gutov  <address@hidden>
+
+       * menu-bar.el (menu-bar-next-tag-other-window)
+       (menu-bar-next-tag): Remove.
+
+2014-12-29  K. Handa  <address@hidden>
+
+       * international/mule.el (make-translation-table-from-alist):
+       Accept nil or zero-length vector for FROM and TO.
+
+2014-12-29  Lars Ingebrigtsen  <address@hidden>
+
+       * net/eww.el (eww-mode): Truncate overlong lines for prettier
+       display when resizing.
+
+       * net/shr.el (shr-width): Default to using the window width when
+       rendering.
+
+2014-12-29  Dmitry Gutov  <address@hidden>
+
+       Unbreak jumping to an alias's definition.
+
+       * emacs-lisp/find-func.el (find-function-library): Return a pair
+       (ORIG-FUNCTION . LIBRARY) instead of just its second element.
+       (find-function-noselect): Use it.
+
+       * progmodes/elisp-mode.el (elisp--xref-identifier-file): Rename to
+       `elisp--xref-identifier-location', incorporate logic from
+       `elisp--xref-find-definitions', use the changed
+       `find-function-library' return value.
+
+2014-12-29  Juri Linkov  <address@hidden>
+
+       * comint.el (comint-history-isearch-message): Use field-beginning
+       instead of comint-line-beginning-position - that's more fixes for
+       http://lists.gnu.org/archive/html/emacs-devel/2014-12/msg00305.html
+       (comint-history-isearch-message): Fix args of isearch-message-prefix.
+
+2014-12-29  Juri Linkov  <address@hidden>
+
+       * vc/vc-dir.el (vc-dir-display-file): New command (bug#19450).
+       (vc-dir-mode-map): Bind it to "\C-o".
+       (vc-dir-menu-map): Add it to menu.
+
+2014-12-29  Dmitry Gutov  <address@hidden>
+
+       * progmodes/etags.el (find-tag-other-window)
+       (find-tag-other-frame, find-tag-regexp, tags-loop-continue)
+       (tags-apropos): Declare obsolete.
+
+       * menu-bar.el (menu-bar-goto-menu): Replace all but one etags item
+       with xref ones.
+
+2014-12-28  Eli Zaretskii  <address@hidden>
+
+       * international/mule.el (define-coding-system): Fix typos in the
+       doc string.
+
+2014-12-28  Kenichi Handa  <address@hidden>
+
+       * international/mule.el (define-coding-system): Improve the doc
+       string.
+
+2014-12-28  Ivan Shmakov  <address@hidden>
+
+       * net/shr.el (shr-tag-table): Fix handling of tbody/header/footer
+       elements in tables (bug#19444).
+
+       * net/eww.el (eww-handle-link): Fix typo in "up" rel handling
+       (bug#19445).
+
+2014-12-28  Juri Linkov  <address@hidden>
+
+       * vc/compare-w.el: Require diff-mode for diff faces.
+       (compare-windows-removed, compare-windows-added): New faces
+       inheriting from diff faces.
+       (compare-windows): Define obsolete face alias.
+       (compare-windows-highlight): Replace face `compare-windows' with
+       new faces `compare-windows-added' and `compare-windows-removed'
+       (bug#19451).
+       (compare-windows-get-recent-window): Signal an error when
+       no other window is found (bug#19170).
+
+2014-12-27  Dmitry Gutov  <address@hidden>
+
+       * progmodes/elisp-mode.el (elisp--xref-identifier-file):
+       Skip features that have no sources.
+
+       * simple.el (execute-extended-command):
+       When `suggest-key-bindings' is nil, don't.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       python.el: Native readline completion.
+
+       * progmodes/python.el 
(python-shell-completion-native-disabled-interpreters)
+       (python-shell-completion-native-enable)
+       (python-shell-completion-native-output-timeout): New defcustoms.
+       (python-shell-completion-native-interpreter-disabled-p)
+       (python-shell-completion-native-try)
+       (python-shell-completion-native-setup)
+       (python-shell-completion-native-turn-off)
+       (python-shell-completion-native-turn-on)
+       (python-shell-completion-native-turn-on-maybe)
+       (python-shell-completion-native-turn-on-maybe-with-msg)
+       (python-shell-completion-native-toggle): New functions.
+       (python-shell-completion-native-get-completions): New function.
+       (python-shell-completion-at-point): Use it.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       python.el: Enhance shell user interaction and deprecate
+       python-shell-get-or-create-process.
+
+       * progmodes/python.el
+       (python-shell-get-process-or-error): New function.
+       (python-shell-with-shell-buffer): Use it.
+       (python-shell-send-string, python-shell-send-region)
+       (python-shell-send-buffer, python-shell-send-defun)
+       (python-shell-send-file, python-shell-switch-to-shell): Use it.
+       Add argument MSG to display user-friendly message when no process
+       is running.
+       (python-shell-switch-to-shell): Call pop-to-buffer with NORECORD.
+       (python-shell-make-comint): Rename argument SHOW from POP.  Use
+       display-buffer instead of pop-to-buffer.
+       (run-python): Doc fix.  Return process.
+       (python-shell-get-or-create-process): Make obsolete.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       * progmodes/python.el (python-shell-buffer-substring): Handle
+       cornercase when region sent starts at point-min.
+
+2014-12-27  Eli Zaretskii  <address@hidden>
+
+       * language/misc-lang.el (composition-function-table): Add Syriac
+       characters and also ZWJ/ZWNJ.  See
+       http://lists.gnu.org/archive/html/help-gnu-emacs/2014-12/msg00248.html
+       for the details.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       python.el: Fix message when sending region.
+
+       * progmodes/python.el (python-shell-send-region): Rename argument
+       send-main from nomain.  Fix message.
+       (python-shell-send-buffer): Rename argument send-main from arg.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       python.el: Cleanup temp files even with eval errors.
+
+       * progmodes/python.el (python-shell-send-file): Make file-name
+       mandatory.  Fix temp file removal in the majority of cases.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       python.el: Handle file encoding for shell.
+
+       * progmodes/python.el (python-rx-constituents): Add coding-cookie.
+       (python-shell--save-temp-file): Write file with proper encoding.
+       (python-shell-buffer-substring): Add coding cookie for detected
+       encoding to generated content.  Fix blank lines when removing
+       if-name-main block.
+       (python-shell-send-file): Handle file encoding.
+       (python-info-encoding-from-cookie)
+       (python-info-encoding): New functions.
+
+2014-12-27  Michael Albinus  <address@hidden>
+
+       * net/tramp-sh.el (tramp-do-copy-or-rename-file-out-of-band):
+       Use `tramp-rsh-end-of-line', it ought to be more robust.
+
+2014-12-27  Stefan Monnier  <address@hidden>
+
+       * progmodes/js.el (js-syntax-propertize): "return" can't be divided
+       (bug#19397).
+
+2014-12-27  Michael Albinus  <address@hidden>
+
+       * net/tramp.el (tramp-read-passwd): Ignore errors from `auth-source-*'.
+
+       * net/tramp-sh.el (tramp-do-copy-or-rename-file-out-of-band): Use "\n"
+       as end-of-line delimeter for passwords, when running on MS Windows.
+
+2014-12-27  Stefan Monnier  <address@hidden>
+
+       * progmodes/sh-script.el (sh-set-shell): Don't change the global value
+       of indent-line-function (bug#19433).
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       Fix line numbers on Python shell.
+       * progmodes/python.el (python-shell--save-temp-file): Do not
+       append coding cookie.
+       (python-shell-send-string): Generalize for
+       python-shell-send-region.
+       (python--use-fake-loc): Delete var.
+       (python-shell-buffer-substring): Cleanup fake-loc logic.
+       (python-shell-send-region): Remove fake-loc logic, simplify.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       * progmodes/python.el (python-indent-post-self-insert-function):
+       Make colon to re-indent only for dedenters, handling
+       multiline-statements gracefully.
+
+2014-12-27  Michael Albinus  <address@hidden>
+
+       * net/tramp.el (tramp-handle-insert-file-contents):
+       Set `find-file-not-found-functions' in case of errors.  (Bug#18623)
+
+2014-12-27  Michael Albinus  <address@hidden>
+
+       * net/tramp-sh.el (tramp-send-command-and-read): New optional
+       arg MARKER.
+       (tramp-get-remote-path): Use it.
+
+2014-12-27  Stefan Monnier  <address@hidden>
+
+       * lisp/subr.el (redisplay-dont-pause): Mark as obsolete.
+
+2014-12-27  Michael Albinus  <address@hidden>
+
+       * net/tramp.el (tramp-error-with-buffer): Call `message' properly.
+       (tramp-accept-process-output): Use nil as argument for
+       `accept-process-output', when there is a gateway prepended.
+
+       * net/tramp-gw.el (tramp-gw-open-connection): Suppress traces in
+       wrong debug buffer.
+       (tramp-gw-open-connection): Set process coding system 'binary.
+       (tramp-gw-open-network-stream): Handle HTTP error 403.
+
+       * net/tramp-sh.el (tramp-compute-multi-hops): Suppress traces in
+       wrong debug buffer.
+       (tramp-maybe-open-connection): Set connection property "gateway".
+
+2014-12-27  Stefan Monnier  <address@hidden>
+
+       * subr.el (sit-for): Tweak docstring (bug#19381).
+
+2014-12-27  Dmitry Gutov  <address@hidden>
+
+       * vc/vc-git.el (vc-git-after-dir-status-stage): Move `up-to-date'
+       stage to after `diff-index' (bug#19386).
+
+2014-12-27  João Távora  <address@hidden>
+
+       * textmodes/tex-mode.el (tex-insert-quote): Consider and respect
+       `electric-pair-mode' (bug#19356).
+
+2014-12-27  Dmitry Gutov  <address@hidden>
+
+       elisp-xref-find: Don't create buffers eagerly.
+
+       * progmodes/elisp-mode.el (elisp--identifier-location): Fold back
+       into `elisp--company-location'.
+       (elisp--identifier-completion-table): Rename to
+       `elisp--identifier-completion-table', and do not include just any
+       symbols with a property list.
+       (elisp-completion-at-point): Revert the 2014-12-25 change.
+       (elisp--xref-identifier-file): New function.
+       (elisp--xref-find-definitions): Use it.
+
+       * emacs-lisp/find-func.el (find-function-library): New function,
+       extracted from `find-function-noselect'.
+
+       * progmodes/xref.el (xref-elisp-location): New class.
+       (xref-make-elisp-location): New function.
+       (xref-location-marker): New implementation.
+
+2014-12-27  Juri Linkov  <address@hidden>
+
+       * minibuffer.el (minibuffer-completion-help):
+       Use shrink-window-if-larger-than-buffer in window-height
+       when temp-buffer-resize-mode is nil.
+
+       * window.el (with-displayed-buffer-window): Remove window-height
+       from the action alist in the temp-buffer-window-show call
+       when window-height is handled explicitly afterwards (bug#19355).
+
+2014-12-27  Juri Linkov  <address@hidden>
+
+       Support subdirectories when saving places in dired.
+       * saveplace.el (toggle-save-place, save-place-to-alist)
+       (save-places-to-alist, save-place-dired-hook):
+       Use dired-current-directory instead of dired-directory (bug#19436).
+       (save-place-dired-hook): Add check for alist to make the new
+       format future-proof to allow other possible formats.
+
+2014-12-26  Fabián Ezequiel Gallina  <address@hidden>
+
+       python.el: Generate clearer shell buffer names.
+
+       * progmodes/python.el (python-shell-get-process-name)
+       (python-shell-internal-get-process-name): Use `buffer-name`.
+       (python-shell-internal-get-or-create-process): Simplify.
+
 2014-12-26  Dmitry Gutov  <address@hidden>
 
        Add basic xref apropos implementation to elisp-mode.
@@ -9,6 +330,11 @@
 
        * progmodes/xref.el (xref--show-xrefs): Use `user-error'.
 
+2014-12-25  Filipp Gunbin  <address@hidden>
+
+       * dired-aux.el (dired-maybe-insert-subdir): Make
+       dired-maybe-insert-subdir always skip trivial files.
+
 2014-12-25  Helmut Eller  <address@hidden>
             Dmitry Gutov  <address@hidden>
 
@@ -4645,12 +4971,6 @@
 
 2014-07-28  Fabián Ezequiel Gallina  <address@hidden>
 
-       Prevent Python process shell buffer to pop twice.
-       * progmodes/python.el (python-shell-switch-to-shell): Do not call
-       pop-to-buffer.
-
-2014-07-28  Fabián Ezequiel Gallina  <address@hidden>
-
        * progmodes/python.el
        (python-shell-with-shell-buffer): New macro.
        (python-shell-font-lock-get-or-create-buffer)
diff --git a/lisp/Makefile.in b/lisp/Makefile.in
index f22ca69..ba2a229 100644
--- a/lisp/Makefile.in
+++ b/lisp/Makefile.in
@@ -325,13 +325,8 @@ compile-clean:
 leim:
        $(MAKE) -C ../leim all EMACS="$(EMACS)"
 
-# FIXME.  Yuck.
 semantic:
-       case ${EMACS} in \
-         .*) EMACS="../${EMACS}" ;; \
-          *) EMACS="${EMACS}" ;; \
-       esac; \
-       $(MAKE) -C ../admin/grammars all EMACS="$${EMACS}"
+       $(MAKE) -C ../admin/grammars all EMACS="$(EMACS:.%=../.%)"
 
 # Compile all Lisp files, but don't recompile those that are up to
 # date.  Some .el files don't get compiled because they set the
diff --git a/lisp/comint.el b/lisp/comint.el
index 3085052..4acaa30 100644
--- a/lisp/comint.el
+++ b/lisp/comint.el
@@ -1532,14 +1532,20 @@ the function `isearch-message'."
     ;; the initial comint prompt.
     (if (overlayp comint-history-isearch-message-overlay)
        (move-overlay comint-history-isearch-message-overlay
-                     (save-excursion (forward-line 0) (point))
-                      (comint-line-beginning-position))
+                     (save-excursion
+                       (goto-char (field-beginning))
+                       (forward-line 0)
+                       (point))
+                      (field-beginning))
       (setq comint-history-isearch-message-overlay
-           (make-overlay (save-excursion (forward-line 0) (point))
-                          (comint-line-beginning-position)))
+           (make-overlay (save-excursion
+                           (goto-char (field-beginning))
+                           (forward-line 0)
+                           (point))
+                          (field-beginning)))
       (overlay-put comint-history-isearch-message-overlay 'evaporate t))
     (overlay-put comint-history-isearch-message-overlay
-                'display (isearch-message-prefix c-q-hack ellipsis))
+                'display (isearch-message-prefix ellipsis 
isearch-nonincremental))
     (if (and comint-input-ring-index (not ellipsis))
        ;; Display the current history index.
        (message "History item: %d" (1+ comint-input-ring-index))
diff --git a/lisp/desktop.el b/lisp/desktop.el
index 75bced4..6ca396a 100644
--- a/lisp/desktop.el
+++ b/lisp/desktop.el
@@ -940,7 +940,7 @@ Frames with a non-nil `desktop-dont-save' parameter are not 
saved."
        (and desktop-restore-frames
             (frameset-save nil
                            :app desktop--app-id
-                           :name (concat user-login-name "@" system-name)
+                           :name (concat user-login-name "@" (system-name))
                            :predicate #'desktop--check-dont-save))))
 
 ;;;###autoload
diff --git a/lisp/dired.el b/lisp/dired.el
index 909ba22..7f7251f 100644
--- a/lisp/dired.el
+++ b/lisp/dired.el
@@ -3884,7 +3884,7 @@ Ask means pop up a menu for the user to select one of 
copy, move or link."
 
 ;;; Start of automatically extracted autoloads.
 
-;;;### (autoloads nil "dired-aux" "dired-aux.el" 
"1448837b5f3e2b9ad63f723361f1e32e")
+;;;### (autoloads nil "dired-aux" "dired-aux.el" 
"73269f48e7fe2fd0ac580fd69252b33a")
 ;;; Generated autoloads from dired-aux.el
 
 (autoload 'dired-diff "dired-aux" "\
diff --git a/lisp/dnd.el b/lisp/dnd.el
index 73b531d..3fda471 100644
--- a/lisp/dnd.el
+++ b/lisp/dnd.el
@@ -122,17 +122,18 @@ Return nil if URI is not a local file."
 
   ;; The hostname may be our hostname, in that case, convert to a local
   ;; file.  Otherwise return nil.  TODO:  How about an IP-address as hostname?
-  (let ((hostname (when (string-match "^file://\\([^/]*\\)" uri)
+  (let ((sysname (system-name)))
+    (let ((hostname (when (string-match "^file://\\([^/]*\\)" uri)
                      (downcase (match-string 1 uri))))
-       (system-name-no-dot
-        (downcase (if (string-match "^[^\\.]+" system-name)
-                      (match-string 0 system-name)
-                    system-name))))
-    (when (and hostname
-            (or (string-equal "localhost" hostname)
-                (string-equal (downcase system-name) hostname)
-                (string-equal system-name-no-dot hostname)))
-       (concat "file://" (substring uri (+ 7 (length hostname)))))))
+         (sysname-no-dot
+          (downcase (if (string-match "^[^\\.]+" sysname)
+                        (match-string 0 sysname)
+                      sysname))))
+      (when (and hostname
+                (or (string-equal "localhost" hostname)
+                    (string-equal (downcase sysname) hostname)
+                    (string-equal sysname-no-dot hostname)))
+       (concat "file://" (substring uri (+ 7 (length hostname))))))))
 
 (defsubst dnd-unescape-uri (uri)
   (replace-regexp-in-string
diff --git a/lisp/emacs-lisp/find-func.el b/lisp/emacs-lisp/find-func.el
index c372117..3131be0 100644
--- a/lisp/emacs-lisp/find-func.el
+++ b/lisp/emacs-lisp/find-func.el
@@ -311,6 +311,45 @@ The search is done in the source for library LIBRARY."
                  (cons (current-buffer) (point)))
              (cons (current-buffer) nil))))))))
 
+(defun find-function-library (function &optional lisp-only verbose)
+  "Return the pair (ORIG-FUNCTION . LIBRARY) for FUNCTION.
+
+ORIG-FUNCTION is the original name, after removing all advice and
+resolving aliases.  LIBRARY is an absolute file name, a relative
+file name inside the C sources directory, or a name of an
+autoloaded feature.
+
+If ORIG-FUNCTION is a built-in function and LISP-ONLY is non-nil,
+signal an error.
+
+If VERBOSE is non-nil, and FUNCTION is an alias, display a
+message about the whole chain of aliases."
+  (let ((def (symbol-function (find-function-advised-original function)))
+        aliases)
+    ;; FIXME for completeness, it might be nice to print something like:
+    ;; foo (which is advised), which is an alias for bar (which is advised).
+    (while (symbolp def)
+      (or (eq def function)
+          (not verbose)
+          (if aliases
+              (setq aliases (concat aliases
+                                    (format ", which is an alias for `%s'"
+                                            (symbol-name def))))
+            (setq aliases (format "`%s' is an alias for `%s'"
+                                  function (symbol-name def)))))
+      (setq function (symbol-function (find-function-advised-original 
function))
+            def (symbol-function (find-function-advised-original function))))
+    (if aliases
+        (message "%s" aliases))
+    (cons function
+          (cond
+           ((autoloadp def) (nth 1 def))
+           ((subrp def)
+            (if lisp-only
+                (error "%s is a built-in function" function))
+            (help-C-file-name def 'subr))
+           ((symbol-file function 'defun))))))
+
 ;;;###autoload
 (defun find-function-noselect (function &optional lisp-only)
   "Return a pair (BUFFER . POINT) pointing to the definition of FUNCTION.
@@ -329,30 +368,8 @@ searched for in `find-function-source-path' if non-nil, 
otherwise
 in `load-path'."
   (if (not function)
     (error "You didn't specify a function"))
-  (let ((def (symbol-function (find-function-advised-original function)))
-       aliases)
-    ;; FIXME for completeness, it might be nice to print something like:
-    ;; foo (which is advised), which is an alias for bar (which is advised).
-    (while (symbolp def)
-      (or (eq def function)
-         (if aliases
-             (setq aliases (concat aliases
-                                   (format ", which is an alias for `%s'"
-                                           (symbol-name def))))
-           (setq aliases (format "`%s' is an alias for `%s'"
-                                 function (symbol-name def)))))
-      (setq function (symbol-function (find-function-advised-original 
function))
-           def (symbol-function (find-function-advised-original function))))
-    (if aliases
-       (message "%s" aliases))
-    (let ((library
-          (cond ((autoloadp def) (nth 1 def))
-                ((subrp def)
-                 (if lisp-only
-                     (error "%s is a built-in function" function))
-                 (help-C-file-name def 'subr))
-                ((symbol-file function 'defun)))))
-      (find-function-search-for-symbol function nil library))))
+  (let ((func-lib (find-function-library function lisp-only t)))
+    (find-function-search-for-symbol (car func-lib) nil (cdr func-lib))))
 
 (defun find-function-read (&optional type)
   "Read and return an interned symbol, defaulting to the one near point.
diff --git a/lisp/gnus/ChangeLog b/lisp/gnus/ChangeLog
index 6f0ea0f..0007b15 100644
--- a/lisp/gnus/ChangeLog
+++ b/lisp/gnus/ChangeLog
@@ -1,3 +1,8 @@
+2014-12-29  Lars Ingebrigtsen  <address@hidden>
+
+       * mm-decode.el (mm-shr): Bind `shr-width' to `fill-column' so that
+       lines don't get overlong when responding.
+
 2014-12-18  Paul Eggert  <address@hidden>
 
        * registry.el (registry-db): Set default slot later.
diff --git a/lisp/gnus/gnus-cloud.el b/lisp/gnus/gnus-cloud.el
index ec016ee..a42bcc0 100644
--- a/lisp/gnus/gnus-cloud.el
+++ b/lisp/gnus/gnus-cloud.el
@@ -329,6 +329,15 @@
 (defun gnus-cloud-server-p (server)
   (member server gnus-cloud-covered-servers))
 
+(defun gnus-cloud-collect-full-newsrc ()
+  (let ((infos nil))
+    (dolist (info (cdr gnus-newsrc-alist))
+      (when (gnus-cloud-server-p
+            (gnus-method-to-server
+             (gnus-find-method-for-group (gnus-info-group info))))
+       (push info infos)))
+    ))
+
 (provide 'gnus-cloud)
 
 ;;; gnus-cloud.el ends here
diff --git a/lisp/gnus/message.el b/lisp/gnus/message.el
index d58a292..ee5d824 100644
--- a/lisp/gnus/message.el
+++ b/lisp/gnus/message.el
@@ -5849,7 +5849,7 @@ give as trustworthy answer as possible."
 
 (defun message-make-fqdn ()
   "Return user's fully qualified domain name."
-  (let* ((system-name (system-name))
+  (let* ((sysname (system-name))
         (user-mail (message-user-mail-address))
         (user-domain
          (if (and user-mail
@@ -5863,10 +5863,10 @@ give as trustworthy answer as possible."
           (not (string-match message-bogus-system-names message-user-fqdn)))
       ;; `message-user-fqdn' seems to be valid
       message-user-fqdn)
-     ((and (string-match message-valid-fqdn-regexp system-name)
-          (not (string-match message-bogus-system-names system-name)))
+     ((and (string-match message-valid-fqdn-regexp sysname)
+          (not (string-match message-bogus-system-names sysname)))
       ;; `system-name' returned the right result.
-      system-name)
+      sysname)
      ;; Try `mail-host-address'.
      ((and (boundp 'mail-host-address)
           (stringp mail-host-address)
@@ -5881,7 +5881,7 @@ give as trustworthy answer as possible."
       user-domain)
      ;; Default to this bogus thing.
      (t
-      (concat system-name
+      (concat sysname
              ".i-did-not-set--mail-host-address--so-tickle-me")))))
 
 (defun message-make-domain ()
diff --git a/lisp/gnus/mm-decode.el b/lisp/gnus/mm-decode.el
index f5b4d7c..3913ecc 100644
--- a/lisp/gnus/mm-decode.el
+++ b/lisp/gnus/mm-decode.el
@@ -1814,6 +1814,7 @@ If RECURSIVE, search recursively."
   ;; Require since we bind its variables.
   (require 'shr)
   (let ((article-buffer (current-buffer))
+       (shr-width fill-column)
        (shr-content-function (lambda (id)
                                (let ((handle (mm-get-content-id id)))
                                  (when handle
diff --git a/lisp/gnus/nnvirtual.el b/lisp/gnus/nnvirtual.el
index f67943a..61bf556 100644
--- a/lisp/gnus/nnvirtual.el
+++ b/lisp/gnus/nnvirtual.el
@@ -99,7 +99,7 @@ component group will show up when you enter the virtual 
group.")
        (let ((vbuf (nnheader-set-temp-buffer
                     (get-buffer-create " *virtual headers*")))
              (carticles (nnvirtual-partition-sequence articles))
-             (system-name (system-name))
+             (sysname (system-name))
              cgroup carticle article result prefix)
          (while carticles
            (setq cgroup (caar carticles))
@@ -151,7 +151,7 @@ component group will show up when you enter the virtual 
group.")
                  ;; and clean up the xrefs.
                  (princ article nntp-server-buffer)
                  (nnvirtual-update-xref-header cgroup carticle
-                                               prefix system-name)
+                                               prefix sysname)
                  (forward-line 1))
                )
 
@@ -378,7 +378,7 @@ component group will show up when you enter the virtual 
group.")
       (mapc 'nnheader-insert-nov headers))))
 
 
-(defun nnvirtual-update-xref-header (group article prefix system-name)
+(defun nnvirtual-update-xref-header (group article prefix sysname)
   "Edit current NOV header in current buffer to have an xref to the component 
group, and also server prefix any existing xref lines."
   ;; Move to beginning of Xref field, creating a slot if needed.
   (beginning-of-line)
@@ -393,7 +393,7 @@ component group will show up when you enter the virtual 
group.")
     (forward-char -1)
     (delete-char 1))
 
-  (insert "Xref: " system-name " " group ":")
+  (insert "Xref: " sysname " " group ":")
   (princ article (current-buffer))
   (insert " ")
 
diff --git a/lisp/international/mule.el b/lisp/international/mule.el
index bb8111e..392ecff 100644
--- a/lisp/international/mule.el
+++ b/lisp/international/mule.el
@@ -593,6 +593,29 @@ as the single-shift area.")
 The remaining arguments must come in pairs ATTRIBUTE VALUE.  ATTRIBUTE
 may be any symbol.
 
+A coding system specifies a rule to decode (i.e. to convert a
+byte sequence to a character sequence) and a rule to encode (the
+opposite of decoding).
+
+The decoding is done by at most 3 steps; the first is to convert
+a byte sequence to a character sequence by one of Emacs'
+internal routines specified by `:coding-type' attribute.  The
+optional second step is to convert the character sequence (the
+result of the first step) by a translation table specified
+by `:decode-translation-table' attribute.  The optional third step
+is to convert the above result by a Lisp function specified
+by `:post-read-conversion' attribute.
+
+The encoding is done by at most 3 steps, which are the reverse
+of the decoding steps.  The optional first step converts a
+character sequence to another character sequence by a Lisp
+function specified by `:pre-write-conversion' attribute.  The
+optional second step converts the above result by a translation
+table specified by `:encode-translation-table' attribute.  The
+third step converts the above result to a byte sequence by one
+of the Emacs's internal routines specified by the `:coding-type'
+attribute.
+
 The following attributes have special meanings.  Those labeled as
 \"(required)\" should not be omitted.
 
@@ -602,27 +625,72 @@ VALUE is a character to display on mode line for the 
coding system.
 
 `:coding-type' (required)
 
-VALUE must be one of `charset', `utf-8', `utf-16', `iso-2022',
-`emacs-mule', `shift-jis', `ccl', `raw-text', `undecided'.
+VALUE specifies the format of byte sequence the coding system
+decodes and encodes to.  It must be one of `charset', `utf-8',
+`utf-16', `iso-2022', `emacs-mule', `shift-jis', `ccl',
+`raw-text', `undecided'.
+
+If VALUE is `charset', the coding system is for handling a
+byte sequence in which each byte or every two- to four-byte
+sequence represents a character code of a charset specified
+by the `:charset-list' attribute.
+
+If VALUE is `utf-8', the coding system is for handling Unicode
+UTF-8 byte sequences.  See also the documentation of the
+attribute `:bom'.
+
+If VALUE is `utf-16', the coding system is for handling Unicode
+UTF-16 byte sequences.  See also the documentation of the
+attributes :bom and `:endian'.
+
+If VALUE is `iso-2022', the coding system is for handling byte
+sequences conforming to ISO/IEC 2022.  See also the documentation
+of the attributes `:charset-list', `:flags', and `:designation'.
+
+If VALUE is `emacs-mule', the coding system is for handling
+byte sequences which Emacs 20 and 21 used for their internal
+representation of characters.
+
+If VALUE is `shift-jis', the coding system is for handling byte
+sequences of Shift_JIS format.  See also the attribute `:charset-list'.
+
+If VALUE is `ccl', the coding system uses CCL programs to decode
+and encode byte sequences.  The CCL programs must be
+specified by the attributes `:ccl-decoder' and `:ccl-encoder'.
+
+If VALUE is `raw-text', the coding system decodes byte sequences
+without any conversions.
 
 `:eol-type'
 
 VALUE is the EOL (end-of-line) format of the coding system.  It must be
 one of `unix', `dos', `mac'.  The symbol `unix' means Unix-like EOL
-\(i.e. single LF), `dos' means DOS-like EOL \(i.e. sequence of CR LF),
-and `mac' means Mac-like EOL \(i.e. single CR).  If omitted, Emacs
-detects the EOL format automatically when decoding.
+\(i.e. a single LF character), `dos' means DOS-like EOL \(i.e. a sequence
+of CR followed by LF), and `mac' means Mac-like EOL \(i.e. a single CR).
+If omitted, Emacs detects the EOL format automatically when decoding.
+
+`:charset-list' (required if `:coding-type' is `charset' or `shift-jis')
+
+VALUE must be a list of charsets supported by the coding system.
+
+If `coding-type:' is `charset', then on decoding and encoding by the
+coding system, if a character belongs to multiple charsets in the
+list, a charset that comes first in the list is selected.
 
-`:charset-list'
+If `:coding-type' is `iso-2022', VALUE may be `iso-2022', which
+indicates that the coding system supports all ISO-2022 based
+charsets.
 
-VALUE must be a list of charsets supported by the coding system.  On
-encoding by the coding system, if a character belongs to multiple
-charsets in the list, a charset that comes earlier in the list is
-selected.  If `:coding-type' is `iso-2022', VALUE may be `iso-2022',
-which indicates that the coding system supports all ISO-2022 based
-charsets.  If `:coding-type' is `emacs-mule', VALUE may be
-`emacs-mule', which indicates that the coding system supports all
-charsets that have the `:emacs-mule-id' property.
+If `:coding-type' is `shift-jis', VALUE must be a list of three
+to four charsets supported by Shift_JIS encoding scheme.  The
+first charset (one dimension) is for code space 0x00..0x7F, the
+second (one dimension) for 0xA1..0xDF, the third (two dimension)
+for 0x8140..0xEFFC, the optional fourth (three dimension) for
+0xF040..0xFCFC.
+
+If `:coding-type' is `emacs-mule', VALUE may be `emacs-mule',
+which indicates that the coding system supports all charsets that
+have the `:emacs-mule-id' property.
 
 `:ascii-compatible-p'
 
@@ -643,9 +711,9 @@ VALUE must be a translation table to use on encoding.
 VALUE must be a function to call after some text is inserted and
 decoded by the coding system itself and before any functions in
 `after-insert-functions' are called.  This function is passed one
-argument; the number of characters in the text to convert, with
+argument: the number of characters in the text to convert, with
 point at the start of the text.  The function should leave point
-the same, and return the new character count.
+unchanged, and should return the new character count.
 
 `:pre-write-conversion'
 
@@ -674,7 +742,7 @@ to lower case.
 `:mime-text-unsuitable'
 
 VALUE non-nil means the `:mime-charset' property names a charset which
-is unsuitable for the top-level media type \"text\".
+is unsuitable for the top-level media of type \"text\".
 
 `:flags'
 
@@ -704,8 +772,8 @@ This attribute is meaningful only when `:coding-type' is 
`iso-2022'.
 
 `:bom'
 
-This attributes specifies whether the coding system uses a `byte order
-mark'.  VALUE must be nil, t, or cons of coding systems whose
+This attributes specifies whether the coding system uses a \"byte order
+mark\".  VALUE must be nil, t, or a cons cell of coding systems whose
 `:coding-type' is `utf-16' or `utf-8'.
 
 If the value is nil, on decoding, don't treat the first two-byte as
@@ -714,9 +782,9 @@ BOM, and on encoding, don't produce BOM bytes.
 If the value is t, on decoding, skip the first two-byte as BOM, and on
 encoding, produce BOM bytes according to the value of `:endian'.
 
-If the value is cons, on decoding, check the first two-byte.  If they
-are 0xFE 0xFF, use the car part coding system of the value.  If they
-are 0xFF 0xFE, use the cdr part coding system of the value.
+If the value is a cons cell, on decoding, check the first two bytes.
+If they are 0xFE 0xFF, use the car part coding system of the value.
+If they are 0xFF 0xFE, use the cdr part coding system of the value.
 Otherwise, treat them as bytes for a normal character.  On encoding,
 produce BOM bytes according to the value of `:endian'.
 
@@ -730,17 +798,17 @@ little-endian respectively.  The default value is `big'.
 
 This attribute is meaningful only when `:coding-type' is `utf-16'.
 
-`:ccl-decoder'
+`:ccl-decoder' (required if :coding-type is `ccl')
 
-VALUE is a symbol representing the registered CCL program used for
-decoding.  This attribute is meaningful only when `:coding-type' is
-`ccl'.
+VALUE is a CCL program name defined by `define-ccl-program'.  The
+CCL program reads a byte sequence and writes a character sequence
+as a decoding result.
 
-`:ccl-encoder'
+`:ccl-encoder' (required if :coding-type is `ccl')
 
-VALUE is a symbol representing the registered CCL program used for
-encoding.  This attribute is meaningful only when `:coding-type' is
-`ccl'.
+VALUE is a CCL program name defined by `define-ccl-program'.  The
+CCL program reads a character sequence and writes a byte sequence
+as an encoding result.
 
 `:inhibit-null-byte-detection'
 
@@ -2249,7 +2317,13 @@ ALIST is an alist, each element has the form (FROM . TO).
 FROM and TO are a character or a vector of characters.
 If FROM is a character, that character is translated to TO.
 If FROM is a vector of characters, that sequence is translated to TO.
-The first extra-slot of the value is a translation table for reverse mapping."
+The first extra-slot of the value is a translation table for reverse mapping.
+
+FROM and TO may be nil.  If TO is nil, the translation from FROM
+to nothing is defined in the translation table and that element
+is ignored in the reverse map.  If FROM is nil, the translation
+from TO to nothing is defined in the reverse map only.  A vector
+of length zero has the same meaning as specifying nil."
   (let ((tables (vector (make-char-table 'translation-table)
                        (make-char-table 'translation-table)))
        table max-lookup from to idx val)
@@ -2262,20 +2336,23 @@ The first extra-slot of the value is a translation 
table for reverse mapping."
          (setq from (cdr elt) to (car elt)))
        (if (characterp from)
            (setq idx from)
-         (setq idx (aref from 0)
-               max-lookup (max max-lookup (length from))))
-       (setq val (aref table idx))
-       (if val
-           (progn
-             (or (consp val)
-                 (setq val (list (cons (vector idx) val))))
-             (if (characterp from)
-                 (setq from (vector from)))
-             (setq val (nconc val (list (cons from to)))))
-         (if (characterp from)
-             (setq val to)
-           (setq val (list (cons from to)))))
-       (aset table idx val))
+         (if (= (length from) 0)
+             (setq idx nil)
+           (setq idx (aref from 0)
+                 max-lookup (max max-lookup (length from)))))
+       (when idx
+         (setq val (aref table idx))
+         (if val
+             (progn
+               (or (consp val)
+                   (setq val (list (cons (vector idx) val))))
+               (if (characterp from)
+                   (setq from (vector from)))
+               (setq val (nconc val (list (cons from to)))))
+           (if (characterp from)
+               (setq val to)
+             (setq val (list (cons from to)))))
+         (aset table idx val)))
       (set-char-table-extra-slot table 1 max-lookup))
     (set-char-table-extra-slot (aref tables 0) 0 (aref tables 1))
     (aref tables 0)))
diff --git a/lisp/language/misc-lang.el b/lisp/language/misc-lang.el
index ee06e34..b56d31f 100644
--- a/lisp/language/misc-lang.el
+++ b/lisp/language/misc-lang.el
@@ -78,7 +78,8 @@ and Italian.")))
 (set-char-table-range
  composition-function-table
  '(#x600 . #x6FF)
- (list ["[\u0600-\u06FF]+" 0 font-shape-gstring]))
+ (list ["\u200D?[\u0600-\u074F]+[\u200D\u200C]*[\u0600-\u074F]+\u200D?"
+       0 font-shape-gstring]))
 
 (provide 'misc-lang)
 
diff --git a/lisp/menu-bar.el b/lisp/menu-bar.el
index 8f33641..ea5794d 100644
--- a/lisp/menu-bar.el
+++ b/lisp/menu-bar.el
@@ -373,35 +373,29 @@
 
     (bindings--define-key menu [set-tags-name]
       '(menu-item "Set Tags File Name..." visit-tags-table
-                  :help "Tell Tags commands which tag table file to use"))
+                  :visible (menu-bar-goto-uses-etags-p)
+                  :help "Tell navigation commands which tag table file to 
use"))
 
     (bindings--define-key menu [separator-tag-file]
-      menu-bar-separator)
+      '(menu-item "--" nil :visible (menu-bar-goto-uses-etags-p)))
+
+    (bindings--define-key menu [xref-pop]
+      '(menu-item "Back" xref-pop-marker-stack
+                  :help "Back to the position of the last search"))
 
-    (bindings--define-key menu [apropos-tags]
-      '(menu-item "Tags Apropos..." tags-apropos
+    (bindings--define-key menu [xref-apropos]
+      '(menu-item "Find Apropos..." xref-find-apropos
                   :help "Find function/variables whose names match regexp"))
-    (bindings--define-key menu [next-tag-otherw]
-      '(menu-item "Next Tag in Other Window"
-                  menu-bar-next-tag-other-window
-                  :enable (and (boundp 'tags-location-ring)
-                               (not (ring-empty-p tags-location-ring)))
-                  :help "Find next function/variable matching last tag name in 
another window"))
-
-    (bindings--define-key menu [next-tag]
-      '(menu-item "Find Next Tag"
-                  menu-bar-next-tag
-                  :enable (and (boundp 'tags-location-ring)
-                               (not (ring-empty-p tags-location-ring)))
-                  :help "Find next function/variable matching last tag name"))
-    (bindings--define-key menu [find-tag-otherw]
-      '(menu-item "Find Tag in Other Window..." find-tag-other-window
+
+    (bindings--define-key menu [xref-find-otherw]
+      '(menu-item "Find Definition in Other Window..."
+                  xref-find-definitions-other-window
                   :help "Find function/variable definition in another window"))
-    (bindings--define-key menu [find-tag]
-      '(menu-item "Find Tag..." find-tag
+    (bindings--define-key menu [xref-find-def]
+      '(menu-item "Find Definition..." xref-find-definitions
                   :help "Find definition of function or variable"))
 
-    (bindings--define-key menu [separator-tags]
+    (bindings--define-key menu [separator-xref]
       menu-bar-separator)
 
     (bindings--define-key menu [end-of-buf]
@@ -416,6 +410,9 @@
                   :help "Read a line number and go to that line"))
     menu))
 
+(defun menu-bar-goto-uses-etags-p ()
+  (or (not (boundp 'xref-find-function))
+      (eq xref-find-function 'etags-xref-find)))
 
 (defvar yank-menu (cons (purecopy "Select Yank") nil))
 (fset 'yank-menu (cons 'keymap yank-menu))
@@ -514,16 +511,6 @@
 
     menu))
 
-(defun menu-bar-next-tag-other-window ()
-  "Find the next definition of the tag already specified."
-  (interactive)
-  (find-tag-other-window nil t))
-
-(defun menu-bar-next-tag ()
-  "Find the next definition of the tag already specified."
-  (interactive)
-  (find-tag nil t))
-
 (define-obsolete-function-alias
   'menu-bar-kill-ring-save 'kill-ring-save "24.1")
 
diff --git a/lisp/minibuffer.el b/lisp/minibuffer.el
index e1e6b0e..9198901 100644
--- a/lisp/minibuffer.el
+++ b/lisp/minibuffer.el
@@ -1818,8 +1818,9 @@ variables.")
              ,(if (eq (selected-window) (minibuffer-window))
                   'display-buffer-at-bottom
                 'display-buffer-below-selected))
-           ,(when temp-buffer-resize-mode
-              '(window-height . resize-temp-buffer-window))
+           ,(if temp-buffer-resize-mode
+                '(window-height . resize-temp-buffer-window)
+              '(window-height . shrink-window-if-larger-than-buffer))
            ,(when temp-buffer-resize-mode
               '(preserve-size . (nil . t))))
           nil
diff --git a/lisp/net/eww.el b/lisp/net/eww.el
index c6d3bbc..af902de 100644
--- a/lisp/net/eww.el
+++ b/lisp/net/eww.el
@@ -445,7 +445,7 @@ See the `eww-search-prefix' variable for the search engine 
used."
                   ("start" . :start)
                   ("home" . :home)
                   ("contents" . :contents)
-                  ("up" . up)))))
+                  ("up" . :up)))))
     (and href
         where
         (plist-put eww-data (cdr where) href))))
@@ -705,6 +705,9 @@ the like."
    (setq-local tool-bar-map eww-tool-bar-map))
   ;; desktop support
   (setq-local desktop-save-buffer 'eww-desktop-misc-data)
+  ;; multi-page isearch support
+  (setq-local multi-isearch-next-buffer-function 'eww-isearch-next-buffer)
+  (setq truncate-lines t)
   (buffer-disable-undo)
   (setq buffer-read-only t))
 
@@ -1884,6 +1887,19 @@ Otherwise, the restored buffer will contain a prompt to 
do so by using
 (add-to-list 'desktop-buffer-mode-handlers
              '(eww-mode . eww-restore-desktop))
 
+;;; Isearch support
+
+(defun eww-isearch-next-buffer (&optional buffer wrap)
+  "Go to the next page to search using `rel' attribute for navigation."
+  (if wrap
+      (condition-case nil
+         (eww-top-url)
+       (error nil))
+    (if isearch-forward
+       (eww-next-url)
+      (eww-previous-url)))
+  (current-buffer))
+
 (provide 'eww)
 
 ;;; eww.el ends here
diff --git a/lisp/net/shr.el b/lisp/net/shr.el
index 387bb02..6553fd3 100644
--- a/lisp/net/shr.el
+++ b/lisp/net/shr.el
@@ -78,11 +78,12 @@ If nil, don't draw horizontal table lines."
   :group 'shr
   :type 'character)
 
-(defcustom shr-width fill-column
+(defcustom shr-width nil
   "Frame width to use for rendering.
 May either be an integer specifying a fixed width in characters,
 or nil, meaning that the full width of the window should be
 used."
+  :version "25.1"
   :type '(choice (integer :tag "Fixed width in characters")
                 (const   :tag "Use the width of the window" nil))
   :group 'shr)
@@ -1439,10 +1440,11 @@ The preference is a float determined from 
`shr-prefer-media-type'."
 
 (defun shr-tag-table (dom)
   (shr-ensure-paragraph)
-  (let* ((caption (dom-child-by-tag dom 'caption))
-        (header (dom-child-by-tag dom 'thead))
-        (body (or (dom-child-by-tag dom 'tbody) dom))
-        (footer (dom-child-by-tag dom 'tfoot))
+  (let* ((caption (dom-children (dom-child-by-tag dom 'caption)))
+        (header (dom-non-text-children (dom-child-by-tag dom 'thead)))
+        (body (dom-non-text-children (or (dom-child-by-tag dom 'tbody)
+                                         dom)))
+        (footer (dom-non-text-children (dom-child-by-tag dom 'tfoot)))
          (bgcolor (dom-attr dom 'bgcolor))
         (start (point))
         (shr-stylesheet (nconc (list (cons 'background-color bgcolor))
@@ -1461,42 +1463,62 @@ The preference is a float determined from 
`shr-prefer-media-type'."
       ;; It's a real table, so render it.
       (shr-tag-table-1
        (nconc
-       (if caption `((tr (td ,@caption))))
-       (if header
-           (if footer
-               ;; header + body + footer
-               (if (= nheader nbody)
-                   (if (= nbody nfooter)
-                       `((tr (td (table (tbody ,@header ,@body ,@footer)))))
-                     (nconc `((tr (td (table (tbody ,@header ,@body)))))
-                            (if (= nfooter 1)
-                                footer
-                              `((tr (td (table (tbody ,@footer))))))))
-                 (nconc `((tr (td (table (tbody ,@header)))))
-                        (if (= nbody nfooter)
-                            `((tr (td (table (tbody ,@body ,@footer)))))
-                          (nconc `((tr (td (table (tbody ,@body)))))
-                                 (if (= nfooter 1)
-                                     footer
-                                   `((tr (td (table (tbody ,@footer))))))))))
-             ;; header + body
-             (if (= nheader nbody)
-                 `((tr (td (table (tbody ,@header ,@body)))))
-               (if (= nheader 1)
-                   `(,@header (tr (td (table (tbody ,@body)))))
-                 `((tr (td (table (tbody ,@header))))
-                   (tr (td (table (tbody ,@body))))))))
-         (if footer
-             ;; body + footer
-             (if (= nbody nfooter)
-                 `((tr (td (table (tbody ,@body ,@footer)))))
-               (nconc `((tr (td (table (tbody ,@body)))))
-                      (if (= nfooter 1)
-                          footer
-                        `((tr (td (table (tbody ,@footer))))))))
-           (if caption
-               `((tr (td (table (tbody ,@body)))))
-             body))))))
+       (list 'table nil)
+       (if caption `((tr nil (td nil ,@caption))))
+       (cond (header
+              (if footer
+                  ;; header + body + footer
+                  (if (= nheader nbody)
+                      (if (= nbody nfooter)
+                          `((tr nil (td nil (table nil
+                                                   (tbody nil ,@header
+                                                          ,@body ,@footer)))))
+                        (nconc `((tr nil (td nil (table nil
+                                                        (tbody nil ,@header
+                                                               ,@body)))))
+                               (if (= nfooter 1)
+                                   footer
+                                 `((tr nil (td nil (table
+                                                    nil (tbody
+                                                         nil ,@footer))))))))
+                    (nconc `((tr nil (td nil (table nil (tbody
+                                                         nil ,@header)))))
+                           (if (= nbody nfooter)
+                               `((tr nil (td nil (table
+                                                  nil (tbody nil ,@body
+                                                             ,@footer)))))
+                             (nconc `((tr nil (td nil (table
+                                                       nil (tbody nil
+                                                                  ,@body)))))
+                                    (if (= nfooter 1)
+                                        footer
+                                      `((tr nil (td nil (table
+                                                         nil
+                                                         (tbody
+                                                          nil
+                                                          ,@footer))))))))))
+                ;; header + body
+                (if (= nheader nbody)
+                    `((tr nil (td nil (table nil (tbody nil ,@header
+                                                        ,@body)))))
+                  (if (= nheader 1)
+                      `(,@header (tr nil (td nil (table
+                                                  nil (tbody nil ,@body)))))
+                    `((tr nil (td nil (table nil (tbody nil ,@header))))
+                      (tr nil (td nil (table nil (tbody nil ,@body)))))))))
+             (footer
+              ;; body + footer
+              (if (= nbody nfooter)
+                  `((tr nil (td nil (table
+                                     nil (tbody nil ,@body ,@footer)))))
+                (nconc `((tr nil (td nil (table nil (tbody nil ,@body)))))
+                       (if (= nfooter 1)
+                           footer
+                         `((tr nil (td nil (table
+                                            nil (tbody nil ,@footer)))))))))
+             (caption
+              `((tr nil (td nil (table nil (tbody nil ,@body))))))
+             (body)))))
     (when bgcolor
       (shr-colorize-region start (point) (cdr (assq 'color shr-stylesheet))
                           bgcolor))
diff --git a/lisp/net/tramp-gw.el b/lisp/net/tramp-gw.el
index 0decd88..e21aaf7 100644
--- a/lisp/net/tramp-gw.el
+++ b/lisp/net/tramp-gw.el
@@ -195,11 +195,12 @@ instead of the host name declared in TARGET-VEC."
     (setq tramp-gw-gw-proc
          (funcall
           socks-function
-          (tramp-get-connection-name gw-vec)
-          (tramp-get-connection-buffer gw-vec)
+          (let ((tramp-verbose 0)) (tramp-get-connection-name gw-vec))
+          (let ((tramp-verbose 0)) (tramp-get-connection-buffer gw-vec))
           (tramp-file-name-real-host target-vec)
           (tramp-file-name-port target-vec)))
     (set-process-sentinel tramp-gw-gw-proc 'tramp-gw-gw-proc-sentinel)
+    (set-process-coding-system tramp-gw-gw-proc 'binary 'binary)
     (tramp-compat-set-process-query-on-exit-flag tramp-gw-gw-proc nil)
     (tramp-message
      vec 4 "Opened %s process `%s'"
@@ -260,6 +261,10 @@ authentication is requested from proxy server, provide it."
          (200 (setq found t))
          ;; We need basic authentication.
          (401 (setq authentication (tramp-gw-basic-authentication nil first)))
+         ;; Access forbidden.
+         (403 (tramp-error-with-buffer
+               (current-buffer) tramp-gw-vector 'file-error
+               "Connection to %s:%d forbidden." host service))
          ;; Target host not found.
          (404 (tramp-error-with-buffer
                (current-buffer) tramp-gw-vector 'file-error
diff --git a/lisp/net/tramp-sh.el b/lisp/net/tramp-sh.el
index ba7b7d9..6fc2eff 100644
--- a/lisp/net/tramp-sh.el
+++ b/lisp/net/tramp-sh.el
@@ -2471,8 +2471,12 @@ The method used must be an out-of-band method."
                   (mapconcat 'identity (process-command p) " "))
                  (tramp-set-connection-property p "vector" orig-vec)
                  (tramp-compat-set-process-query-on-exit-flag p nil)
-                 (tramp-process-actions
-                  p v nil tramp-actions-copy-out-of-band)
+
+                 ;; We must adapt `tramp-local-end-of-line' for
+                 ;; sending the password.
+                 (let ((tramp-local-end-of-line tramp-rsh-end-of-line))
+                   (tramp-process-actions
+                    p v nil tramp-actions-copy-out-of-band))
 
                  ;; Check the return code.
                  (goto-char (point-max))
@@ -2883,7 +2887,7 @@ the result will be a local, non-Tramp, file name."
           (name1 name)
           (i 0)
           ;; We do not want to raise an error when
-          ;; `start-file-process' has been started several time in
+          ;; `start-file-process' has been started several times in
           ;; `eshell' and friends.
           (tramp-current-connection nil))
 
@@ -4510,7 +4514,8 @@ Gateway hops are already opened."
        ;; Therefore, we must remember the gateway vector.  But we
        ;; cannot do it as connection property, because it shouldn't
        ;; be persistent.  And we have no started process yet either.
-       (tramp-set-file-property (car target-alist) "" "gateway" hop)))
+       (let ((tramp-verbose 0))
+         (tramp-set-file-property (car target-alist) "" "gateway" hop))))
 
     ;; Foreign and out-of-band methods are not supported for multi-hops.
     (when (cdr target-alist)
@@ -4687,7 +4692,8 @@ connection if a previous connection has died for some 
reason."
                           l-method 'tramp-connection-timeout))
                         (gw-args
                          (tramp-get-method-parameter l-method 'tramp-gw-args))
-                        (gw (tramp-get-file-property hop "" "gateway" nil))
+                        (gw (let ((tramp-verbose 0))
+                              (tramp-get-file-property hop "" "gateway" nil)))
                         (g-method (and gw (tramp-file-name-method gw)))
                         (g-user (and gw (tramp-file-name-user gw)))
                         (g-host (and gw (tramp-file-name-real-host gw)))
@@ -4715,8 +4721,10 @@ connection if a previous connection has died for some 
reason."
                      (setq login-args (append async-args login-args)))
 
                    ;; Add gateway arguments if necessary.
-                   (when (and gw gw-args)
-                     (setq login-args (append gw-args login-args)))
+                   (when gw
+                     (tramp-set-connection-property p "gateway" t)
+                     (when gw-args
+                       (setq login-args (append gw-args login-args))))
 
                    ;; Check for port number.  Until now, there's no
                    ;; need for handling like method, user, host.
@@ -4902,8 +4910,9 @@ FMT and ARGS which are passed to `error'."
   (or (tramp-send-command-and-check vec command)
       (apply 'tramp-error vec 'file-error fmt args)))
 
-(defun tramp-send-command-and-read (vec command &optional noerror)
+(defun tramp-send-command-and-read (vec command &optional noerror marker)
   "Run COMMAND and return the output, which must be a Lisp expression.
+If MARKER is a regexp, read the output after that string.
 In case there is no valid Lisp expression and NOERROR is nil, it
 raises an error."
   (when (if noerror
@@ -4911,8 +4920,17 @@ raises an error."
          (tramp-barf-unless-okay
           vec command "`%s' returns with error" command))
     (with-current-buffer (tramp-get-connection-buffer vec)
-      ;; Read the expression.
       (goto-char (point-min))
+      ;; Read the marker.
+      (when (stringp marker)
+       (condition-case nil
+           (re-search-forward marker)
+         (error (unless noerror
+                  (tramp-error
+                   vec 'file-error
+                   "`%s' does not return the marker `%s': `%s'"
+                   command marker (buffer-string))))))
+      ;; Read the expression.
       (condition-case nil
          (prog1 (read (current-buffer))
            ;; Error handling.
@@ -5064,25 +5082,22 @@ Return ATTR."
                   "/bin:/usr/bin")
                  "/bin:/usr/bin"))))
           (own-remote-path
-           ;; We cannot apply `tramp-send-command-and-read' because
-           ;; the login shell could return more than just the $PATH
-           ;; string.  So we emulate that function.
+           ;; The login shell could return more than just the $PATH
+           ;; string.  So we use `tramp-end-of-heredoc' as marker.
            (when elt2
-             (tramp-send-command
+             (tramp-send-command-and-read
               vec
               (format
-               "%s -l %s 'echo \\\"$PATH\\\"'"
+               "%s -l %s 'echo %s \\\"$PATH\\\"'"
                (tramp-get-method-parameter
                 (tramp-file-name-method vec) 'tramp-remote-shell)
                (mapconcat
                 'identity
                 (tramp-get-method-parameter
                  (tramp-file-name-method vec) 'tramp-remote-shell-args)
-                " ")))
-             (with-current-buffer (tramp-get-connection-buffer vec)
-               (goto-char (point-max))
-               (forward-line -1)
-               (read (current-buffer))))))
+                " ")
+               (tramp-shell-quote-argument tramp-end-of-heredoc))
+              nil (regexp-quote tramp-end-of-heredoc)))))
 
       ;; Replace place holder `tramp-default-remote-path'.
       (when elt1
diff --git a/lisp/net/tramp.el b/lisp/net/tramp.el
index 2cf9d45..3c8b5bb 100644
--- a/lisp/net/tramp.el
+++ b/lisp/net/tramp.el
@@ -1610,7 +1610,7 @@ an input event arrives.  The other arguments are passed 
to `tramp-error'."
          (let ((enable-recursive-minibuffers t))
            ;; `tramp-error' does not show messages.  So we must do it
            ;; ourselves.
-           (message fmt-string arguments)
+           (apply 'message fmt-string arguments)
            ;; Show buffer.
            (pop-to-buffer buf)
            (discard-input)
@@ -3086,115 +3086,118 @@ User is always nil."
   (setq filename (expand-file-name filename))
   (let (result local-copy remote-copy)
     (with-parsed-tramp-file-name filename nil
-      (with-tramp-progress-reporter
-         v 3 (format "Inserting `%s'" filename)
-       (unwind-protect
-           (if (not (file-exists-p filename))
-               (progn
-                 ;; We don't raise a Tramp error, because it might be
-                 ;; suppressed, like in `find-file-noselect-1'.
-                 (tramp-message
-                  v 1 "File not `%s' found on remote host" filename)
-                 (signal 'file-error
-                         (list "File not found on remote host" filename)))
-
-             (if (and (tramp-local-host-p v)
-                      (let (file-name-handler-alist)
-                        (file-readable-p localname)))
-                 ;; Short track: if we are on the local host, we can
-                 ;; run directly.
-                 (setq result
-                       (tramp-run-real-handler
-                        'insert-file-contents
-                        (list localname visit beg end replace)))
-
-               ;; When we shall insert only a part of the file, we
-               ;; copy this part.  This works only for the shell file
-               ;; name handlers.
-               (when (and (or beg end)
-                          (tramp-get-method-parameter
-                           (tramp-file-name-method v) 'tramp-login-program))
-                 (setq remote-copy (tramp-make-tramp-temp-file v))
-                 ;; This is defined in tramp-sh.el.  Let's assume
-                 ;; this is loaded already.
-                 (tramp-compat-funcall
-                  'tramp-send-command
-                  v
-                  (cond
-                   ((and beg end)
-                    (format "dd bs=1 skip=%d if=%s count=%d of=%s"
-                            beg (tramp-shell-quote-argument localname)
-                            (- end beg) remote-copy))
-                   (beg
-                    (format "dd bs=1 skip=%d if=%s of=%s"
-                            beg (tramp-shell-quote-argument localname)
-                            remote-copy))
-                   (end
-                    (format "dd bs=1 count=%d if=%s of=%s"
-                            end (tramp-shell-quote-argument localname)
-                            remote-copy))))
-                 (setq tramp-temp-buffer-file-name nil beg nil end nil))
-
-               ;; `insert-file-contents-literally' takes care to
-               ;; avoid calling jka-compr.  By let-binding
-               ;; `inhibit-file-name-operation', we propagate that
-               ;; care to the `file-local-copy' operation.
-               (setq local-copy
-                     (let ((inhibit-file-name-operation
-                            (when (eq inhibit-file-name-operation
-                                      'insert-file-contents)
-                              'file-local-copy)))
-                       (cond
-                        ((stringp remote-copy)
-                         (file-local-copy
-                          (tramp-make-tramp-file-name
-                           method user host remote-copy)))
-                        ((stringp tramp-temp-buffer-file-name)
-                         (copy-file filename tramp-temp-buffer-file-name 'ok)
-                         tramp-temp-buffer-file-name)
-                        (t (file-local-copy filename)))))
-
-               ;; When the file is not readable for the owner, it
-               ;; cannot be inserted, even if it is readable for the
-               ;; group or for everybody.
-               (set-file-modes
-                local-copy (tramp-compat-octal-to-decimal "0600"))
-
-               (when (and (null remote-copy)
-                          (tramp-get-method-parameter
-                           method 'tramp-copy-keep-tmpfile))
-                 ;; We keep the local file for performance reasons,
-                 ;; useful for "rsync".
-                 (setq tramp-temp-buffer-file-name local-copy))
-
-               ;; We must ensure that `file-coding-system-alist'
-               ;; matches `local-copy'.  We must also use `visit',
-               ;; otherwise there might be an error in the
-               ;; `revert-buffer' function under XEmacs.
-               (let ((file-coding-system-alist
-                      (tramp-find-file-name-coding-system-alist
-                       filename local-copy)))
-                 (setq result
-                       (insert-file-contents
-                        local-copy visit beg end replace)))))
-
-         ;; Save exit.
-         (progn
-           (when visit
-             (setq buffer-file-name filename)
-             (setq buffer-read-only (not (file-writable-p filename)))
-             (set-visited-file-modtime)
-             (set-buffer-modified-p nil))
-           (when (and (stringp local-copy)
-                      (or remote-copy (null tramp-temp-buffer-file-name)))
-             (delete-file local-copy))
-           (when (stringp remote-copy)
-             (delete-file
-              (tramp-make-tramp-file-name method user host remote-copy)))))))
-
-    ;; Result.
-    (list (expand-file-name filename)
-         (cadr result))))
+      (unwind-protect
+         (if (not (file-exists-p filename))
+             (tramp-error
+              v 'file-error "File `%s' not found on remote host" filename)
+
+           (with-tramp-progress-reporter
+               v 3 (format "Inserting `%s'" filename)
+             (condition-case err
+                 (if (and (tramp-local-host-p v)
+                          (let (file-name-handler-alist)
+                            (file-readable-p localname)))
+                     ;; Short track: if we are on the local host, we can
+                     ;; run directly.
+                     (setq result
+                           (tramp-run-real-handler
+                            'insert-file-contents
+                            (list localname visit beg end replace)))
+
+                   ;; When we shall insert only a part of the file, we
+                   ;; copy this part.  This works only for the shell file
+                   ;; name handlers.
+                   (when (and (or beg end)
+                              (tramp-get-method-parameter
+                               (tramp-file-name-method v)
+                               'tramp-login-program))
+                     (setq remote-copy (tramp-make-tramp-temp-file v))
+                     ;; This is defined in tramp-sh.el.  Let's assume
+                     ;; this is loaded already.
+                     (tramp-compat-funcall
+                      'tramp-send-command
+                      v
+                      (cond
+                       ((and beg end)
+                        (format "dd bs=1 skip=%d if=%s count=%d of=%s"
+                                beg (tramp-shell-quote-argument localname)
+                                (- end beg) remote-copy))
+                       (beg
+                        (format "dd bs=1 skip=%d if=%s of=%s"
+                                beg (tramp-shell-quote-argument localname)
+                                remote-copy))
+                       (end
+                        (format "dd bs=1 count=%d if=%s of=%s"
+                                end (tramp-shell-quote-argument localname)
+                                remote-copy))))
+                     (setq tramp-temp-buffer-file-name nil beg nil end nil))
+
+                   ;; `insert-file-contents-literally' takes care to
+                   ;; avoid calling jka-compr.  By let-binding
+                   ;; `inhibit-file-name-operation', we propagate that
+                   ;; care to the `file-local-copy' operation.
+                   (setq local-copy
+                         (let ((inhibit-file-name-operation
+                                (when (eq inhibit-file-name-operation
+                                          'insert-file-contents)
+                                  'file-local-copy)))
+                           (cond
+                            ((stringp remote-copy)
+                             (file-local-copy
+                              (tramp-make-tramp-file-name
+                               method user host remote-copy)))
+                            ((stringp tramp-temp-buffer-file-name)
+                             (copy-file
+                              filename tramp-temp-buffer-file-name 'ok)
+                             tramp-temp-buffer-file-name)
+                            (t (file-local-copy filename)))))
+
+                   ;; When the file is not readable for the owner, it
+                   ;; cannot be inserted, even if it is readable for the
+                   ;; group or for everybody.
+                   (set-file-modes
+                    local-copy (tramp-compat-octal-to-decimal "0600"))
+
+                   (when (and (null remote-copy)
+                              (tramp-get-method-parameter
+                               method 'tramp-copy-keep-tmpfile))
+                     ;; We keep the local file for performance reasons,
+                     ;; useful for "rsync".
+                     (setq tramp-temp-buffer-file-name local-copy))
+
+                   ;; We must ensure that `file-coding-system-alist'
+                   ;; matches `local-copy'.  We must also use `visit',
+                   ;; otherwise there might be an error in the
+                   ;; `revert-buffer' function under XEmacs.
+                   (let ((file-coding-system-alist
+                          (tramp-find-file-name-coding-system-alist
+                           filename local-copy)))
+                     (setq result
+                           (insert-file-contents
+                            local-copy visit beg end replace))))
+               (error
+                (add-hook 'find-file-not-found-functions
+                          `(lambda () (signal ',(car err) ',(cdr err)))
+                          nil t)
+                (signal (car err) (cdr err))))))
+
+       ;; Save exit.
+       (progn
+         (when visit
+           (setq buffer-file-name filename)
+           (setq buffer-read-only (not (file-writable-p filename)))
+           (set-visited-file-modtime)
+           (set-buffer-modified-p nil))
+         (when (and (stringp local-copy)
+                    (or remote-copy (null tramp-temp-buffer-file-name)))
+           (delete-file local-copy))
+         (when (stringp remote-copy)
+           (delete-file
+            (tramp-make-tramp-file-name method user host remote-copy)))))
+
+      ;; Result.
+      (list (expand-file-name filename)
+           (cadr result)))))
 
 (defun tramp-handle-load (file &optional noerror nomessage nosuffix 
must-suffix)
   "Like `load' for Tramp files."
@@ -3609,15 +3612,19 @@ connection buffer."
 This is needed in order to hide `last-coding-system-used', which is set
 for process communication also."
   (with-current-buffer (process-buffer proc)
-    (tramp-message proc 10 "%s %s" proc (process-status proc))
-    (let (buffer-read-only last-coding-system-used)
+    ;; FIXME: If there is a gateway process, we need communication
+    ;; between several processes.  Too complicate to implement, so we
+    ;; read output from all processes.
+    (let ((p (if (tramp-get-connection-property proc "gateway" nil) nil proc))
+         buffer-read-only last-coding-system-used)
       ;; Under Windows XP, accept-process-output doesn't return
       ;; sometimes.  So we add an additional timeout.
       (with-timeout ((or timeout 1))
        (if (featurep 'xemacs)
-           (accept-process-output proc timeout timeout-msecs)
-         (accept-process-output proc timeout timeout-msecs (and proc t)))))
-    (tramp-message proc 10 "\n%s" (buffer-string))))
+           (accept-process-output p timeout timeout-msecs)
+         (accept-process-output p timeout timeout-msecs (and proc t))))
+      (tramp-message proc 10 "%s %s %s\n%s"
+                    proc (process-status proc) p (buffer-string)))))
 
 (defun tramp-check-for-regexp (proc regexp)
   "Check, whether REGEXP is contained in process buffer of PROC.
@@ -4184,25 +4191,27 @@ Invokes `password-read' if available, `read-passwd' 
else."
               ;; it's bound.  `auth-source-user-or-password' is an
               ;; obsoleted function, it has been replaced by
               ;; `auth-source-search'.
-              (and (boundp 'auth-sources)
-                   (tramp-get-connection-property
-                    v "first-password-request" nil)
-                   ;; Try with Tramp's current method.
-                   (if (fboundp 'auth-source-search)
-                       (setq auth-info
-                             (tramp-compat-funcall
-                              'auth-source-search
-                              :max 1
-                              :user (or tramp-current-user t)
-                              :host tramp-current-host
-                              :port tramp-current-method)
-                             auth-passwd (plist-get (nth 0 auth-info) :secret)
-                             auth-passwd (if (functionp auth-passwd)
-                                             (funcall auth-passwd)
-                                           auth-passwd))
-                     (tramp-compat-funcall
-                      'auth-source-user-or-password
-                      "password" tramp-current-host tramp-current-method)))
+              (ignore-errors
+                (and (boundp 'auth-sources)
+                     (tramp-get-connection-property
+                      v "first-password-request" nil)
+                     ;; Try with Tramp's current method.
+                     (if (fboundp 'auth-source-search)
+                         (setq auth-info
+                               (tramp-compat-funcall
+                                'auth-source-search
+                                :max 1
+                                :user (or tramp-current-user t)
+                                :host tramp-current-host
+                                :port tramp-current-method)
+                               auth-passwd (plist-get
+                                            (nth 0 auth-info) :secret)
+                               auth-passwd (if (functionp auth-passwd)
+                                               (funcall auth-passwd)
+                                             auth-passwd))
+                       (tramp-compat-funcall
+                        'auth-source-user-or-password
+                        "password" tramp-current-host tramp-current-method))))
               ;; Try the password cache.
               (when (functionp 'password-read)
                 (let ((password
diff --git a/lisp/nxml/rng-uri.el b/lisp/nxml/rng-uri.el
index b93624a..43218ec 100644
--- a/lisp/nxml/rng-uri.el
+++ b/lisp/nxml/rng-uri.el
@@ -85,7 +85,7 @@ Signal an error if URI is not a valid file URL."
          ((not (string= (downcase scheme) "file"))
           (rng-uri-error "URI `%s' does not use the `file:' scheme" uri)))
     (when (not (member authority
-                      (cons system-name '(nil "" "localhost"))))
+                      (cons (system-name) '(nil "" "localhost"))))
       (rng-uri-error "URI `%s' does not start with `file:///' or 
`file://localhost/'"
             uri))
     (when query
diff --git a/lisp/obsolete/pc-select.el b/lisp/obsolete/pc-select.el
index 5ee0818..5404f49 100644
--- a/lisp/obsolete/pc-select.el
+++ b/lisp/obsolete/pc-select.el
@@ -337,7 +337,7 @@ but before calling PC Selection mode):
                            (cadr pc-select-meta-moves-sexps-key-bindings))
                          (if  (or pc-select-selection-keys-only
                                   (eq window-system 'x)
-                                  (memq system-name '(ms-dos windows-nt)))
+                                  (memq system-type '(ms-dos windows-nt)))
                              nil
                            pc-select-tty-key-bindings)))
 
@@ -346,7 +346,7 @@ but before calling PC Selection mode):
 
            (unless  (or pc-select-selection-keys-only
                         (eq window-system 'x)
-                        (memq system-name '(ms-dos windows-nt)))
+                        (memq system-type '(ms-dos windows-nt)))
              ;; it is not clear that we need the following line
              ;; I hope it doesn't do too much harm to leave it in, though...
              (setq pc-select-old-M-delete-binding
@@ -355,7 +355,7 @@ but before calling PC Selection mode):
 
            (when (and (not pc-select-selection-keys-only)
                       (or (eq window-system 'x)
-                          (memq system-name '(ms-dos windows-nt)))
+                          (memq system-type '(ms-dos windows-nt)))
                       (fboundp 'normal-erase-is-backspace-mode))
              (pc-select-save-and-set-mode normal-erase-is-backspace-mode 1
                                           normal-erase-is-backspace))
@@ -378,13 +378,13 @@ but before calling PC Selection mode):
                               (current-global-map))
        (unless  (or pc-select-selection-keys-only
                     (eq window-system 'x)
-                    (memq system-name '(ms-dos windows-nt)))
+                    (memq system-type '(ms-dos windows-nt)))
          ;; it is not clear that we need the following line
          ;; I hope it doesn't do too much harm to leave it in, though...
          (define-key function-key-map  [M-delete] [?\M-d]))
        (when (and (not pc-select-selection-keys-only)
                   (or (eq window-system 'x)
-                      (memq system-name '(ms-dos windows-nt)))
+                      (memq system-type '(ms-dos windows-nt)))
                   (fboundp 'normal-erase-is-backspace-mode))
          (normal-erase-is-backspace-mode 1))
        (setq highlight-nonselected-windows nil)
@@ -395,7 +395,7 @@ but before calling PC Selection mode):
     (when pc-select-key-bindings-alist
       (when (and (not pc-select-selection-keys-only)
                 (or (eq window-system 'x)
-                    (memq system-name '(ms-dos windows-nt))))
+                    (memq system-type '(ms-dos windows-nt))))
        (pc-select-restore-mode normal-erase-is-backspace-mode))
 
       (pc-select-restore-keys
diff --git a/lisp/org/org-clock.el b/lisp/org/org-clock.el
index 51c8789..c928758 100644
--- a/lisp/org/org-clock.el
+++ b/lisp/org/org-clock.el
@@ -2811,8 +2811,8 @@ The details of what will be saved are regulated by the 
variable
          (delete-region (point-min) (point-max))
          ;;Store clock
          (insert (format ";; org-persist.el - %s at %s\n"
-                         system-name (format-time-string
-                                      (cdr org-time-stamp-formats))))
+                         (system-name) (format-time-string
+                                        (cdr org-time-stamp-formats))))
          (if (and (memq org-clock-persist '(t clock))
                   (setq b (org-clocking-buffer))
                   (setq b (or (buffer-base-buffer b) b))
diff --git a/lisp/org/org-ctags.el b/lisp/org/org-ctags.el
index 41775bd..faf543b 100644
--- a/lisp/org/org-ctags.el
+++ b/lisp/org/org-ctags.el
@@ -63,19 +63,19 @@
 ;; with the same name as the link; then, if unsuccessful, ask the user if
 ;; he/she wants to rebuild the 'TAGS' database and try again; then ask if
 ;; the user wishes to append 'tag' as a new toplevel heading at the end of
-;; the buffer; and finally, defer to org's default behaviour which is to
+;; the buffer; and finally, defer to org's default behavior which is to
 ;; search the entire text of the current buffer for 'tag'.
 ;;
-;; This behaviour can be modified by changing the value of
+;; This behavior can be modified by changing the value of
 ;; ORG-CTAGS-OPEN-LINK-FUNCTIONS. For example I have the following in my
-;; .emacs, which describes the same behaviour as the above paragraph with
+;; .emacs, which describes the same behavior as the above paragraph with
 ;; one difference:
 ;;
 ;; (setq org-ctags-open-link-functions
 ;;       '(org-ctags-find-tag
 ;;         org-ctags-ask-rebuild-tags-file-then-find-tag
 ;;         org-ctags-ask-append-topic
-;;         org-ctags-fail-silently))  ; <-- prevents org default behaviour
+;;         org-ctags-fail-silently))  ; <-- prevents org default behavior
 ;;
 ;;
 ;; Usage
diff --git a/lisp/org/ox-html.el b/lisp/org/ox-html.el
index a3f0b50..c952a82 100644
--- a/lisp/org/ox-html.el
+++ b/lisp/org/ox-html.el
@@ -581,7 +581,7 @@ The function must accept two parameters:
 The function should return the string to be exported.
 
 For example, the variable could be set to the following function
-in order to mimic default behaviour:
+in order to mimic default behavior:
 
 The default value simply returns the value of CONTENTS."
   :group 'org-export-html
diff --git a/lisp/org/ox-latex.el b/lisp/org/ox-latex.el
index 2c71f7d..f6f3b22 100644
--- a/lisp/org/ox-latex.el
+++ b/lisp/org/ox-latex.el
@@ -589,7 +589,7 @@ The function must accept six parameters:
 The function should return the string to be exported.
 
 For example, the variable could be set to the following function
-in order to mimic default behaviour:
+in order to mimic default behavior:
 
 \(defun org-latex-format-inlinetask \(todo type priority name tags contents\)
 \"Format an inline task element for LaTeX export.\"
diff --git a/lisp/org/ox-publish.el b/lisp/org/ox-publish.el
index efc70d2..b33ba45 100644
--- a/lisp/org/ox-publish.el
+++ b/lisp/org/ox-publish.el
@@ -228,7 +228,7 @@ If you create a site-map file, adjust the sorting like this:
   `:sitemap-sort-files'
 
     The site map is normally sorted alphabetically.  You can
-    change this behaviour setting this to `anti-chronologically',
+    change this behavior setting this to `anti-chronologically',
     `chronologically', or nil.
 
   `:sitemap-ignore-case'
diff --git a/lisp/org/ox.el b/lisp/org/ox.el
index 1327ae4..2b0978d 100644
--- a/lisp/org/ox.el
+++ b/lisp/org/ox.el
@@ -493,7 +493,7 @@ t           Allow export of math snippets."
   "The last level which is still exported as a headline.
 
 Inferior levels will usually produce itemize or enumerate lists
-when exported, but back-end behaviour may differ.
+when exported, but back-end behavior may differ.
 
 This option can also be set with the OPTIONS keyword,
 e.g. \"H:2\"."
@@ -1736,13 +1736,13 @@ Assume buffer is in Org mode.  Narrowing, if any, is 
ignored."
                      (t
                       ;; Options in `org-export-options-alist'.
                       (dolist (property (funcall find-properties key))
-                        (let ((behaviour (nth 4 (assq property options))))
+                        (let ((behavior (nth 4 (assq property options))))
                           (setq plist
                                 (plist-put
                                  plist property
                                  ;; Handle value depending on specified
                                  ;; BEHAVIOR.
-                                 (case behaviour
+                                 (case behavior
                                    (space
                                     (if (not (plist-get plist property))
                                         (org-trim val)
diff --git a/lisp/progmodes/elisp-mode.el b/lisp/progmodes/elisp-mode.el
index ef619f0..c6cab12 100644
--- a/lisp/progmodes/elisp-mode.el
+++ b/lisp/progmodes/elisp-mode.el
@@ -418,40 +418,19 @@ It can be quoted, or be inside a quoted form."
          (match-string 0 doc))))
 
 (declare-function find-library-name "find-func" (library))
-
-(defvar elisp--identifier-types '(defun defvar feature defface))
-
-(defun elisp--identifier-location (type sym)
-  (pcase (cons type sym)
-    (`(defun . ,(pred fboundp))
-     (find-definition-noselect sym nil))
-    (`(defvar . ,(pred boundp))
-     (find-definition-noselect sym 'defvar))
-    (`(defface . ,(pred facep))
-     (find-definition-noselect sym 'defface))
-    (`(feature . ,(pred featurep))
-     (require 'find-func)
-     (cons (find-file-noselect (find-library-name
-                                (symbol-name sym)))
-           1))))
+(declare-function find-function-library "find-func" (function &optional l-o v))
 
 (defun elisp--company-location (str)
-  (catch 'res
-    (let ((sym (intern-soft str)))
-      (when sym
-        (dolist (type elisp--identifier-types)
-          (let ((loc (elisp--identifier-location type sym)))
-            (and loc (throw 'res loc))))))))
-
-(defvar elisp--identifier-completion-table
-  (apply-partially #'completion-table-with-predicate
-                   obarray
-                   (lambda (sym)
-                     (or (boundp sym)
-                         (fboundp sym)
-                         (featurep sym)
-                         (symbol-plist sym)))
-                   'strict))
+  (let ((sym (intern-soft str)))
+    (cond
+     ((fboundp sym) (find-definition-noselect sym nil))
+     ((boundp sym) (find-definition-noselect sym 'defvar))
+     ((featurep sym)
+      (require 'find-func)
+      (cons (find-file-noselect (find-library-name
+                                 (symbol-name sym)))
+            0))
+     ((facep sym) (find-definition-noselect sym 'defface)))))
 
 (defun elisp-completion-at-point ()
   "Function used for `completion-at-point-functions' in `emacs-lisp-mode'."
@@ -493,8 +472,13 @@ It can be quoted, or be inside a quoted form."
                            :company-docsig #'elisp--company-doc-string
                            :company-location #'elisp--company-location))
                     ((elisp--form-quoted-p beg)
-                     ;; Don't include all symbols (bug#16646).
-                     (list nil elisp--identifier-completion-table
+                     (list nil obarray
+                           ;; Don't include all symbols (bug#16646).
+                           :predicate (lambda (sym)
+                                        (or (boundp sym)
+                                            (fboundp sym)
+                                            (featurep sym)
+                                            (symbol-plist sym)))
                            :annotation-function
                            (lambda (str) (if (fboundp (intern-soft str)) " 
<f>"))
                            :company-doc-buffer #'elisp--company-doc-buffer
@@ -572,11 +556,12 @@ It can be quoted, or be inside a quoted form."
 
 ;;; Xref backend
 
-(declare-function xref-make-buffer-location "xref" (buffer position))
+(declare-function xref-make-elisp-location "xref" (symbol type file))
 (declare-function xref-make-bogus-location "xref" (message))
 (declare-function xref-make "xref" (description location))
 
 (defun elisp-xref-find (action id)
+  (require 'find-func)
   (pcase action
     (`definitions
       (let ((sym (intern-soft id)))
@@ -585,16 +570,34 @@ It can be quoted, or be inside a quoted form."
     (`apropos
      (elisp--xref-find-apropos id))))
 
+(defun elisp--xref-identifier-location (type sym)
+  (let ((file
+         (pcase type
+           (`defun (when (fboundp sym)
+                     (let ((fun-lib
+                            (find-function-library sym)))
+                       (setq sym (car fun-lib))
+                       (cdr fun-lib))))
+           (`defvar (when (boundp sym)
+                      (or (symbol-file sym 'defvar)
+                          (help-C-file-name sym 'var))))
+           (`feature (when (featurep sym)
+                       (ignore-errors
+                         (find-library-name (symbol-name sym)))))
+           (`defface (when (facep sym)
+                       (symbol-file sym 'defface))))))
+    (when file
+      (when (string-match-p "\\.elc\\'" file)
+        (setq file (substring file 0 -1)))
+      (xref-make-elisp-location sym type file))))
+
 (defun elisp--xref-find-definitions (symbol)
   (save-excursion
     (let (lst)
-      (dolist (type elisp--identifier-types)
+      (dolist (type '(feature defface defvar defun))
         (let ((loc
                (condition-case err
-                   (let ((buf-pos (elisp--identifier-location type symbol)))
-                     (when buf-pos
-                       (xref-make-buffer-location (car buf-pos)
-                                                  (or (cdr buf-pos) 1))))
+                   (elisp--xref-identifier-location type symbol)
                  (error
                   (xref-make-bogus-location (error-message-string err))))))
           (when loc
@@ -611,8 +614,18 @@ It can be quoted, or be inside a quoted form."
             (push (elisp--xref-find-definitions sym) lst))
            (nreverse lst))))
 
+(defvar elisp--xref-identifier-completion-table
+  (apply-partially #'completion-table-with-predicate
+                   obarray
+                   (lambda (sym)
+                     (or (boundp sym)
+                         (fboundp sym)
+                         (featurep sym)
+                         (facep sym)))
+                   'strict))
+
 (defun elisp--xref-identifier-completion-table ()
-  elisp--identifier-completion-table)
+  elisp--xref-identifier-completion-table)
 
 ;;; Elisp Interaction mode
 
diff --git a/lisp/progmodes/etags.el b/lisp/progmodes/etags.el
index 0be9979..be0dabf 100644
--- a/lisp/progmodes/etags.el
+++ b/lisp/progmodes/etags.el
@@ -975,6 +975,7 @@ onto a ring and may be popped back to with \\[pop-tag-mark].
 Contrast this with the ring of marks gone to by the command.
 
 See documentation of variable `tags-file-name'."
+  (declare (obsolete xref-find-definitions-other-window "25.1"))
   (interactive (find-tag-interactive "Find tag other window: "))
 
   ;; This hair is to deal with the case where the tag is found in the
@@ -1015,6 +1016,7 @@ onto a ring and may be popped back to with 
\\[pop-tag-mark].
 Contrast this with the ring of marks gone to by the command.
 
 See documentation of variable `tags-file-name'."
+  (declare (obsolete xref-find-definitions-other-frame "25.1"))
   (interactive (find-tag-interactive "Find tag other frame: "))
   (let ((pop-up-frames t))
     (find-tag-other-window tagname next-p)))
@@ -1037,6 +1039,7 @@ onto a ring and may be popped back to with 
\\[pop-tag-mark].
 Contrast this with the ring of marks gone to by the command.
 
 See documentation of variable `tags-file-name'."
+  (declare (obsolete xref-find-apropos "25.1"))
   (interactive (find-tag-interactive "Find tag regexp: " t))
   ;; We go through find-tag-other-window to do all the display hair there.
   (funcall (if other-window 'find-tag-other-window 'find-tag)
@@ -1786,6 +1789,7 @@ Two variables control the processing we do on each file: 
the value of
 interesting (it returns non-nil if so) and `tags-loop-operate' is a form to
 evaluate to operate on an interesting file.  If the latter evaluates to
 nil, we exit; otherwise we scan the next file."
+  (declare (obsolete "use `xref-find-definitions' interface instead." "25.1"))
   (interactive)
   (let (new
        ;; Non-nil means we have finished one file
@@ -1929,6 +1933,7 @@ directory specification."
 ;;;###autoload
 (defun tags-apropos (regexp)
   "Display list of all tags in tags table REGEXP matches."
+  (declare (obsolete xref-find-apropos "25.1"))
   (interactive "sTags apropos (regexp): ")
   (with-output-to-temp-buffer "*Tags List*"
     (princ "Click mouse-2 to follow tags.\n\nTags matching regexp `")
diff --git a/lisp/progmodes/js.el b/lisp/progmodes/js.el
index 45074d3..f6a9440 100644
--- a/lisp/progmodes/js.el
+++ b/lisp/progmodes/js.el
@@ -1673,7 +1673,7 @@ This performs fontification according to 
`js--class-styles'."
     ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
     ;; point I think only * and / would be missing which could also be added,
     ;; but need care to avoid affecting the // and */ comment markers.
-    ("\\(?:^\\|[=([{,:;]\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
+    ("\\(?:^\\|[=([{,:;]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
      (1 (ignore
         (forward-char -1)
          (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?\t)))
diff --git a/lisp/progmodes/python.el b/lisp/progmodes/python.el
index 35e24e1..c46c5d6 100644
--- a/lisp/progmodes/python.el
+++ b/lisp/progmodes/python.el
@@ -69,7 +69,7 @@
 ;; Besides that only the standard CPython (2.x and 3.x) shell and
 ;; IPython are officially supported out of the box, the interaction
 ;; should support any other readline based Python shells as well
-;; (e.g. Jython and Pypy have been reported to work).  You can change
+;; (e.g. Jython and PyPy have been reported to work).  You can change
 ;; your default interpreter and commandline arguments by setting the
 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
 ;; variables.  This example enables IPython globally:
@@ -119,18 +119,24 @@
 ;; modify its behavior.
 
 ;; Shell completion: hitting tab will try to complete the current
-;; word.  Shell completion is implemented in such way that if you
-;; change the `python-shell-interpreter' it should be possible to
-;; integrate custom logic to calculate completions.  To achieve this
-;; you just need to set `python-shell-completion-setup-code' and
-;; `python-shell-completion-string-code'.  The default provided code,
-;; enables autocompletion for both CPython and IPython (and ideally
-;; any readline based Python shell).  This code depends on the
-;; readline module, so if you are using some Operating System that
-;; bundles Python without it (like Windows), installing pyreadline
-;; from URL `http://ipython.scipy.org/moin/PyReadline/Intro' should
-;; suffice.  To troubleshoot why you are not getting any completions
-;; you can try the following in your Python shell:
+;; word.  The two built-in mechanisms depend on Python's readline
+;; module: the "native" completion is tried first and is activated
+;; when `python-shell-completion-native-enable' is non-nil, the
+;; current `python-shell-interpreter' is not a member of the
+;; `python-shell-completion-native-disabled-interpreters' variable and
+;; `python-shell-completion-native-setup' succeeds; the "fallback" or
+;; "legacy" mechanism works by executing Python code in the background
+;; and enables auto-completion for shells that do not support
+;; receiving escape sequences (with some limitations, i.e. completion
+;; in blocks does not work).  The code executed for the "fallback"
+;; completion can be found in `python-shell-completion-setup-code' and
+;; `python-shell-completion-string-code' variables.  Their default
+;; values enable completion for both CPython and IPython, and probably
+;; any readline based shell (it's known to work with PyPy).  If your
+;; Python installation lacks readline (like CPython for Windows),
+;; installing pyreadline (URL `http://ipython.org/pyreadline.html')
+;; should suffice.  To troubleshoot why you are not getting any
+;; completions, you can try the following in your Python shell:
 
 ;; >>> import readline, rlcompleter
 
@@ -256,6 +262,7 @@
 (defvar outline-heading-end-regexp)
 
 (autoload 'comint-mode "comint")
+(autoload 'help-function-arglist "help-fns")
 
 ;;;###autoload
 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'")  'python-mode))
@@ -395,7 +402,18 @@
                                          (* ?\\ ?\\) (any ?\' ?\")))
                                 (* ?\\ ?\\)
                                 ;; Match single or triple quotes of any kind.
-                                (group (or  "\"" "\"\"\"" "'" "'''"))))))
+                                (group (or  "\"" "\"\"\"" "'" "'''")))))
+      (coding-cookie . ,(rx line-start ?# (* space)
+                            (or
+                             ;; # coding=<encoding name>
+                             (: "coding" (or ?: ?=) (* space) (group-n 1 (+ 
(or word ?-))))
+                             ;; # -*- coding: <encoding name> -*-
+                             (: "-*-" (* space) "coding:" (* space)
+                                (group-n 1 (+ (or word ?-))) (* space) "-*-")
+                             ;; # vim: set fileencoding=<encoding name> :
+                             (: "vim:" (* space) "set" (+ space)
+                                "fileencoding" (* space) ?= (* space)
+                                (group-n 1 (+ (or word ?-))) (* space) ":")))))
     "Additional Python specific sexps for `python-rx'")
 
   (defmacro python-rx (&rest regexps)
@@ -1206,12 +1224,18 @@ the line will be re-indented automatically if needed."
            (eolp)
            ;; Avoid re-indenting on extra colon
            (not (equal ?: (char-before (1- (point)))))
-           (not (python-syntax-comment-or-string-p))
-           ;; Never re-indent at beginning of defun
-           (not (save-excursion
-                  (python-nav-beginning-of-statement)
-                  (python-info-looking-at-beginning-of-defun))))
-      (python-indent-line)))))
+           (not (python-syntax-comment-or-string-p)))
+      ;; Just re-indent dedenters
+      (let ((dedenter-pos (python-info-dedenter-statement-p))
+            (current-pos (point)))
+        (when dedenter-pos
+          (save-excursion
+            (goto-char dedenter-pos)
+            (python-indent-line)
+            (unless (= (line-number-at-pos dedenter-pos)
+                       (line-number-at-pos current-pos))
+              ;; Reindent region if this is a multiline statement
+              (python-indent-region dedenter-pos current-pos)))))))))
 
 
 ;;; Navigation
@@ -2087,36 +2111,18 @@ and `python-shell-output-prompt-regexp' using the 
values from
 
 (defun python-shell-get-process-name (dedicated)
   "Calculate the appropriate process name for inferior Python process.
-If DEDICATED is t and the variable `buffer-file-name' is non-nil
-returns a string with the form
-`python-shell-buffer-name'[variable `buffer-file-name'] else
-returns the value of `python-shell-buffer-name'."
-  (let ((process-name
-         (if (and dedicated
-                  buffer-file-name)
-             (format "%s[%s]" python-shell-buffer-name buffer-file-name)
-           (format "%s" python-shell-buffer-name))))
-    process-name))
+If DEDICATED is t returns a string with the form
+`python-shell-buffer-name'[`buffer-name'] else returns the value
+of `python-shell-buffer-name'."
+  (if dedicated
+      (format "%s[%s]" python-shell-buffer-name (buffer-name))
+    python-shell-buffer-name))
 
 (defun python-shell-internal-get-process-name ()
   "Calculate the appropriate process name for Internal Python process.
 The name is calculated from `python-shell-global-buffer-name' and
-a hash of all relevant global shell settings in order to ensure
-uniqueness for different types of configurations."
-  (format "%s [%s]"
-          python-shell-internal-buffer-name
-          (md5
-           (concat
-            python-shell-interpreter
-            python-shell-interpreter-args
-            python-shell--prompt-calculated-input-regexp
-            python-shell--prompt-calculated-output-regexp
-            (mapconcat #'symbol-value python-shell-setup-codes "")
-            (mapconcat #'identity python-shell-process-environment "")
-            (mapconcat #'identity python-shell-extra-pythonpaths "")
-            (mapconcat #'identity python-shell-exec-path "")
-            (or python-shell-virtualenv-root "")
-            (mapconcat #'identity python-shell-exec-path "")))))
+the `buffer-name'."
+  (format "%s[%s]" python-shell-internal-buffer-name (buffer-name)))
 
 (defun python-shell-calculate-command ()
   "Calculate the string used to execute the inferior Python process."
@@ -2256,11 +2262,9 @@ Avoids `recenter' calls until OUTPUT is completely sent."
   "Execute the forms in BODY with the shell buffer temporarily current.
 Signals an error if no shell buffer is available for current buffer."
   (declare (indent 0) (debug t))
-  (let ((shell-buffer (make-symbol "shell-buffer")))
-    `(let ((,shell-buffer (python-shell-get-buffer)))
-       (when (not ,shell-buffer)
-         (error "No inferior Python buffer available."))
-       (with-current-buffer ,shell-buffer
+  (let ((shell-process (make-symbol "shell-process")))
+    `(let ((,shell-process (python-shell-get-process-or-error)))
+       (with-current-buffer (process-buffer ,shell-process)
          ,@body))))
 
 (defvar python-shell--font-lock-buffer nil)
@@ -2472,12 +2476,12 @@ variable.
   (python-shell-accept-process-output
    (get-buffer-process (current-buffer))))
 
-(defun python-shell-make-comint (cmd proc-name &optional pop internal)
+(defun python-shell-make-comint (cmd proc-name &optional show internal)
   "Create a Python shell comint buffer.
 CMD is the Python command to be executed and PROC-NAME is the
 process name the comint buffer will get.  After the comint buffer
 is created the `inferior-python-mode' is activated.  When
-optional argument POP is non-nil the buffer is shown.  When
+optional argument SHOW is non-nil the buffer is shown.  When
 optional argument INTERNAL is non-nil this process is run on a
 buffer with a name that starts with a space, following the Emacs
 convention for temporary/internal buffers, and also makes sure
@@ -2506,16 +2510,13 @@ killed."
                 (mapconcat #'identity args " ")))
           (with-current-buffer buffer
             (inferior-python-mode))
-          (and pop (pop-to-buffer buffer t))
+          (when show (display-buffer buffer))
           (and internal (set-process-query-on-exit-flag process nil))))
       proc-buffer-name)))
 
 ;;;###autoload
 (defun run-python (&optional cmd dedicated show)
   "Run an inferior Python process.
-Input and output via buffer named after
-`python-shell-buffer-name'.  If there is a process already
-running in that buffer, just switch to it.
 
 Argument CMD defaults to `python-shell-calculate-command' return
 value.  When called interactively with `prefix-arg', it allows
@@ -2523,6 +2524,11 @@ the user to edit such value and choose whether the 
interpreter
 should be DEDICATED for the current buffer.  When numeric prefix
 arg is other than 0 or 4 do not SHOW.
 
+For a given buffer and same values of DEDICATED, if a process is
+already running for it, it will do nothing.  This means that if
+the current buffer is using a global process, the user is still
+able to switch it to use a dedicated one.
+
 Runs the hook `inferior-python-mode-hook' after
 `comint-mode-hook' is run.  (Type \\[describe-mode] in the
 process buffer for a list of commands.)"
@@ -2533,10 +2539,10 @@ process buffer for a list of commands.)"
         (y-or-n-p "Make dedicated process? ")
         (= (prefix-numeric-value current-prefix-arg) 4))
      (list (python-shell-calculate-command) nil t)))
-  (python-shell-make-comint
-   (or cmd (python-shell-calculate-command))
-   (python-shell-get-process-name dedicated) show)
-  dedicated)
+  (get-buffer-process
+   (python-shell-make-comint
+    (or cmd (python-shell-calculate-command))
+    (python-shell-get-process-name dedicated) show)))
 
 (defun run-python-internal ()
   "Run an inferior Internal Python process.
@@ -2579,6 +2585,21 @@ If current buffer is in `inferior-python-mode', return 
it."
   "Return inferior Python process for current buffer."
   (get-buffer-process (python-shell-get-buffer)))
 
+(defun python-shell-get-process-or-error (&optional interactivep)
+  "Return inferior Python process for current buffer or signal error.
+When argument INTERACTIVEP is non-nil, use `user-error' instead
+of `error' with a user-friendly message."
+  (or (python-shell-get-process)
+      (if interactivep
+          (user-error
+           "Start a Python process first with `M-x run-python' or `%s'."
+           ;; Get the binding.
+           (key-description
+            (where-is-internal
+             #'run-python overriding-local-map t)))
+        (error
+         "No inferior Python process running."))))
+
 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
   "Get or create an inferior Python process for current buffer and return it.
 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
@@ -2594,6 +2615,11 @@ be asked for their values."
         (run-python cmd dedicated show)))
     (or shell-process (python-shell-get-process))))
 
+(make-obsolete
+ #'python-shell-get-or-create-process
+ "Instead call `python-shell-get-process' and create one if returns nil."
+ "25.1")
+
 (defvar python-shell-internal-buffer nil
   "Current internal shell buffer for the current buffer.
 This is really not necessary at all for the code to work but it's
@@ -2606,12 +2632,10 @@ there for compatibility with CEDET.")
 
 (defun python-shell-internal-get-or-create-process ()
   "Get or create an inferior Internal Python process."
-  (let* ((proc-name (python-shell-internal-get-process-name))
-         (proc-buffer-name (format " *%s*" proc-name)))
-    (when (not (process-live-p proc-name))
-      (run-python-internal)
-      (setq python-shell-internal-buffer proc-buffer-name))
-    (get-buffer-process proc-buffer-name)))
+  (let ((proc-name (python-shell-internal-get-process-name)))
+    (if (process-live-p proc-name)
+        (get-process proc-name)
+      (run-python-internal))))
 
 (define-obsolete-function-alias
   'python-proc 'python-shell-internal-get-or-create-process "24.3")
@@ -2628,20 +2652,24 @@ there for compatibility with CEDET.")
               (concat (file-remote-p default-directory) "/tmp")
             temporary-file-directory))
          (temp-file-name (make-temp-file "py"))
-         (coding-system-for-write 'utf-8))
+         (coding-system-for-write (python-info-encoding)))
     (with-temp-file temp-file-name
-      (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
       (insert string)
       (delete-trailing-whitespace))
     temp-file-name))
 
-(defun python-shell-send-string (string &optional process)
-  "Send STRING to inferior Python PROCESS."
-  (interactive "sPython command: ")
-  (let ((process (or process (python-shell-get-or-create-process))))
+(defun python-shell-send-string (string &optional process msg)
+  "Send STRING to inferior Python PROCESS.
+When optional argument MSG is non-nil, forces display of a
+user-friendly message if there's no process running; defaults to
+t when called interactively."
+  (interactive
+   (list (read-string "Python command: ") nil t))
+  (let ((process (or process (python-shell-get-process-or-error msg))))
     (if (string-match ".\n+." string)   ;Multiline.
-        (let* ((temp-file-name (python-shell--save-temp-file string)))
-          (python-shell-send-file temp-file-name process temp-file-name t))
+        (let* ((temp-file-name (python-shell--save-temp-file string))
+               (file-name (or (buffer-file-name) temp-file-name)))
+          (python-shell-send-file file-name process temp-file-name t))
       (comint-send-string process string)
       (when (or (not (string-match "\n\\'" string))
                 (string-match "\n[ \t].*\n?\\'" string))
@@ -2680,7 +2708,7 @@ detecting a prompt at the end of the buffer."
 (defun python-shell-send-string-no-output (string &optional process)
   "Send STRING to PROCESS and inhibit output.
 Return the output."
-  (let ((process (or process (python-shell-get-or-create-process)))
+  (let ((process (or process (python-shell-get-process-or-error)))
         (comint-preoutput-filter-functions
          '(python-shell-output-filter))
         (python-shell-output-filter-in-progress t)
@@ -2717,12 +2745,6 @@ Returns the output.  See 
`python-shell-send-string-no-output'."
 (define-obsolete-function-alias
   'python-send-string 'python-shell-internal-send-string "24.3")
 
-(defvar python--use-fake-loc nil
-  "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
-If nil, regions of text are prepended by the corresponding number of empty
-lines and Python is told to output error messages referring to the whole
-source file.")
-
 (defun python-shell-buffer-substring (start end &optional nomain)
   "Send buffer substring from START to END formatted for shell.
 This is a wrapper over `buffer-substring' that takes care of
@@ -2732,27 +2754,32 @@ the python shell:
      \"if __name__ == '__main__'\" block will be removed.
   2. When a subregion of the buffer is sent, it takes care of
      appending extra empty lines so tracebacks are correct.
-  3. Wraps indented regions under an \"if True:\" block so the
+  3. When the region sent is a substring of the current buffer, a
+     coding cookie is added.
+  4. Wraps indented regions under an \"if True:\" block so the
      interpreter evaluates them correctly."
-  (let ((substring (buffer-substring-no-properties start end))
-        (fillstr (unless python--use-fake-loc
-                   (make-string (1- (line-number-at-pos start)) ?\n)))
-        (toplevel-block-p (save-excursion
-                            (goto-char start)
-                            (or (zerop (line-number-at-pos start))
-                                (progn
-                                  (python-util-forward-comment 1)
-                                  (zerop (current-indentation)))))))
+  (let* ((substring (buffer-substring-no-properties start end))
+         (starts-at-point-min-p (save-restriction
+                                  (widen)
+                                  (= (point-min) start)))
+         (encoding (python-info-encoding))
+         (fillstr (when (not starts-at-point-min-p)
+                    (concat
+                     (format "# -*- coding: %s -*-\n" encoding)
+                     (make-string
+                      ;; Substract 2 because of the coding cookie.
+                      (- (line-number-at-pos start) 2) ?\n))))
+         (toplevel-block-p (save-excursion
+                             (goto-char start)
+                             (or (zerop (line-number-at-pos start))
+                                 (progn
+                                   (python-util-forward-comment 1)
+                                   (zerop (current-indentation)))))))
     (with-temp-buffer
       (python-mode)
       (if fillstr (insert fillstr))
       (insert substring)
       (goto-char (point-min))
-      (unless python--use-fake-loc
-        ;; python-shell--save-temp-file adds an extra coding line, which would
-        ;; throw off the line-counts, so let's try to compensate here.
-        (if (looking-at "[ \t]*[#\n]")
-            (delete-region (point) (line-beginning-position 2))))
       (when (not toplevel-block-p)
         (insert "if True:")
         (delete-region (point) (line-end-position)))
@@ -2763,53 +2790,65 @@ the python shell:
                        (when (python-nav-if-name-main)
                          (cons (point)
                                (progn (python-nav-forward-sexp-safe)
+                                      ;; Include ending newline
+                                      (forward-line 1)
                                       (point)))))))
                ;; Oh destructuring bind, how I miss you.
                (if-name-main-start (car if-name-main-start-end))
-               (if-name-main-end (cdr if-name-main-start-end)))
+               (if-name-main-end (cdr if-name-main-start-end))
+               (fillstr (make-string
+                         (- (line-number-at-pos if-name-main-end)
+                            (line-number-at-pos if-name-main-start)) ?\n)))
           (when if-name-main-start-end
             (goto-char if-name-main-start)
             (delete-region if-name-main-start if-name-main-end)
-            (insert
-             (make-string
-              (- (line-number-at-pos if-name-main-end)
-                 (line-number-at-pos if-name-main-start)) ?\n)))))
+            (insert fillstr))))
+      ;; Ensure there's only one coding cookie in the generated string.
+      (goto-char (point-min))
+      (when (looking-at-p (python-rx coding-cookie))
+        (forward-line 1)
+        (when (looking-at-p (python-rx coding-cookie))
+          (delete-region
+           (line-beginning-position) (line-end-position))))
       (buffer-substring-no-properties (point-min) (point-max)))))
 
-(declare-function compilation-fake-loc "compile"
-                  (marker file &optional line col))
-
-(defun python-shell-send-region (start end &optional nomain)
-  "Send the region delimited by START and END to inferior Python process."
-  (interactive "r")
-  (let* ((python--use-fake-loc
-          (or python--use-fake-loc (not buffer-file-name)))
-         (string (python-shell-buffer-substring start end nomain))
-         (process (python-shell-get-or-create-process))
-         (_ (string-match "\\`\n*\\(.*\\)" string)))
-    (message "Sent: %s..." (match-string 1 string))
-    (let* ((temp-file-name (python-shell--save-temp-file string))
-           (file-name (or (buffer-file-name) temp-file-name)))
-      (python-shell-send-file file-name process temp-file-name t)
-      (unless python--use-fake-loc
-        (with-current-buffer (process-buffer process)
-          (compilation-fake-loc (copy-marker start) temp-file-name
-                                2)) ;; Not 1, because of the added coding line.
-        ))))
-
-(defun python-shell-send-buffer (&optional arg)
+(defun python-shell-send-region (start end &optional send-main msg)
+  "Send the region delimited by START and END to inferior Python process.
+When optional argument SEND-MAIN is non-nil, allow execution of
+code inside blocks delimited by \"if __name__== '__main__':\".
+When called interactively SEND-MAIN defaults to nil, unless it's
+called with prefix argument.  When optional argument MSG is
+non-nil, forces display of a user-friendly message if there's no
+process running; defaults to t when called interactively."
+  (interactive
+   (list (region-beginning) (region-end) current-prefix-arg t))
+  (let* ((string (python-shell-buffer-substring start end (not send-main)))
+         (process (python-shell-get-process-or-error msg))
+         (original-string (buffer-substring-no-properties start end))
+         (_ (string-match "\\`\n*\\(.*\\)" original-string)))
+    (message "Sent: %s..." (match-string 1 original-string))
+    (python-shell-send-string string process)))
+
+(defun python-shell-send-buffer (&optional send-main msg)
   "Send the entire buffer to inferior Python process.
-With prefix ARG allow execution of code inside blocks delimited
-by \"if __name__== '__main__':\"."
-  (interactive "P")
+When optional argument SEND-MAIN is non-nil, allow execution of
+code inside blocks delimited by \"if __name__== '__main__':\".
+When called interactively SEND-MAIN defaults to nil, unless it's
+called with prefix argument.  When optional argument MSG is
+non-nil, forces display of a user-friendly message if there's no
+process running; defaults to t when called interactively."
+  (interactive (list current-prefix-arg t))
   (save-restriction
     (widen)
-    (python-shell-send-region (point-min) (point-max) (not arg))))
+    (python-shell-send-region (point-min) (point-max) send-main msg)))
 
-(defun python-shell-send-defun (arg)
+(defun python-shell-send-defun (&optional arg msg)
   "Send the current defun to inferior Python process.
-When argument ARG is non-nil do not include decorators."
-  (interactive "P")
+When argument ARG is non-nil do not include decorators.  When
+optional argument MSG is non-nil, forces display of a
+user-friendly message if there's no process running; defaults to
+t when called interactively."
+  (interactive (list current-prefix-arg t))
   (save-excursion
     (python-shell-send-region
      (progn
@@ -2825,42 +2864,60 @@ When argument ARG is non-nil do not include decorators."
      (progn
        (or (python-nav-end-of-defun)
            (end-of-line 1))
-       (point-marker)))))
+       (point-marker))
+     nil  ;; noop
+     msg)))
 
 (defun python-shell-send-file (file-name &optional process temp-file-name
-                                         delete)
+                                         delete msg)
   "Send FILE-NAME to inferior Python PROCESS.
 If TEMP-FILE-NAME is passed then that file is used for processing
-instead, while internally the shell will continue to use FILE-NAME.
-If DELETE is non-nil, delete the file afterwards."
-  (interactive "fFile to send: ")
-  (let* ((process (or process (python-shell-get-or-create-process)))
+instead, while internally the shell will continue to use
+FILE-NAME.  If TEMP-FILE-NAME and DELETE are non-nil, then
+TEMP-FILE-NAME is deleted after evaluation is performed.  When
+optional argument MSG is non-nil, forces display of a
+user-friendly message if there's no process running; defaults to
+t when called interactively."
+  (interactive
+   (list
+    (read-file-name "File to send: ")   ; file-name
+    nil                                 ; process
+    nil                                 ; temp-file-name
+    nil                                 ; delete
+    t))                                 ; msg
+  (let* ((process (or process (python-shell-get-process-or-error msg)))
+         (encoding (with-temp-buffer
+                     (insert-file-contents
+                      (or temp-file-name file-name))
+                     (python-info-encoding)))
+         (file-name (expand-file-name
+                     (or (file-remote-p file-name 'localname)
+                         file-name)))
          (temp-file-name (when temp-file-name
                            (expand-file-name
                             (or (file-remote-p temp-file-name 'localname)
-                                temp-file-name))))
-         (file-name (or (when file-name
-                          (expand-file-name
-                           (or (file-remote-p file-name 'localname)
-                               file-name)))
-                        temp-file-name)))
-    (when (not file-name)
-      (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
+                                temp-file-name)))))
     (python-shell-send-string
      (format
-      (concat "__pyfile = open('''%s''');"
-              "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
-              "__pyfile.close()%s")
-      (or temp-file-name file-name) file-name
-      (if delete (format "; import os; os.remove('''%s''')"
-                         (or temp-file-name file-name))
-        ""))
+      (concat
+       "import codecs, os;"
+       "__pyfile = codecs.open('''%s''', encoding='''%s''');"
+       "__code = __pyfile.read().encode('''%s''');"
+       "__pyfile.close();"
+       (when (and delete temp-file-name)
+         (format "os.remove('''%s''');" temp-file-name))
+       "exec(compile(__code, '''%s''', 'exec'));")
+      (or temp-file-name file-name) encoding encoding file-name)
      process)))
 
-(defun python-shell-switch-to-shell ()
-  "Switch to inferior Python process buffer."
-  (interactive)
-  (process-buffer (python-shell-get-or-create-process)) t)
+(defun python-shell-switch-to-shell (&optional msg)
+  "Switch to inferior Python process buffer.
+When optional argument MSG is non-nil, forces display of a
+user-friendly message if there's no process running; defaults to
+t when called interactively."
+  (interactive "p")
+  (pop-to-buffer
+   (process-buffer (python-shell-get-process-or-error msg)) nil t))
 
 (defun python-shell-send-setup-code ()
   "Send all setup code for shell.
@@ -2947,6 +3004,194 @@ the full statement in the case of imports."
   "25.1"
   "Completion string code must work for (i)pdb.")
 
+(defcustom python-shell-completion-native-disabled-interpreters
+  ;; PyPy's readline cannot handle some escape sequences yet.
+  (list "pypy")
+  "List of disabled interpreters.
+When a match is found, native completion is disabled."
+  :type '(repeat string))
+
+(defcustom python-shell-completion-native-enable t
+  "Enable readline based native completion."
+  :type 'boolean)
+
+(defcustom python-shell-completion-native-output-timeout 0.01
+  "Time in seconds to wait for completion output before giving up."
+  :type 'float)
+
+(defvar python-shell-completion-native-redirect-buffer
+  " *Python completions redirect*"
+  "Buffer to be used to redirect output of readline commands.")
+
+(defun python-shell-completion-native-interpreter-disabled-p ()
+  "Return non-nil if interpreter has native completion disabled."
+  (when python-shell-completion-native-disabled-interpreters
+    (string-match
+     (regexp-opt python-shell-completion-native-disabled-interpreters)
+     (file-name-nondirectory python-shell-interpreter))))
+
+(defun python-shell-completion-native-try ()
+  "Return non-nil if can trigger native completion."
+  (let ((python-shell-completion-native-enable t))
+    (python-shell-completion-native-get-completions
+     (get-buffer-process (current-buffer))
+     nil "int")))
+
+(defun python-shell-completion-native-setup ()
+  "Try to setup native completion, return non-nil on success."
+  (let ((process (python-shell-get-process)))
+    (python-shell-send-string
+     (funcall
+      'mapconcat
+      #'identity
+      (list
+       "try:"
+       "    import readline, rlcompleter"
+       ;; Remove parens on callables as it breaks completion on
+       ;; arguments (e.g. str(Ari<tab>)).
+       "    class Completer(rlcompleter.Completer):"
+       "        def _callable_postfix(self, val, word):"
+       "            return word"
+       "    readline.set_completer(Completer().complete)"
+       "    if readline.__doc__ and 'libedit' in readline.__doc__:"
+       "        readline.parse_and_bind('bind ^I rl_complete')"
+       "    else:"
+       "        readline.parse_and_bind('tab: complete')"
+       "    print ('python.el: readline is available')"
+       "except:"
+       "    print ('python.el: readline not available')")
+      "\n")
+     process)
+    (python-shell-accept-process-output process)
+    (when (save-excursion
+            (re-search-backward
+             (regexp-quote "python.el: readline is available") nil t 1))
+      (python-shell-completion-native-try))))
+
+(defun python-shell-completion-native-turn-off (&optional msg)
+  "Turn off shell native completions.
+With argument MSG show deactivation message."
+  (interactive "p")
+  (python-shell-with-shell-buffer
+    (set (make-local-variable 'python-shell-completion-native-enable) nil)
+    (when msg
+      (message "Shell native completion is disabled, using fallback"))))
+
+(defun python-shell-completion-native-turn-on (&optional msg)
+  "Turn on shell native completions.
+With argument MSG show deactivation message."
+  (interactive "p")
+  (python-shell-with-shell-buffer
+    (set (make-local-variable 'python-shell-completion-native-enable) t)
+    (python-shell-completion-native-turn-on-maybe msg)))
+
+(defun python-shell-completion-native-turn-on-maybe (&optional msg)
+  "Turn on native completions if enabled and available.
+With argument MSG show activation/deactivation message."
+  (interactive "p")
+  (python-shell-with-shell-buffer
+    (when python-shell-completion-native-enable
+      (cond
+       ((python-shell-completion-native-interpreter-disabled-p)
+        (python-shell-completion-native-turn-off msg))
+       ((python-shell-completion-native-setup)
+        (when msg
+          (message "Shell native completion is enabled.")))
+       (t (lwarn
+           '(python python-shell-completion-native-turn-on-maybe)
+           :warning
+           (concat
+            "Your `python-shell-interpreter' doesn't seem to "
+            "support readline, yet `python-shell-completion-native' "
+            (format "was `t' and %S is not part of the "
+                    (file-name-nondirectory python-shell-interpreter))
+            "`python-shell-completion-native-disabled-interpreters' "
+            "list.  Native completions have been disabled locally. "))
+          (python-shell-completion-native-turn-off msg))))))
+
+(defun python-shell-completion-native-turn-on-maybe-with-msg ()
+  "Like `python-shell-completion-native-turn-on-maybe' but force messages."
+  (python-shell-completion-native-turn-on-maybe t))
+
+(add-hook 'inferior-python-mode-hook
+          #'python-shell-completion-native-turn-on-maybe-with-msg)
+
+(defun python-shell-completion-native-toggle (&optional msg)
+  "Toggle shell native completion.
+With argument MSG show activation/deactivation message."
+  (interactive "p")
+  (python-shell-with-shell-buffer
+    (if python-shell-completion-native-enable
+        (python-shell-completion-native-turn-off msg)
+      (python-shell-completion-native-turn-on msg))
+    python-shell-completion-native-enable))
+
+(defun python-shell-completion-native-get-completions (process import input)
+  "Get completions using native readline for PROCESS.
+When IMPORT is non-nil takes precedence over INPUT for
+completion."
+  (when (and python-shell-completion-native-enable
+             (python-util-comint-last-prompt)
+             (>= (point) (cdr (python-util-comint-last-prompt))))
+    (let* ((input (or import input))
+           (original-filter-fn (process-filter process))
+           (redirect-buffer (get-buffer-create
+                             python-shell-completion-native-redirect-buffer))
+           (separators (python-rx
+                        (or whitespace open-paren close-paren)))
+           (trigger "\t\t\t")
+           (new-input (concat input trigger))
+           (input-length
+            (save-excursion
+              (+ (- (point-max) (comint-bol)) (length new-input))))
+           (delete-line-command (make-string input-length ?\b))
+           (input-to-send (concat new-input delete-line-command)))
+      ;; Ensure restoring the process filter, even if the user quits
+      ;; or there's some other error.
+      (unwind-protect
+          (with-current-buffer redirect-buffer
+            ;; Cleanup the redirect buffer
+            (delete-region (point-min) (point-max))
+            ;; Mimic `comint-redirect-send-command', unfortunately it
+            ;; can't be used here because it expects a newline in the
+            ;; command and that's exactly what we are trying to avoid.
+            (let ((comint-redirect-echo-input nil)
+                  (comint-redirect-verbose nil)
+                  (comint-redirect-perform-sanity-check nil)
+                  (comint-redirect-insert-matching-regexp nil)
+                  ;; Feed it some regex that will never match.
+                  (comint-redirect-finished-regexp "^\\'$")
+                  (comint-redirect-output-buffer redirect-buffer))
+              ;; Compatibility with Emacs 24.x.  Comint changed and
+              ;; now `comint-redirect-filter' gets 3 args.  This
+              ;; checks which version of `comint-redirect-filter' is
+              ;; in use based on its args and uses `apply-partially'
+              ;; to make it up for the 3 args case.
+              (if (= (length
+                      (help-function-arglist 'comint-redirect-filter)) 3)
+                  (set-process-filter
+                   process (apply-partially
+                            #'comint-redirect-filter original-filter-fn))
+                (set-process-filter process #'comint-redirect-filter))
+              (process-send-string process input-to-send)
+              (accept-process-output
+               process
+               python-shell-completion-native-output-timeout)
+              ;; XXX: can't use `python-shell-accept-process-output'
+              ;; here because there are no guarantees on how output
+              ;; ends.  The workaround here is to call
+              ;; `accept-process-output' until we don't find anything
+              ;; else to accept.
+              (while (accept-process-output
+                      process
+                      python-shell-completion-native-output-timeout))
+              (cl-remove-duplicates
+               (split-string
+                (buffer-substring-no-properties
+                 (point-min) (point-max))
+                separators t))))
+        (set-process-filter process original-filter-fn)))))
+
 (defun python-shell-completion-get-completions (process import input)
   "Do completion at point using PROCESS for IMPORT or INPUT.
 When IMPORT is non-nil takes precedence over INPUT for
@@ -3004,11 +3249,15 @@ using that one instead of current buffer's process."
                 last-prompt-end
               (forward-char (length (match-string-no-properties 0)))
               (point))))
-         (end (point)))
+         (end (point))
+         (completion-fn
+          (if python-shell-completion-native-enable
+              #'python-shell-completion-native-get-completions
+            #'python-shell-completion-get-completions)))
     (list start end
           (completion-table-dynamic
            (apply-partially
-            #'python-shell-completion-get-completions
+            completion-fn
             process import-statement)))))
 
 (define-obsolete-function-alias
@@ -4155,6 +4404,32 @@ operator."
                 (* whitespace) line-end))
     (string-equal "" (match-string-no-properties 1))))
 
+(defun python-info-encoding-from-cookie ()
+  "Detect current buffer's encoding from its coding cookie.
+Returns the enconding as a symbol."
+  (let ((first-two-lines
+         (save-excursion
+           (save-restriction
+             (widen)
+             (goto-char (point-min))
+             (forward-line 2)
+             (buffer-substring-no-properties
+              (point)
+              (point-min))))))
+    (when (string-match (python-rx coding-cookie) first-two-lines)
+      (intern (match-string-no-properties 1 first-two-lines)))))
+
+(defun python-info-encoding ()
+  "Return encoding for file.
+Try `python-info-encoding-from-cookie', if none is found then
+default to utf-8."
+  ;; If no enconding is defined, then it's safe to use UTF-8: Python 2
+  ;; uses ASCII as default while Python 3 uses UTF-8.  This means that
+  ;; in the worst case escenario python.el will make things work for
+  ;; Python 2 files with unicode data and no encoding defined.
+  (or (python-info-encoding-from-cookie)
+      'utf-8))
+
 
 ;;; Utility functions
 
diff --git a/lisp/progmodes/sh-script.el b/lisp/progmodes/sh-script.el
index 524749d..904e9df 100644
--- a/lisp/progmodes/sh-script.el
+++ b/lisp/progmodes/sh-script.el
@@ -2374,7 +2374,7 @@ Calls the value of `sh-set-shell-hook' if set."
            (sh-make-vars-local))
        (message "Indentation setup for shell type %s" sh-shell))
     (message "No indentation for this shell type.")
-    (setq indent-line-function 'sh-basic-indent-line))
+    (setq-local indent-line-function 'sh-basic-indent-line))
   (when font-lock-mode
     (setq font-lock-set-defaults nil)
     (font-lock-set-defaults)
diff --git a/lisp/progmodes/xref.el b/lisp/progmodes/xref.el
index 21c0d6a..f3dc4bd 100644
--- a/lisp/progmodes/xref.el
+++ b/lisp/progmodes/xref.el
@@ -136,6 +136,31 @@ actual location is not known.")
 
 (defmethod xref-location-group ((_ xref-bogus-location)) "(No location)")
 
+;; This should be in elisp-mode.el, but it's preloaded, and we can't
+;; preload defclass and defmethod (at least, not yet).
+(defclass xref-elisp-location (xref-location)
+  ((symbol :type symbol :initarg :symbol)
+   (type   :type symbol :initarg :type)
+   (file   :type string :initarg :file
+           :reader xref-location-group))
+  :documentation "Location of an Emacs Lisp symbol definition.")
+
+(defun xref-make-elisp-location (symbol type file)
+  (make-instance 'xref-elisp-location :symbol symbol :type type :file file))
+
+(defmethod xref-location-marker ((l xref-elisp-location))
+  (with-slots (symbol type file) l
+    (let ((buffer-point
+           (pcase type
+             (`defun (find-function-search-for-symbol symbol nil file))
+             ((or `defvar `defface)
+              (find-function-search-for-symbol symbol type file))
+             (`feature
+              (cons (find-file-noselect file) 1)))))
+      (with-current-buffer (car buffer-point)
+        (goto-char (or (cdr buffer-point) (point-min)))
+        (point-marker)))))
+
 
 ;;; Cross-reference
 
@@ -442,7 +467,8 @@ Return an alist of the form ((FILENAME . (XREF ...)) ...)."
 ;;;###autoload
 (defun xref-find-definitions (identifier)
   "Find the definition of the identifier at point.
-With prefix argument, prompt for the identifier."
+With prefix argument or when there's no identifier at point,
+prompt for it."
   (interactive (list (xref--read-identifier "Find definitions of: ")))
   (xref--find-definitions identifier nil))
 
diff --git a/lisp/saveplace.el b/lisp/saveplace.el
index a25dba2..985a52a 100644
--- a/lisp/saveplace.el
+++ b/lisp/saveplace.el
@@ -138,6 +138,8 @@ disabled, i.e., the position is recorded for all files."
   :version "24.1"
   :type 'regexp :group 'save-place)
 
+(declare-function dired-current-directory "dired" (&optional localp))
+
 (defun toggle-save-place (&optional parg)
   "Toggle whether to save your place in this file between sessions.
 If this mode is enabled, point is recorded when you kill the buffer
@@ -153,7 +155,7 @@ file:
 \(setq-default save-place t)"
   (interactive "P")
   (if (not (or buffer-file-name (and (derived-mode-p 'dired-mode)
-                                    dired-directory)))
+                                    (dired-current-directory))))
       (message "Buffer `%s' not visiting a file or directory" (buffer-name))
     (setq save-place (if parg
                          (> (prefix-numeric-value parg) 0)
@@ -172,12 +174,13 @@ file:
   ;; file.  If not, do so, then feel free to modify the alist.  It
   ;; will be saved again when Emacs is killed.
   (or save-place-loaded (load-save-place-alist-from-file))
-  (let ((item (or buffer-file-name
-                  (and (derived-mode-p 'dired-mode)
-                      dired-directory
-                      (expand-file-name (if (consp dired-directory)
-                                            (car dired-directory)
-                                          dired-directory))))))
+  (let* ((directory (and (derived-mode-p 'dired-mode)
+                        (dired-current-directory)))
+        (item (or buffer-file-name
+                  (and directory
+                       (expand-file-name (if (consp directory)
+                                             (car directory)
+                                           directory))))))
     (when (and item
                (or (not save-place-ignore-files-regexp)
                    (not (string-match save-place-ignore-files-regexp
@@ -186,8 +189,7 @@ file:
             (position (cond ((eq major-mode 'hexl-mode)
                             (with-no-warnings
                               (1+ (hexl-current-address))))
-                           ((and (derived-mode-p 'dired-mode)
-                                 dired-directory)
+                           ((and (derived-mode-p 'dired-mode) directory)
                             (let ((filename (dired-get-filename nil t)))
                               (if filename
                                   `((dired-filename . ,filename))
@@ -305,7 +307,7 @@ may have changed) back to `save-place-alist'."
        ;; save-place checks buffer-file-name too, but we can avoid
        ;; overhead of function call by checking here too.
        (and (or buffer-file-name (and (derived-mode-p 'dired-mode)
-                                      dired-directory))
+                                      (dired-current-directory)))
             (save-place-to-alist))
        (setq buf-list (cdr buf-list))))))
 
@@ -325,19 +327,21 @@ may have changed) back to `save-place-alist'."
 (defun save-place-dired-hook ()
   "Position the point in a Dired buffer."
   (or save-place-loaded (load-save-place-alist-from-file))
-  (let ((cell (assoc (and (derived-mode-p 'dired-mode)
-                         dired-directory
-                         (expand-file-name (if (consp dired-directory)
-                                               (car dired-directory)
-                                             dired-directory)))
-                    save-place-alist)))
+  (let* ((directory (and (derived-mode-p 'dired-mode)
+                        (dired-current-directory)))
+        (cell (assoc (and directory
+                          (expand-file-name (if (consp directory)
+                                                (car directory)
+                                              directory)))
+                     save-place-alist)))
     (if cell
         (progn
           (or revert-buffer-in-progress-p
-              (if (integerp (cdr cell))
-                 (goto-char (cdr cell))
-               (and (assq 'dired-filename (cdr cell))
-                    (dired-goto-file (cdr (assq 'dired-filename (cdr 
cell)))))))
+              (cond
+              ((integerp (cdr cell))
+               (goto-char (cdr cell)))
+              ((and (listp (cdr cell)) (assq 'dired-filename (cdr cell)))
+               (dired-goto-file (cdr (assq 'dired-filename (cdr cell)))))))
           ;; and make sure it will be saved again for later
           (setq save-place t)))))
 
diff --git a/lisp/simple.el b/lisp/simple.el
index 0fcd5db..b436dd7 100644
--- a/lisp/simple.el
+++ b/lisp/simple.el
@@ -1667,7 +1667,6 @@ invoking, give a prefix argument to 
`execute-extended-command'."
     (let ((prefix-arg prefixarg))
       (command-execute function 'record))
     ;; If enabled, show which key runs this command.
-    ;; (when binding
     ;; But first wait, and skip the message if there is input.
     (let* ((waited
             ;; If this command displayed something in the echo area;
@@ -1675,10 +1674,11 @@ invoking, give a prefix argument to 
`execute-extended-command'."
             ;; FIXME: Wait *after* running post-command-hook!
             ;; FIXME: Don't wait if execute-extended-command--shorter won't
             ;; find a better answer anyway!
-            (sit-for (cond
-                      ((zerop (length (current-message))) 0)
-                      ((numberp suggest-key-bindings) suggest-key-bindings)
-                      (t 2)))))
+            (when suggest-key-bindings
+              (sit-for (cond
+                        ((zerop (length (current-message))) 0)
+                        ((numberp suggest-key-bindings) suggest-key-bindings)
+                        (t 2))))))
       (when (and waited (not (consp unread-command-events)))
         (unless (or binding executing-kbd-macro (not (symbolp function))
                     (<= (length (symbol-name function)) 2))
diff --git a/lisp/startup.el b/lisp/startup.el
index 8e981bb..0c5e66a 100644
--- a/lisp/startup.el
+++ b/lisp/startup.el
@@ -358,6 +358,8 @@ this variable usefully is to set it while building and 
dumping Emacs."
   :set (lambda (_variable _value)
          (error "Customizing `site-run-file' does not work")))
 
+(make-obsolete-variable 'system-name "use (system-name) instead" "25.1")
+
 (defcustom mail-host-address nil
   "Name of this machine, for purposes of naming users.
 If non-nil, Emacs uses this instead of `system-name' when constructing
diff --git a/lisp/subr.el b/lisp/subr.el
index 6ce02b7..53ad272 100644
--- a/lisp/subr.el
+++ b/lisp/subr.el
@@ -2166,7 +2166,7 @@ keyboard-quit events while waiting for a valid input."
     char))
 
 (defun sit-for (seconds &optional nodisp obsolete)
-  "Perform redisplay, then wait for SECONDS seconds or until input is 
available.
+  "Redisplay, then wait for SECONDS seconds.  Stop when input is available.
 SECONDS may be a floating-point value.
 \(On operating systems that do not support waiting for fractions of a
 second, floating-point values are rounded down to the nearest integer.)
@@ -2184,7 +2184,7 @@ floating point support."
   (declare (advertised-calling-convention (seconds &optional nodisp) "22.1"))
   ;; This used to be implemented in C until the following discussion:
   ;; http://lists.gnu.org/archive/html/emacs-devel/2006-07/msg00401.html
-  ;; Then it was moved to C using an implementation based on an idle timer,
+  ;; Then it was moved here using an implementation based on an idle timer,
   ;; which was then replaced by the use of read-event.
   (if (numberp nodisp)
       (setq seconds (+ seconds (* 1e-3 nodisp))
diff --git a/lisp/textmodes/tex-mode.el b/lisp/textmodes/tex-mode.el
index 1993ff1..12e7fda 100644
--- a/lisp/textmodes/tex-mode.el
+++ b/lisp/textmodes/tex-mode.el
@@ -1300,18 +1300,48 @@ Inserts the value of `tex-open-quote' (normally ``) or 
`tex-close-quote'
 \(normally '') depending on the context.  With prefix argument, always
 inserts \" characters."
   (interactive "*P")
+  ;; Discover if we'll be inserting normal double quotes.
+  ;;
   (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
-         (eq (get-text-property (point) 'face) 'tex-verbatim)
-         (save-excursion
-           (backward-char (length tex-open-quote))
-           (when (or (looking-at (regexp-quote tex-open-quote))
-                     (looking-at (regexp-quote tex-close-quote)))
-             (delete-char (length tex-open-quote))
-             t)))
+          (eq (get-text-property (point) 'face) 'tex-verbatim)
+          ;; Discover if a preceding occurrence of `tex-open-quote'
+          ;; should be morphed to a normal double quote.
+          ;;
+          (and (>= (point) (+ (point-min) (length tex-open-quote)))
+               (save-excursion
+                 (backward-char (length tex-open-quote))
+                 (when (or (looking-at (regexp-quote tex-open-quote))
+                           (looking-at (regexp-quote tex-close-quote)))
+                   (delete-char (length tex-open-quote))
+                   (when (looking-at (regexp-quote tex-close-quote))
+                     (delete-char (length tex-close-quote)))
+                   t))))
+      ;; Insert the normal quote (eventually letting
+      ;; `electric-pair-mode' do its thing).
+      ;;
       (self-insert-command (prefix-numeric-value arg))
-    (insert (if (or (memq (char-syntax (preceding-char)) '(?\( ?> ?\s))
-                    (memq (preceding-char) '(?~)))
-               tex-open-quote tex-close-quote))))
+    ;; We'll be inserting fancy TeX quotes, but consider and imitate
+    ;; `electric-pair-mode''s two behaviors: pair-insertion and
+    ;; region wrapping.
+    ;;
+    (if (and electric-pair-mode (use-region-p))
+        (let* ((saved (point-marker)))
+          (goto-char (mark))
+          (insert (if (> saved (mark)) tex-open-quote tex-close-quote))
+          (goto-char saved)
+          (insert (if (> saved (mark)) tex-close-quote tex-open-quote)))
+      (if (or (memq (char-syntax (preceding-char)) '(?\( ?> ?\s))
+              (memq (preceding-char) '(?~)))
+          (if electric-pair-mode
+              (if (looking-at (regexp-quote tex-close-quote))
+                  (forward-char (length tex-close-quote))
+                (insert tex-open-quote)
+                (insert tex-close-quote)
+                (backward-char (length tex-close-quote)))
+            (insert tex-open-quote))
+        (if (looking-at (regexp-quote tex-close-quote))
+            (forward-char (length tex-close-quote))
+          (insert tex-close-quote))))))
 
 (defun tex-validate-buffer ()
   "Check current buffer for paragraphs containing mismatched braces or $s.
diff --git a/lisp/vc/compare-w.el b/lisp/vc/compare-w.el
index 3b8293c..454139e 100644
--- a/lisp/vc/compare-w.el
+++ b/lisp/vc/compare-w.el
@@ -30,6 +30,8 @@
 
 ;;; Code:
 
+(require 'diff-mode)                    ; For diff faces.
+
 (defgroup compare-windows nil
   "Compare text between windows."
   :prefix "compare-"
@@ -128,11 +130,19 @@ out all highlighting later with the command 
`compare-windows-dehighlight'."
   :group 'compare-windows
   :version "22.1")
 
-(defface compare-windows
-  '((t :inherit lazy-highlight))
-  "Face for highlighting of compare-windows difference regions."
+(defface compare-windows-removed
+  '((t :inherit diff-removed))
+  "Face for highlighting of compare-windows removed regions."
   :group 'compare-windows
-  :version "22.1")
+  :version "25.1")
+
+(defface compare-windows-added
+  '((t :inherit diff-added))
+  "Face for highlighting of compare-windows added regions."
+  :group 'compare-windows
+  :version "25.1")
+
+(define-obsolete-face-alias 'compare-windows 'compare-windows-added "25.1")
 
 (defvar compare-windows-overlay1 nil)
 (defvar compare-windows-overlay2 nil)
@@ -158,7 +168,8 @@ then try to get a window on an iconified frame, and finally
 consider all existing frames."
   (or (get-mru-window 'visible t t)
       (get-mru-window 0 t t)
-      (get-mru-window t t t)))
+      (get-mru-window t t t)
+      (error "No other window")))
 
 (defun compare-windows-get-next-window ()
   "Return the window next in the cyclic ordering of windows.
@@ -393,13 +404,13 @@ on third call it again advances points to the next 
difference and so on."
     (if compare-windows-overlay1
         (move-overlay compare-windows-overlay1 beg1 end1 b1)
       (setq compare-windows-overlay1 (make-overlay beg1 end1 b1))
-      (overlay-put compare-windows-overlay1 'face 'compare-windows)
+      (overlay-put compare-windows-overlay1 'face 'compare-windows-added)
       (overlay-put compare-windows-overlay1 'priority 1000))
     (overlay-put compare-windows-overlay1 'window w1)
     (if compare-windows-overlay2
         (move-overlay compare-windows-overlay2 beg2 end2 b2)
       (setq compare-windows-overlay2 (make-overlay beg2 end2 b2))
-      (overlay-put compare-windows-overlay2 'face 'compare-windows)
+      (overlay-put compare-windows-overlay2 'face 'compare-windows-removed)
       (overlay-put compare-windows-overlay2 'priority 1000))
     (overlay-put compare-windows-overlay2 'window w2)
     (if (not (eq compare-windows-highlight 'persistent))
diff --git a/lisp/vc/vc-dir.el b/lisp/vc/vc-dir.el
index 4955c5a..08eb778 100644
--- a/lisp/vc/vc-dir.el
+++ b/lisp/vc/vc-dir.el
@@ -169,6 +169,9 @@ See `run-hooks'."
     (define-key map [ise]
       '(menu-item "Isearch Files..." vc-dir-isearch
                  :help "Incremental search a string in the marked files"))
+    (define-key map [display]
+      '(menu-item "Display in Other Window" vc-dir-display-file
+                 :help "Display the file on the current line, in another 
window"))
     (define-key map [open-other]
       '(menu-item "Open in Other Window" vc-dir-find-file-other-window
                  :help "Find the file on the current line, in another window"))
@@ -273,6 +276,7 @@ See `run-hooks'."
     (define-key map "e" 'vc-dir-find-file) ; dired-mode compatibility
     (define-key map "\C-m" 'vc-dir-find-file)
     (define-key map "o" 'vc-dir-find-file-other-window)
+    (define-key map "\C-o" 'vc-dir-display-file)
     (define-key map "\C-c\C-c" 'vc-dir-kill-dir-status-process)
     (define-key map [down-mouse-3] 'vc-dir-menu)
     (define-key map [mouse-2] 'vc-dir-toggle-mark)
@@ -755,6 +759,13 @@ that share the same state."
   (if event (posn-set-point (event-end event)))
   (find-file-other-window (vc-dir-current-file)))
 
+(defun vc-dir-display-file (&optional event)
+  "Display the file on the current line, in another window."
+  (interactive (list last-nonmenu-event))
+  (if event (posn-set-point (event-end event)))
+  (display-buffer (find-file-noselect (vc-dir-current-file))
+                 t))
+
 (defun vc-dir-isearch ()
   "Search for a string through all marked buffers using Isearch."
   (interactive)
diff --git a/lisp/vc/vc-git.el b/lisp/vc/vc-git.el
index 65f683c..1700bef1 100644
--- a/lisp/vc/vc-git.el
+++ b/lisp/vc/vc-git.el
@@ -371,8 +371,7 @@ or an empty string if none."
     (goto-char (point-min))
     (pcase stage
       (`update-index
-       (setq next-stage (if (vc-git--empty-db-p) 'ls-files-added
-                          (if files 'ls-files-up-to-date 'diff-index))))
+       (setq next-stage (if (vc-git--empty-db-p) 'ls-files-added 'diff-index)))
       (`ls-files-added
        (setq next-stage 'ls-files-unknown)
        (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 
0\t\\([^\0]+\\)\0" nil t)
@@ -381,7 +380,7 @@ or an empty string if none."
            (push (list name 'added (vc-git-create-extra-fileinfo 0 new-perm))
                  result))))
       (`ls-files-up-to-date
-       (setq next-stage 'diff-index)
+       (setq next-stage 'ls-files-unknown)
        (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 
0\t\\([^\0]+\\)\0" nil t)
          (let ((perm (string-to-number (match-string 1) 8))
                (name (match-string 2)))
@@ -400,7 +399,7 @@ or an empty string if none."
                      (vc-git-create-extra-fileinfo 0 0))
                result)))
       (`diff-index
-       (setq next-stage 'ls-files-unknown)
+       (setq next-stage (if files 'ls-files-up-to-date 'ls-files-unknown))
        (while (re-search-forward
                ":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 
[0-9a-f]\\{40\\} 
\\(\\([ADMUT]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
                nil t 1)
diff --git a/lisp/window.el b/lisp/window.el
index 2b593c3..21bd2c5 100644
--- a/lisp/window.el
+++ b/lisp/window.el
@@ -237,7 +237,12 @@ displays the buffer specified by BUFFER-OR-NAME before 
running BODY."
              (standard-output ,buffer)
              ,window ,value)
         (with-current-buffer ,buffer
-          (setq ,window (temp-buffer-window-show ,buffer ,vaction)))
+          (setq ,window (temp-buffer-window-show
+                         ,buffer
+                         ;; Remove window-height when it's handled below.
+                         (if (functionp (cdr (assq 'window-height (cdr 
,vaction))))
+                             (assq-delete-all 'window-height (copy-sequence 
,vaction))
+                           ,vaction))))
 
         (let ((inhibit-read-only t)
               (inhibit-modification-hooks t))
diff --git a/src/ChangeLog b/src/ChangeLog
index 72601fe..85eb113 100644
--- a/src/ChangeLog
+++ b/src/ChangeLog
@@ -1,3 +1,121 @@
+2014-12-31  Paul Eggert  <address@hidden>
+
+       Simplify setfattr use by assuming GNU make
+       * Makefile.in (PAXCTL_if_present, SETFATTR_if_present): New macros.
+       (emacs$(EXEEXT), temacs$(EXEEXT), bootstrap-emacs$(EXEEXT)): Use them.
+       Simplify by using GNU make rather than shell conditionals,
+       by using ln -f rather than rm -f followed by ln,
+       and by preferring $@ to spelling out the destination.
+
+2014-12-29  Eli Zaretskii  <address@hidden>
+
+       * sysdep.c [WINDOWSNT]: Include sys/socket.h, without which this
+       file doesn't compile on MS-Windows.
+
+2014-12-28  Paul Eggert  <address@hidden>
+
+       Fix produce_composite_width typo
+       * term.c (produce_composite_glyph):
+       Fix typo that confused number of columns for pixel width.
+
+2014-12-28  Paul Eggert  <address@hidden>
+
+       Wrap dll functions more simply
+       * decompress.c, gnutls.c, image.c, xml.c:
+       If WINDOWSNT, use '#define FOO fn_FOO' to wrap dll functions,
+       rather than the inverse when not WINDOWSNT.  This isolates the
+       fn_* business into the WINDOWSNT-specific section of the code,
+       which makes it easier to maintain the generic code.
+       * decompress.c (DEF_ZLIB_FN, LOAD_ZLIB_FN):
+       * gnutls.c (DEF_GNUTLS_FN, LOAD_GNUTLS_FN):
+       * image.c (DEF_IMGLIB_FN, LOAD_IMGLIB_FN):
+       * xml.c (DEF_XML2_FN, LOAD_XML2_FN):
+       Remove.  All uses replaced by DEF_DLL_FN.
+       * decompress.c (inflateInit2): Remove; no longer needed.
+       * w32.h (DEF_DLL_FN, LOAD_DLL_FN): New macros.
+
+       Port memory-full checking to GnuTLS 3.3
+       Instead of using gnutls_global_set_mem_functions, check every call
+       to a GnuTLS function that might return an indication of memory
+       exhaustion.  Suggested by Dmitry Antipov in:
+       http://lists.gnu.org/archive/html/emacs-devel/2014-12/msg02056.html
+       * gnutls.c (gnutls_global_set_mem_functions) [WINDOWSNT]: Remove.
+       (init_gnutls_functions): Do not load gnutls_global_set_mem_functions.
+       (fn_gnutls_global_set_mem_functions) [!WINDOWSNT]: Remove.
+       All uses removed.
+       (check_memory_full): New function.
+       (emacs_gnutls_handshake, emacs_gnutls_handle_error)
+       (gnutls_make_error, gnutls_certificate_details, Fgnutls_peer_status)
+       (Fgnutls_boot): Use it.
+       (emacs_gnutls_global_init): Avoid gnutls_global_set_mem_functions.
+
+2014-12-27  Paul Eggert  <address@hidden>
+
+       Fix parse_settings to match internal documentation
+       * xsettings.c (parse_settings): Return the number of settings seen.
+       Count the settings changes accurately.
+       (read_settings): Don't confuse number of settings changes with
+       the return code from XGetWindowProperty.
+
+2014-12-27  Eli Zaretskii  <address@hidden>
+
+       * xdisp.c (set_iterator_to_next) <GET_FROM_STRING>: Limit search in
+       composition_compute_stop_pos to the number of characters in the
+       string.  (Bug#19435)
+       <GET_FROM_BUFFER, GET_FROM_STRING>: Simplify code.
+
+       * composite.c (composition_compute_stop_pos): If no composition
+       was found in a string before ENDPOS, and ENDPOS is the string end,
+       no need to back up to a safe point.
+
+       * dispextern.h (struct it) <end_charpos>: Improve commentary.
+
+2014-12-27  Jan Djärv  <address@hidden>
+
+       * nsimage.m (allocInitFromFile:): Initialize bmRep.
+       (dealloc): Release bmRep.
+        (setPixmapData): Make bmRep local so class member is not
+        set (Bug#19133).
+       (setPixmapData): Rename local variable bmRep to avoid compiler
+       warning.
+
+2014-12-27  Jan Djärv  <address@hidden>
+
+       * xterm.c (do_ewmh_fullscreen): Don't remove maximized_horz/vert
+       when going to fullscreen (Bug#0x180004f).
+
+2014-12-27  Stefan Monnier  <address@hidden>
+
+       * buffer.c (syms_of_buffer) <Vafter_change_functions>: fix docstring.
+
+2014-12-27  Eli Zaretskii  <address@hidden>
+
+       * gnutls.c (gnutls_init): Fix deprecation warning from GCC.
+
+2014-12-26  Paul Eggert  <address@hidden>
+
+       Use bool for boolean in xselect.c, xsettings.c
+       * xselect.c (x_get_local_selection, struct selection_data)
+       (x_selection_request_lisp_error, struct prop_location)
+       (x_handle_selection_request, x_convert_selection)
+       (waiting_for_other_props_on_window, expect_property_change)
+       (wait_for_property_change, x_handle_property_notify)
+       (x_get_foreign_selection, x_get_window_property)
+       (receive_incremental_selection)
+       (x_get_window_property_as_lisp_data)
+       (lisp_data_to_selection_data, Fx_get_selection_internal)
+       (x_send_client_event):
+       * xselect.c, xterm.h (x_handle_dnd_message):
+       * xsettings.c (dpyinfo_valid, parse_settings, read_settings)
+       (apply_xft_settings, read_and_apply_settings)
+       (xft_settings_event, init_gsettings, init_xsettings)
+       (syms_of_xsettings):
+       Use bool for boolean.
+       * xselect.c (x_get_window_property): Omit last arg, which was an
+       unused boolean.
+       * xsettings.c (apply_xft_settings): Remove 2nd arg, which was
+       always true.  All callers changed.
+
 2014-12-26  Eli Zaretskii  <address@hidden>
 
        * w32proc.c (sys_spawnve, get_lcid_callback): Use strcpy instead
@@ -894,6 +1012,8 @@
        * fileio.c (Fexpand_file_name): Use make_unibyte_string, not
        build_string, when importing a home directory.  (Bug#18873)
 
+2014-12-27  Eli Zaretskii  <address@hidden>
+
        * dispnew.c (buffer_posn_from_coords):
        Use WINDOW_WANTS_HEADER_LINE_P, not WINDOW_WANTS_MODELINE_P, to
        account for the header-line height.  (Bug#18839)
diff --git a/src/Makefile.in b/src/Makefile.in
index 930cca3..0ea4530 100644
--- a/src/Makefile.in
+++ b/src/Makefile.in
@@ -114,6 +114,8 @@ TEMACS_LDFLAGS = $(LD_SWITCH_SYSTEM) 
$(LD_SWITCH_SYSTEM_TEMACS)
 ## around this, newer ones setfattr.  See Bug#11398 and Bug#16343.
 PAXCTL = @PAXCTL@
 SETFATTR = @SETFATTR@
+PAXCTL_if_present = $(or $(PAXCTL),: paxctl)
+SETFATTR_if_present = $(or $(SETFATTR),: setfattr)
 
 ## Some systems define this to request special libraries.
 address@hidden@
@@ -459,17 +461,13 @@ $(srcdir)/macuvs.h 
$(lispsource)/international/charprop.el: \
 emacs$(EXEEXT): temacs$(EXEEXT) \
                 $(etc)/DOC $(lisp) $(leimdir)/leim-list.el \
                 $(lispsource)/international/charprop.el
-       if test "$(CANNOT_DUMP)" = "yes"; then \
-         rm -f emacs$(EXEEXT); \
-         ln temacs$(EXEEXT) emacs$(EXEEXT); \
-       else \
-         LC_ALL=C $(RUN_TEMACS) -batch -l loadup dump || exit 1; \
-         test "X$(PAXCTL)" = X || $(PAXCTL) -zex emacs$(EXEEXT); \
-         while test -f bootstrap-emacs$(EXEEXT); do \
-           rm -f bootstrap-emacs$(EXEEXT); \
-         done; \
-         ln emacs$(EXEEXT) bootstrap-emacs$(EXEEXT); \
-       fi
+ifeq ($(CANNOT_DUMP),yes)
+       ln -f temacs$(EXEEXT) $@
+else
+       LC_ALL=C $(RUN_TEMACS) -batch -l loadup dump
+       $(PAXCTL_if_present) -zex $@
+       ln -f $@ bootstrap-emacs$(EXEEXT)
+endif
 
 ## We run make-docfile twice because the command line may get too long
 ## on some systems.  The sed command operating on lisp.mk also reduces
@@ -527,10 +525,10 @@ temacs$(EXEEXT): $(LIBXMENU) $(ALLOBJS) \
        $(AM_V_CCLD)$(CC) $(ALL_CFLAGS) $(TEMACS_LDFLAGS) $(LDFLAGS) \
          -o temacs $(ALLOBJS) $(lib)/libgnu.a $(W32_RES_LINK) $(LIBES)
        $(MKDIR_P) $(etc)
-       test "$(CANNOT_DUMP)" = "yes" || \
-         test "X$(PAXCTL)" = X || $(PAXCTL) -r temacs$(EXEEXT)
-       test "$(CANNOT_DUMP)" = "yes" || test -z "$(SETFATTR)" || \
-         $(SETFATTR) -n user.pax.flags -v er $@
+ifneq ($(CANNOT_DUMP),yes)
+       $(PAXCTL_if_present) -r $@
+       $(SETFATTR_if_present) -n user.pax.flags -v er $@
+endif
 
 ## The following oldxmenu-related rules are only (possibly) used if
 ## HAVE_X11 && !USE_GTK, but there is no harm in always defining them.
@@ -662,14 +660,13 @@ $(lispsource)/loaddefs.el: $(VCSWITNESS) | 
bootstrap-emacs$(EXEEXT)
 ## files from loadup.el in source form.
 bootstrap-emacs$(EXEEXT): temacs$(EXEEXT)
        $(MAKE) -C ../lisp update-subdirs
-       if test "$(CANNOT_DUMP)" = "yes"; then \
-         rm -f bootstrap-emacs$(EXEEXT); \
-         ln temacs$(EXEEXT) bootstrap-emacs$(EXEEXT); \
-       else \
-         $(RUN_TEMACS) --batch --load loadup bootstrap || exit 1; \
-         test "X$(PAXCTL)" = X || $(PAXCTL) -zex emacs$(EXEEXT); \
-         mv -f emacs$(EXEEXT) bootstrap-emacs$(EXEEXT); \
-       fi
+ifeq ($(CANNOT_DUMP),yes)
+       ln -f temacs$(EXEEXT) $@
+else
+       $(RUN_TEMACS) --batch --load loadup bootstrap
+       $(PAXCTL_if_present) -zex emacs$(EXEEXT)
+       mv -f emacs$(EXEEXT) $@
+endif
        @: Compile some files earlier to speed up further compilation.
        $(MAKE) -C ../lisp compile-first EMACS="$(bootstrap_exe)"
 
diff --git a/src/buffer.c b/src/buffer.c
index 7e424bb..4e74690 100644
--- a/src/buffer.c
+++ b/src/buffer.c
@@ -6074,9 +6074,9 @@ from happening repeatedly and making Emacs nonfunctional. 
 */);
               doc: /* List of functions to call after each text change.
 Three arguments are passed to each function: the positions of
 the beginning and end of the range of changed text,
-and the length in bytes of the pre-change text replaced by that range.
+and the length in chars of the pre-change text replaced by that range.
 \(For an insertion, the pre-change length is zero;
-for a deletion, that length is the number of bytes deleted,
+for a deletion, that length is the number of chars deleted,
 and the post-change beginning and end are at the same place.)
 
 Buffer changes made while executing the `after-change-functions'
diff --git a/src/composite.c b/src/composite.c
index 8982c90..0b52a9f 100644
--- a/src/composite.c
+++ b/src/composite.c
@@ -1032,7 +1032,8 @@ composition_compute_stop_pos (struct composition_it 
*cmp_it, ptrdiff_t charpos,
                }
            }
        }
-      if (charpos == endpos)
+      if (charpos == endpos
+         && !(STRINGP (string) && endpos == SCHARS (string)))
        {
          /* We couldn't find a composition point before ENDPOS.  But,
             some character after ENDPOS may be composed with
diff --git a/src/decompress.c b/src/decompress.c
index 24ce852..f86aa6f 100644
--- a/src/decompress.c
+++ b/src/decompress.c
@@ -31,26 +31,14 @@ along with GNU Emacs.  If not, see 
<http://www.gnu.org/licenses/>.  */
 static Lisp_Object Qzlib_dll;
 
 #ifdef WINDOWSNT
-#include <windows.h>
-#include "w32.h"
+# include <windows.h>
+# include "w32.h"
 
-/* Macro for defining functions that will be loaded from the zlib DLL.  */
-#define DEF_ZLIB_FN(rettype,func,args) static rettype (FAR CDECL 
*fn_##func)args
-
-/* Macro for loading zlib functions from the library.  */
-#define LOAD_ZLIB_FN(lib,func) {                                       \
-    fn_##func = (void *) GetProcAddress (lib, #func);                  \
-    if (!fn_##func) return false;                                      \
-  }
-
-DEF_ZLIB_FN (int, inflateInit2_,
-            (z_streamp strm, int  windowBits, const char *version, int 
stream_size));
-
-DEF_ZLIB_FN (int, inflate,
-            (z_streamp strm, int flush));
-
-DEF_ZLIB_FN (int, inflateEnd,
-            (z_streamp strm));
+DEF_DLL_FN (int, inflateInit2_,
+           (z_streamp strm, int windowBits, const char *version,
+            int stream_size));
+DEF_DLL_FN (int, inflate, (z_streamp strm, int flush));
+DEF_DLL_FN (int, inflateEnd, (z_streamp strm));
 
 static bool zlib_initialized;
 
@@ -62,20 +50,19 @@ init_zlib_functions (void)
   if (!library)
     return false;
 
-  LOAD_ZLIB_FN (library, inflateInit2_);
-  LOAD_ZLIB_FN (library, inflate);
-  LOAD_ZLIB_FN (library, inflateEnd);
+  LOAD_DLL_FN (library, inflateInit2_);
+  LOAD_DLL_FN (library, inflate);
+  LOAD_DLL_FN (library, inflateEnd);
   return true;
 }
 
-#define fn_inflateInit2(strm, windowBits) \
-        fn_inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
-
-#else /* !WINDOWSNT */
+# undef inflate
+# undef inflateEnd
+# undef inflateInit2_
 
-#define fn_inflateInit2                inflateInit2
-#define fn_inflate             inflate
-#define fn_inflateEnd          inflateEnd
+# define inflate fn_inflate
+# define inflateEnd fn_inflateEnd
+# define inflateInit2_ fn_inflateInit2_
 
 #endif /* WINDOWSNT */
 
@@ -90,7 +77,7 @@ static void
 unwind_decompress (void *ddata)
 {
   struct decompress_unwind_data *data = ddata;
-  fn_inflateEnd (data->stream);
+  inflateEnd (data->stream);
 
   /* Delete any uncompressed data already inserted on error.  */
   if (data->start)
@@ -167,7 +154,7 @@ This function can be called only in unibyte buffers.  */)
 
   /* The magic number 32 apparently means "autodetect both the gzip and
      zlib formats" according to zlib.h.  */
-  if (fn_inflateInit2 (&stream, MAX_WBITS + 32) != Z_OK)
+  if (inflateInit2 (&stream, MAX_WBITS + 32) != Z_OK)
     return Qnil;
 
   unwind_data.start = iend;
@@ -197,7 +184,7 @@ This function can be called only in unibyte buffers.  */)
       stream.avail_in = avail_in;
       stream.next_out = GPT_ADDR;
       stream.avail_out = avail_out;
-      inflate_status = fn_inflate (&stream, Z_NO_FLUSH);
+      inflate_status = inflate (&stream, Z_NO_FLUSH);
       pos_byte += avail_in - stream.avail_in;
       decompressed = avail_out - stream.avail_out;
       insert_from_gap (decompressed, decompressed, 0);
diff --git a/src/dispextern.h b/src/dispextern.h
index 10a567e..908b62b 100644
--- a/src/dispextern.h
+++ b/src/dispextern.h
@@ -2252,7 +2252,10 @@ struct it
   ptrdiff_t base_level_stop;
 
   /* Maximum string or buffer position + 1.  ZV when iterating over
-     current_buffer.  */
+     current_buffer.  When iterating over a string in display_string,
+     this can be smaller or greater than the number of string
+     characters, depending on the values of PRECISION and FIELD_WIDTH
+     with which display_string was called.  */
   ptrdiff_t end_charpos;
 
   /* C string to iterate over.  Non-null means get characters from
diff --git a/src/editfns.c b/src/editfns.c
index 430c4c9..2a7dd92 100644
--- a/src/editfns.c
+++ b/src/editfns.c
@@ -93,6 +93,17 @@ static char const *initial_tz;
    It is OK (though a bit slower) if the user chooses this value.  */
 static char dump_tz_string[] = "TZ=UtC0";
 
+/* The cached value of Vsystem_name.  This is used only to compare it
+   to Vsystem_name, so it need not be visible to the GC.  */
+static Lisp_Object cached_system_name;
+
+static void
+init_and_cache_system_name (void)
+{
+  init_system_name ();
+  cached_system_name = Vsystem_name;
+}
+
 void
 init_editfns (void)
 {
@@ -102,7 +113,7 @@ init_editfns (void)
   Lisp_Object tem;
 
   /* Set up system_name even when dumping.  */
-  init_system_name ();
+  init_and_cache_system_name ();
 
 #ifndef CANNOT_DUMP
   /* When just dumping out, set the time zone to a known unlikely value
@@ -1365,6 +1376,8 @@ DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
        doc: /* Return the host name of the machine you are running on, as a 
string.  */)
   (void)
 {
+  if (EQ (Vsystem_name, cached_system_name))
+    init_and_cache_system_name ();
   return Vsystem_name;
 }
 
@@ -4965,6 +4978,7 @@ functions if all the text being accessed has this 
property.  */);
 
   DEFVAR_LISP ("system-name", Vsystem_name,
               doc: /* The host name of the machine Emacs is running on.  */);
+  Vsystem_name = cached_system_name = Qnil;
 
   DEFVAR_LISP ("user-full-name", Vuser_full_name,
               doc: /* The full name of the user logged in.  */);
diff --git a/src/filelock.c b/src/filelock.c
index f857c48..99215f2 100644
--- a/src/filelock.c
+++ b/src/filelock.c
@@ -592,9 +592,10 @@ current_lock_owner (lock_info_type *owner, char *lfname)
     return -1;
 
   /* On current host?  */
-  if (STRINGP (Vsystem_name)
-      && dot - (at + 1) == SBYTES (Vsystem_name)
-      && memcmp (at + 1, SSDATA (Vsystem_name), SBYTES (Vsystem_name)) == 0)
+  Lisp_Object system_name = Fsystem_name ();
+  if (STRINGP (system_name)
+      && dot - (at + 1) == SBYTES (system_name)
+      && memcmp (at + 1, SSDATA (system_name), SBYTES (system_name)) == 0)
     {
       if (pid == getpid ())
         ret = 2; /* We own it.  */
diff --git a/src/frame.c b/src/frame.c
index 2ad1c1b5..82a85bc 100644
--- a/src/frame.c
+++ b/src/frame.c
@@ -5057,7 +5057,7 @@ keep it unchanged if this option is either `t' or a list 
containing
 `vertical-scroll-bars'.
 
 The default value is '(tool-bar-lines) on Lucid, Motif and Windows
-(which means that adding/removing a tool bar does not change the frame
+\(which means that adding/removing a tool bar does not change the frame
 height), nil on all other window systems including GTK+ (which means
 that changing any of the parameters listed above may change the size of
 the frame), and `t' otherwise (which means the frame size never changes
diff --git a/src/gnutls.c b/src/gnutls.c
index bf9f132..f945778 100644
--- a/src/gnutls.c
+++ b/src/gnutls.c
@@ -71,142 +71,129 @@ enum extra_peer_verification
 
 #ifdef WINDOWSNT
 
-/* Macro for defining functions that will be loaded from the GnuTLS DLL.  */
-#define DEF_GNUTLS_FN(rettype,func,args) static rettype (FAR CDECL 
*fn_##func)args
-
-/* Macro for loading GnuTLS functions from the library.  */
-#define LOAD_GNUTLS_FN(lib,func) {                                     \
-    fn_##func = (void *) GetProcAddress (lib, #func);                  \
-    if (!fn_##func) return 0;                                          \
-  }
-
-DEF_GNUTLS_FN (gnutls_alert_description_t, gnutls_alert_get,
-              (gnutls_session_t));
-DEF_GNUTLS_FN (const char *, gnutls_alert_get_name,
-              (gnutls_alert_description_t));
-DEF_GNUTLS_FN (int, gnutls_alert_send_appropriate, (gnutls_session_t, int));
-DEF_GNUTLS_FN (int, gnutls_anon_allocate_client_credentials,
-              (gnutls_anon_client_credentials_t *));
-DEF_GNUTLS_FN (void, gnutls_anon_free_client_credentials,
-              (gnutls_anon_client_credentials_t));
-DEF_GNUTLS_FN (int, gnutls_bye, (gnutls_session_t, gnutls_close_request_t));
-DEF_GNUTLS_FN (int, gnutls_certificate_allocate_credentials,
-              (gnutls_certificate_credentials_t *));
-DEF_GNUTLS_FN (void, gnutls_certificate_free_credentials,
-              (gnutls_certificate_credentials_t));
-DEF_GNUTLS_FN (const gnutls_datum_t *, gnutls_certificate_get_peers,
-              (gnutls_session_t, unsigned int *));
-DEF_GNUTLS_FN (void, gnutls_certificate_set_verify_flags,
-              (gnutls_certificate_credentials_t, unsigned int));
-DEF_GNUTLS_FN (int, gnutls_certificate_set_x509_crl_file,
-              (gnutls_certificate_credentials_t, const char *,
-               gnutls_x509_crt_fmt_t));
-DEF_GNUTLS_FN (int, gnutls_certificate_set_x509_key_file,
-              (gnutls_certificate_credentials_t, const char *, const char *,
-               gnutls_x509_crt_fmt_t));
-#if GNUTLS_VERSION_MAJOR +                                     \
-  (GNUTLS_VERSION_MINOR > 0 || GNUTLS_VERSION_PATCH >= 20) > 3
-DEF_GNUTLS_FN (int, gnutls_certificate_set_x509_system_trust,
-              (gnutls_certificate_credentials_t));
-#endif
-DEF_GNUTLS_FN (int, gnutls_certificate_set_x509_trust_file,
-              (gnutls_certificate_credentials_t, const char *,
-               gnutls_x509_crt_fmt_t));
-DEF_GNUTLS_FN (gnutls_certificate_type_t, gnutls_certificate_type_get,
-              (gnutls_session_t));
-DEF_GNUTLS_FN (int, gnutls_certificate_verify_peers2,
-              (gnutls_session_t, unsigned int *));
-DEF_GNUTLS_FN (int, gnutls_credentials_set,
-              (gnutls_session_t, gnutls_credentials_type_t, void *));
-DEF_GNUTLS_FN (void, gnutls_deinit, (gnutls_session_t));
-DEF_GNUTLS_FN (void, gnutls_dh_set_prime_bits,
-              (gnutls_session_t, unsigned int));
-DEF_GNUTLS_FN (int, gnutls_dh_get_prime_bits, (gnutls_session_t));
-DEF_GNUTLS_FN (int, gnutls_error_is_fatal, (int));
-DEF_GNUTLS_FN (int, gnutls_global_init, (void));
-DEF_GNUTLS_FN (void, gnutls_global_set_log_function, (gnutls_log_func));
-#ifdef HAVE_GNUTLS3
-DEF_GNUTLS_FN (void, gnutls_global_set_audit_log_function, 
(gnutls_audit_log_func));
-#endif
-DEF_GNUTLS_FN (void, gnutls_global_set_log_level, (int));
-DEF_GNUTLS_FN (void, gnutls_global_set_mem_functions,
-              (gnutls_alloc_function, gnutls_alloc_function,
-               gnutls_is_secure_function, gnutls_realloc_function,
-               gnutls_free_function));
-DEF_GNUTLS_FN (int, gnutls_handshake, (gnutls_session_t));
-DEF_GNUTLS_FN (int, gnutls_init, (gnutls_session_t *, 
gnutls_connection_end_t));
-DEF_GNUTLS_FN (int, gnutls_priority_set_direct,
-              (gnutls_session_t, const char *, const char **));
-DEF_GNUTLS_FN (size_t, gnutls_record_check_pending, (gnutls_session_t));
-DEF_GNUTLS_FN (ssize_t, gnutls_record_recv, (gnutls_session_t, void *, 
size_t));
-DEF_GNUTLS_FN (ssize_t, gnutls_record_send,
-              (gnutls_session_t, const void *, size_t));
-DEF_GNUTLS_FN (const char *, gnutls_strerror, (int));
-DEF_GNUTLS_FN (void, gnutls_transport_set_errno, (gnutls_session_t, int));
-DEF_GNUTLS_FN (const char *, gnutls_check_version, (const char *));
-DEF_GNUTLS_FN (void, gnutls_transport_set_lowat, (gnutls_session_t, int));
-DEF_GNUTLS_FN (void, gnutls_transport_set_ptr2,
-              (gnutls_session_t, gnutls_transport_ptr_t,
-               gnutls_transport_ptr_t));
-DEF_GNUTLS_FN (void, gnutls_transport_set_pull_function,
-              (gnutls_session_t, gnutls_pull_func));
-DEF_GNUTLS_FN (void, gnutls_transport_set_push_function,
-              (gnutls_session_t, gnutls_push_func));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_check_hostname,
-              (gnutls_x509_crt_t, const char *));
-DEF_GNUTLS_FN (void, gnutls_x509_crt_deinit, (gnutls_x509_crt_t));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_import,
-              (gnutls_x509_crt_t, const gnutls_datum_t *,
-               gnutls_x509_crt_fmt_t));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_init, (gnutls_x509_crt_t *));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_fingerprint,
-              (gnutls_x509_crt_t,
-               gnutls_digest_algorithm_t, void *, size_t *));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_version,
-              (gnutls_x509_crt_t));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_serial,
-              (gnutls_x509_crt_t, void *, size_t *));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_issuer_dn,
-              (gnutls_x509_crt_t, char *, size_t *));
-DEF_GNUTLS_FN (time_t, gnutls_x509_crt_get_activation_time,
-              (gnutls_x509_crt_t));
-DEF_GNUTLS_FN (time_t, gnutls_x509_crt_get_expiration_time,
-              (gnutls_x509_crt_t));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_dn,
-              (gnutls_x509_crt_t, char *, size_t *));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_pk_algorithm,
-              (gnutls_x509_crt_t, unsigned int *));
-DEF_GNUTLS_FN (const char*, gnutls_pk_algorithm_get_name,
-              (gnutls_pk_algorithm_t));
-DEF_GNUTLS_FN (int, gnutls_pk_bits_to_sec_param,
-              (gnutls_pk_algorithm_t, unsigned int));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_issuer_unique_id,
-              (gnutls_x509_crt_t, char *, size_t *));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_subject_unique_id,
-              (gnutls_x509_crt_t, char *, size_t *));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_signature_algorithm,
-              (gnutls_x509_crt_t));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_signature,
-              (gnutls_x509_crt_t, char *, size_t *));
-DEF_GNUTLS_FN (int, gnutls_x509_crt_get_key_id,
-              (gnutls_x509_crt_t, unsigned int,
-               unsigned char *, size_t *_size));
-DEF_GNUTLS_FN (const char*, gnutls_sec_param_get_name, (gnutls_sec_param_t));
-DEF_GNUTLS_FN (const char*, gnutls_sign_get_name, (gnutls_sign_algorithm_t));
-DEF_GNUTLS_FN (int, gnutls_server_name_set, (gnutls_session_t,
-                                            gnutls_server_name_type_t,
-                                            const void *, size_t));
-DEF_GNUTLS_FN (gnutls_kx_algorithm_t, gnutls_kx_get, (gnutls_session_t));
-DEF_GNUTLS_FN (const char*, gnutls_kx_get_name, (gnutls_kx_algorithm_t));
-DEF_GNUTLS_FN (gnutls_protocol_t, gnutls_protocol_get_version,
-              (gnutls_session_t));
-DEF_GNUTLS_FN (const char*, gnutls_protocol_get_name, (gnutls_protocol_t));
-DEF_GNUTLS_FN (gnutls_cipher_algorithm_t, gnutls_cipher_get,
-              (gnutls_session_t));
-DEF_GNUTLS_FN (const char*, gnutls_cipher_get_name,
-              (gnutls_cipher_algorithm_t));
-DEF_GNUTLS_FN (gnutls_mac_algorithm_t, gnutls_mac_get, (gnutls_session_t));
-DEF_GNUTLS_FN (const char*, gnutls_mac_get_name, (gnutls_mac_algorithm_t));
+DEF_DLL_FN (gnutls_alert_description_t, gnutls_alert_get,
+           (gnutls_session_t));
+DEF_DLL_FN (const char *, gnutls_alert_get_name,
+           (gnutls_alert_description_t));
+DEF_DLL_FN (int, gnutls_alert_send_appropriate, (gnutls_session_t, int));
+DEF_DLL_FN (int, gnutls_anon_allocate_client_credentials,
+           (gnutls_anon_client_credentials_t *));
+DEF_DLL_FN (void, gnutls_anon_free_client_credentials,
+           (gnutls_anon_client_credentials_t));
+DEF_DLL_FN (int, gnutls_bye, (gnutls_session_t, gnutls_close_request_t));
+DEF_DLL_FN (int, gnutls_certificate_allocate_credentials,
+           (gnutls_certificate_credentials_t *));
+DEF_DLL_FN (void, gnutls_certificate_free_credentials,
+           (gnutls_certificate_credentials_t));
+DEF_DLL_FN (const gnutls_datum_t *, gnutls_certificate_get_peers,
+           (gnutls_session_t, unsigned int *));
+DEF_DLL_FN (void, gnutls_certificate_set_verify_flags,
+           (gnutls_certificate_credentials_t, unsigned int));
+DEF_DLL_FN (int, gnutls_certificate_set_x509_crl_file,
+           (gnutls_certificate_credentials_t, const char *,
+            gnutls_x509_crt_fmt_t));
+DEF_DLL_FN (int, gnutls_certificate_set_x509_key_file,
+           (gnutls_certificate_credentials_t, const char *, const char *,
+            gnutls_x509_crt_fmt_t));
+# if ((GNUTLS_VERSION_MAJOR                                            \
+       + (GNUTLS_VERSION_MINOR > 0 || GNUTLS_VERSION_PATCH >= 20))     \
+      > 3)
+DEF_DLL_FN (int, gnutls_certificate_set_x509_system_trust,
+           (gnutls_certificate_credentials_t));
+# endif
+DEF_DLL_FN (int, gnutls_certificate_set_x509_trust_file,
+           (gnutls_certificate_credentials_t, const char *,
+            gnutls_x509_crt_fmt_t));
+DEF_DLL_FN (gnutls_certificate_type_t, gnutls_certificate_type_get,
+           (gnutls_session_t));
+DEF_DLL_FN (int, gnutls_certificate_verify_peers2,
+           (gnutls_session_t, unsigned int *));
+DEF_DLL_FN (int, gnutls_credentials_set,
+           (gnutls_session_t, gnutls_credentials_type_t, void *));
+DEF_DLL_FN (void, gnutls_deinit, (gnutls_session_t));
+DEF_DLL_FN (void, gnutls_dh_set_prime_bits,
+           (gnutls_session_t, unsigned int));
+DEF_DLL_FN (int, gnutls_dh_get_prime_bits, (gnutls_session_t));
+DEF_DLL_FN (int, gnutls_error_is_fatal, (int));
+DEF_DLL_FN (int, gnutls_global_init, (void));
+DEF_DLL_FN (void, gnutls_global_set_log_function, (gnutls_log_func));
+# ifdef HAVE_GNUTLS3
+DEF_DLL_FN (void, gnutls_global_set_audit_log_function, 
(gnutls_audit_log_func));
+# endif
+DEF_DLL_FN (void, gnutls_global_set_log_level, (int));
+DEF_DLL_FN (int, gnutls_handshake, (gnutls_session_t));
+DEF_DLL_FN (int, gnutls_init, (gnutls_session_t *, unsigned int));
+DEF_DLL_FN (int, gnutls_priority_set_direct,
+           (gnutls_session_t, const char *, const char **));
+DEF_DLL_FN (size_t, gnutls_record_check_pending, (gnutls_session_t));
+DEF_DLL_FN (ssize_t, gnutls_record_recv, (gnutls_session_t, void *, size_t));
+DEF_DLL_FN (ssize_t, gnutls_record_send,
+           (gnutls_session_t, const void *, size_t));
+DEF_DLL_FN (const char *, gnutls_strerror, (int));
+DEF_DLL_FN (void, gnutls_transport_set_errno, (gnutls_session_t, int));
+DEF_DLL_FN (const char *, gnutls_check_version, (const char *));
+DEF_DLL_FN (void, gnutls_transport_set_lowat, (gnutls_session_t, int));
+DEF_DLL_FN (void, gnutls_transport_set_ptr2,
+           (gnutls_session_t, gnutls_transport_ptr_t,
+            gnutls_transport_ptr_t));
+DEF_DLL_FN (void, gnutls_transport_set_pull_function,
+           (gnutls_session_t, gnutls_pull_func));
+DEF_DLL_FN (void, gnutls_transport_set_push_function,
+           (gnutls_session_t, gnutls_push_func));
+DEF_DLL_FN (int, gnutls_x509_crt_check_hostname,
+           (gnutls_x509_crt_t, const char *));
+DEF_DLL_FN (void, gnutls_x509_crt_deinit, (gnutls_x509_crt_t));
+DEF_DLL_FN (int, gnutls_x509_crt_import,
+           (gnutls_x509_crt_t, const gnutls_datum_t *,
+            gnutls_x509_crt_fmt_t));
+DEF_DLL_FN (int, gnutls_x509_crt_init, (gnutls_x509_crt_t *));
+DEF_DLL_FN (int, gnutls_x509_crt_get_fingerprint,
+           (gnutls_x509_crt_t,
+            gnutls_digest_algorithm_t, void *, size_t *));
+DEF_DLL_FN (int, gnutls_x509_crt_get_version,
+           (gnutls_x509_crt_t));
+DEF_DLL_FN (int, gnutls_x509_crt_get_serial,
+           (gnutls_x509_crt_t, void *, size_t *));
+DEF_DLL_FN (int, gnutls_x509_crt_get_issuer_dn,
+           (gnutls_x509_crt_t, char *, size_t *));
+DEF_DLL_FN (time_t, gnutls_x509_crt_get_activation_time,
+           (gnutls_x509_crt_t));
+DEF_DLL_FN (time_t, gnutls_x509_crt_get_expiration_time,
+           (gnutls_x509_crt_t));
+DEF_DLL_FN (int, gnutls_x509_crt_get_dn,
+           (gnutls_x509_crt_t, char *, size_t *));
+DEF_DLL_FN (int, gnutls_x509_crt_get_pk_algorithm,
+           (gnutls_x509_crt_t, unsigned int *));
+DEF_DLL_FN (const char*, gnutls_pk_algorithm_get_name,
+           (gnutls_pk_algorithm_t));
+DEF_DLL_FN (int, gnutls_pk_bits_to_sec_param,
+           (gnutls_pk_algorithm_t, unsigned int));
+DEF_DLL_FN (int, gnutls_x509_crt_get_issuer_unique_id,
+           (gnutls_x509_crt_t, char *, size_t *));
+DEF_DLL_FN (int, gnutls_x509_crt_get_subject_unique_id,
+           (gnutls_x509_crt_t, char *, size_t *));
+DEF_DLL_FN (int, gnutls_x509_crt_get_signature_algorithm,
+           (gnutls_x509_crt_t));
+DEF_DLL_FN (int, gnutls_x509_crt_get_signature,
+           (gnutls_x509_crt_t, char *, size_t *));
+DEF_DLL_FN (int, gnutls_x509_crt_get_key_id,
+           (gnutls_x509_crt_t, unsigned int, unsigned char *, size_t *_size));
+DEF_DLL_FN (const char*, gnutls_sec_param_get_name, (gnutls_sec_param_t));
+DEF_DLL_FN (const char*, gnutls_sign_get_name, (gnutls_sign_algorithm_t));
+DEF_DLL_FN (int, gnutls_server_name_set,
+           (gnutls_session_t, gnutls_server_name_type_t,
+            const void *, size_t));
+DEF_DLL_FN (gnutls_kx_algorithm_t, gnutls_kx_get, (gnutls_session_t));
+DEF_DLL_FN (const char*, gnutls_kx_get_name, (gnutls_kx_algorithm_t));
+DEF_DLL_FN (gnutls_protocol_t, gnutls_protocol_get_version,
+           (gnutls_session_t));
+DEF_DLL_FN (const char*, gnutls_protocol_get_name, (gnutls_protocol_t));
+DEF_DLL_FN (gnutls_cipher_algorithm_t, gnutls_cipher_get,
+           (gnutls_session_t));
+DEF_DLL_FN (const char*, gnutls_cipher_get_name,
+           (gnutls_cipher_algorithm_t));
+DEF_DLL_FN (gnutls_mac_algorithm_t, gnutls_mac_get, (gnutls_session_t));
+DEF_DLL_FN (const char*, gnutls_mac_get_name, (gnutls_mac_algorithm_t));
 
 
 static bool
@@ -221,83 +208,83 @@ init_gnutls_functions (void)
       return 0;
     }
 
-  LOAD_GNUTLS_FN (library, gnutls_alert_get);
-  LOAD_GNUTLS_FN (library, gnutls_alert_get_name);
-  LOAD_GNUTLS_FN (library, gnutls_alert_send_appropriate);
-  LOAD_GNUTLS_FN (library, gnutls_anon_allocate_client_credentials);
-  LOAD_GNUTLS_FN (library, gnutls_anon_free_client_credentials);
-  LOAD_GNUTLS_FN (library, gnutls_bye);
-  LOAD_GNUTLS_FN (library, gnutls_certificate_allocate_credentials);
-  LOAD_GNUTLS_FN (library, gnutls_certificate_free_credentials);
-  LOAD_GNUTLS_FN (library, gnutls_certificate_get_peers);
-  LOAD_GNUTLS_FN (library, gnutls_certificate_set_verify_flags);
-  LOAD_GNUTLS_FN (library, gnutls_certificate_set_x509_crl_file);
-  LOAD_GNUTLS_FN (library, gnutls_certificate_set_x509_key_file);
-#if GNUTLS_VERSION_MAJOR +                                     \
-  (GNUTLS_VERSION_MINOR > 0 || GNUTLS_VERSION_PATCH >= 20) > 3
-  LOAD_GNUTLS_FN (library, gnutls_certificate_set_x509_system_trust);
-#endif
-  LOAD_GNUTLS_FN (library, gnutls_certificate_set_x509_trust_file);
-  LOAD_GNUTLS_FN (library, gnutls_certificate_type_get);
-  LOAD_GNUTLS_FN (library, gnutls_certificate_verify_peers2);
-  LOAD_GNUTLS_FN (library, gnutls_credentials_set);
-  LOAD_GNUTLS_FN (library, gnutls_deinit);
-  LOAD_GNUTLS_FN (library, gnutls_dh_set_prime_bits);
-  LOAD_GNUTLS_FN (library, gnutls_dh_get_prime_bits);
-  LOAD_GNUTLS_FN (library, gnutls_error_is_fatal);
-  LOAD_GNUTLS_FN (library, gnutls_global_init);
-  LOAD_GNUTLS_FN (library, gnutls_global_set_log_function);
-#ifdef HAVE_GNUTLS3
-  LOAD_GNUTLS_FN (library, gnutls_global_set_audit_log_function);
-#endif
-  LOAD_GNUTLS_FN (library, gnutls_global_set_log_level);
-  LOAD_GNUTLS_FN (library, gnutls_global_set_mem_functions);
-  LOAD_GNUTLS_FN (library, gnutls_handshake);
-  LOAD_GNUTLS_FN (library, gnutls_init);
-  LOAD_GNUTLS_FN (library, gnutls_priority_set_direct);
-  LOAD_GNUTLS_FN (library, gnutls_record_check_pending);
-  LOAD_GNUTLS_FN (library, gnutls_record_recv);
-  LOAD_GNUTLS_FN (library, gnutls_record_send);
-  LOAD_GNUTLS_FN (library, gnutls_strerror);
-  LOAD_GNUTLS_FN (library, gnutls_transport_set_errno);
-  LOAD_GNUTLS_FN (library, gnutls_check_version);
+  LOAD_DLL_FN (library, gnutls_alert_get);
+  LOAD_DLL_FN (library, gnutls_alert_get_name);
+  LOAD_DLL_FN (library, gnutls_alert_send_appropriate);
+  LOAD_DLL_FN (library, gnutls_anon_allocate_client_credentials);
+  LOAD_DLL_FN (library, gnutls_anon_free_client_credentials);
+  LOAD_DLL_FN (library, gnutls_bye);
+  LOAD_DLL_FN (library, gnutls_certificate_allocate_credentials);
+  LOAD_DLL_FN (library, gnutls_certificate_free_credentials);
+  LOAD_DLL_FN (library, gnutls_certificate_get_peers);
+  LOAD_DLL_FN (library, gnutls_certificate_set_verify_flags);
+  LOAD_DLL_FN (library, gnutls_certificate_set_x509_crl_file);
+  LOAD_DLL_FN (library, gnutls_certificate_set_x509_key_file);
+# if ((GNUTLS_VERSION_MAJOR                                            \
+       + (GNUTLS_VERSION_MINOR > 0 || GNUTLS_VERSION_PATCH >= 20))     \
+      > 3)
+  LOAD_DLL_FN (library, gnutls_certificate_set_x509_system_trust);
+# endif
+  LOAD_DLL_FN (library, gnutls_certificate_set_x509_trust_file);
+  LOAD_DLL_FN (library, gnutls_certificate_type_get);
+  LOAD_DLL_FN (library, gnutls_certificate_verify_peers2);
+  LOAD_DLL_FN (library, gnutls_credentials_set);
+  LOAD_DLL_FN (library, gnutls_deinit);
+  LOAD_DLL_FN (library, gnutls_dh_set_prime_bits);
+  LOAD_DLL_FN (library, gnutls_dh_get_prime_bits);
+  LOAD_DLL_FN (library, gnutls_error_is_fatal);
+  LOAD_DLL_FN (library, gnutls_global_init);
+  LOAD_DLL_FN (library, gnutls_global_set_log_function);
+# ifdef HAVE_GNUTLS3
+  LOAD_DLL_FN (library, gnutls_global_set_audit_log_function);
+# endif
+  LOAD_DLL_FN (library, gnutls_global_set_log_level);
+  LOAD_DLL_FN (library, gnutls_handshake);
+  LOAD_DLL_FN (library, gnutls_init);
+  LOAD_DLL_FN (library, gnutls_priority_set_direct);
+  LOAD_DLL_FN (library, gnutls_record_check_pending);
+  LOAD_DLL_FN (library, gnutls_record_recv);
+  LOAD_DLL_FN (library, gnutls_record_send);
+  LOAD_DLL_FN (library, gnutls_strerror);
+  LOAD_DLL_FN (library, gnutls_transport_set_errno);
+  LOAD_DLL_FN (library, gnutls_check_version);
   /* We don't need to call gnutls_transport_set_lowat in GnuTLS 2.11.1
      and later, and the function was removed entirely in 3.0.0.  */
   if (!fn_gnutls_check_version ("2.11.1"))
-    LOAD_GNUTLS_FN (library, gnutls_transport_set_lowat);
-  LOAD_GNUTLS_FN (library, gnutls_transport_set_ptr2);
-  LOAD_GNUTLS_FN (library, gnutls_transport_set_pull_function);
-  LOAD_GNUTLS_FN (library, gnutls_transport_set_push_function);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_check_hostname);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_deinit);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_import);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_init);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_fingerprint);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_version);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_serial);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_issuer_dn);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_activation_time);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_expiration_time);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_dn);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_pk_algorithm);
-  LOAD_GNUTLS_FN (library, gnutls_pk_algorithm_get_name);
-  LOAD_GNUTLS_FN (library, gnutls_pk_bits_to_sec_param);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_issuer_unique_id);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_subject_unique_id);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_signature_algorithm);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_signature);
-  LOAD_GNUTLS_FN (library, gnutls_x509_crt_get_key_id);
-  LOAD_GNUTLS_FN (library, gnutls_sec_param_get_name);
-  LOAD_GNUTLS_FN (library, gnutls_sign_get_name);
-  LOAD_GNUTLS_FN (library, gnutls_server_name_set);
-  LOAD_GNUTLS_FN (library, gnutls_kx_get);
-  LOAD_GNUTLS_FN (library, gnutls_kx_get_name);
-  LOAD_GNUTLS_FN (library, gnutls_protocol_get_version);
-  LOAD_GNUTLS_FN (library, gnutls_protocol_get_name);
-  LOAD_GNUTLS_FN (library, gnutls_cipher_get);
-  LOAD_GNUTLS_FN (library, gnutls_cipher_get_name);
-  LOAD_GNUTLS_FN (library, gnutls_mac_get);
-  LOAD_GNUTLS_FN (library, gnutls_mac_get_name);
+    LOAD_DLL_FN (library, gnutls_transport_set_lowat);
+  LOAD_DLL_FN (library, gnutls_transport_set_ptr2);
+  LOAD_DLL_FN (library, gnutls_transport_set_pull_function);
+  LOAD_DLL_FN (library, gnutls_transport_set_push_function);
+  LOAD_DLL_FN (library, gnutls_x509_crt_check_hostname);
+  LOAD_DLL_FN (library, gnutls_x509_crt_deinit);
+  LOAD_DLL_FN (library, gnutls_x509_crt_import);
+  LOAD_DLL_FN (library, gnutls_x509_crt_init);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_fingerprint);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_version);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_serial);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_issuer_dn);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_activation_time);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_expiration_time);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_dn);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_pk_algorithm);
+  LOAD_DLL_FN (library, gnutls_pk_algorithm_get_name);
+  LOAD_DLL_FN (library, gnutls_pk_bits_to_sec_param);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_issuer_unique_id);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_subject_unique_id);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_signature_algorithm);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_signature);
+  LOAD_DLL_FN (library, gnutls_x509_crt_get_key_id);
+  LOAD_DLL_FN (library, gnutls_sec_param_get_name);
+  LOAD_DLL_FN (library, gnutls_sign_get_name);
+  LOAD_DLL_FN (library, gnutls_server_name_set);
+  LOAD_DLL_FN (library, gnutls_kx_get);
+  LOAD_DLL_FN (library, gnutls_kx_get_name);
+  LOAD_DLL_FN (library, gnutls_protocol_get_version);
+  LOAD_DLL_FN (library, gnutls_protocol_get_name);
+  LOAD_DLL_FN (library, gnutls_cipher_get);
+  LOAD_DLL_FN (library, gnutls_cipher_get_name);
+  LOAD_DLL_FN (library, gnutls_mac_get);
+  LOAD_DLL_FN (library, gnutls_mac_get_name);
 
   max_log_level = global_gnutls_log_level;
 
@@ -310,80 +297,89 @@ init_gnutls_functions (void)
   return 1;
 }
 
-#else /* !WINDOWSNT */
-
-#define fn_gnutls_alert_get                    gnutls_alert_get
-#define fn_gnutls_alert_get_name               gnutls_alert_get_name
-#define fn_gnutls_alert_send_appropriate       gnutls_alert_send_appropriate
-#define fn_gnutls_anon_allocate_client_credentials 
gnutls_anon_allocate_client_credentials
-#define fn_gnutls_anon_free_client_credentials 
gnutls_anon_free_client_credentials
-#define fn_gnutls_bye                          gnutls_bye
-#define fn_gnutls_certificate_allocate_credentials 
gnutls_certificate_allocate_credentials
-#define fn_gnutls_certificate_free_credentials 
gnutls_certificate_free_credentials
-#define fn_gnutls_certificate_get_peers                
gnutls_certificate_get_peers
-#define fn_gnutls_certificate_set_verify_flags 
gnutls_certificate_set_verify_flags
-#define fn_gnutls_certificate_set_x509_crl_file        
gnutls_certificate_set_x509_crl_file
-#define fn_gnutls_certificate_set_x509_key_file 
gnutls_certificate_set_x509_key_file
-#if GNUTLS_VERSION_MAJOR +                                     \
-  (GNUTLS_VERSION_MINOR > 0 || GNUTLS_VERSION_PATCH >= 20) > 3
-#define fn_gnutls_certificate_set_x509_system_trust 
gnutls_certificate_set_x509_system_trust
-#endif
-#define fn_gnutls_certificate_set_x509_trust_file 
gnutls_certificate_set_x509_trust_file
-#define fn_gnutls_certificate_type_get         gnutls_certificate_type_get
-#define fn_gnutls_certificate_verify_peers2    gnutls_certificate_verify_peers2
-#define fn_gnutls_cipher_get                    gnutls_cipher_get
-#define fn_gnutls_cipher_get_name               gnutls_cipher_get_name
-#define fn_gnutls_credentials_set              gnutls_credentials_set
-#define fn_gnutls_deinit                       gnutls_deinit
-#define fn_gnutls_dh_get_prime_bits            gnutls_dh_get_prime_bits
-#define fn_gnutls_dh_set_prime_bits            gnutls_dh_set_prime_bits
-#define fn_gnutls_error_is_fatal               gnutls_error_is_fatal
-#define fn_gnutls_global_init                  gnutls_global_init
-#ifdef HAVE_GNUTLS3
-#define fn_gnutls_global_set_audit_log_function        
gnutls_global_set_audit_log_function
+# define gnutls_alert_get fn_gnutls_alert_get
+# define gnutls_alert_get_name fn_gnutls_alert_get_name
+# define gnutls_alert_send_appropriate fn_gnutls_alert_send_appropriate
+# define gnutls_anon_allocate_client_credentials 
fn_gnutls_anon_allocate_client_credentials
+# define gnutls_anon_free_client_credentials 
fn_gnutls_anon_free_client_credentials
+# define gnutls_bye fn_gnutls_bye
+# define gnutls_certificate_allocate_credentials 
fn_gnutls_certificate_allocate_credentials
+# define gnutls_certificate_free_credentials 
fn_gnutls_certificate_free_credentials
+# define gnutls_certificate_get_peers fn_gnutls_certificate_get_peers
+# define gnutls_certificate_set_verify_flags 
fn_gnutls_certificate_set_verify_flags
+# define gnutls_certificate_set_x509_crl_file 
fn_gnutls_certificate_set_x509_crl_file
+# define gnutls_certificate_set_x509_key_file 
fn_gnutls_certificate_set_x509_key_file
+# define gnutls_certificate_set_x509_system_trust 
fn_gnutls_certificate_set_x509_system_trust
+# define gnutls_certificate_set_x509_trust_file 
fn_gnutls_certificate_set_x509_trust_file
+# define gnutls_certificate_type_get fn_gnutls_certificate_type_get
+# define gnutls_certificate_verify_peers2 fn_gnutls_certificate_verify_peers2
+# define gnutls_check_version fn_gnutls_check_version
+# define gnutls_cipher_get fn_gnutls_cipher_get
+# define gnutls_cipher_get_name fn_gnutls_cipher_get_name
+# define gnutls_credentials_set fn_gnutls_credentials_set
+# define gnutls_deinit fn_gnutls_deinit
+# define gnutls_dh_get_prime_bits fn_gnutls_dh_get_prime_bits
+# define gnutls_dh_set_prime_bits fn_gnutls_dh_set_prime_bits
+# define gnutls_error_is_fatal fn_gnutls_error_is_fatal
+# define gnutls_global_init fn_gnutls_global_init
+# define gnutls_global_set_audit_log_function 
fn_gnutls_global_set_audit_log_function
+# define gnutls_global_set_log_function fn_gnutls_global_set_log_function
+# define gnutls_global_set_log_level fn_gnutls_global_set_log_level
+# define gnutls_handshake fn_gnutls_handshake
+# define gnutls_init fn_gnutls_init
+# define gnutls_kx_get fn_gnutls_kx_get
+# define gnutls_kx_get_name fn_gnutls_kx_get_name
+# define gnutls_mac_get fn_gnutls_mac_get
+# define gnutls_mac_get_name fn_gnutls_mac_get_name
+# define gnutls_pk_algorithm_get_name fn_gnutls_pk_algorithm_get_name
+# define gnutls_pk_bits_to_sec_param fn_gnutls_pk_bits_to_sec_param
+# define gnutls_priority_set_direct fn_gnutls_priority_set_direct
+# define gnutls_protocol_get_name fn_gnutls_protocol_get_name
+# define gnutls_protocol_get_version fn_gnutls_protocol_get_version
+# define gnutls_record_check_pending fn_gnutls_record_check_pending
+# define gnutls_record_recv fn_gnutls_record_recv
+# define gnutls_record_send fn_gnutls_record_send
+# define gnutls_sec_param_get_name fn_gnutls_sec_param_get_name
+# define gnutls_server_name_set fn_gnutls_server_name_set
+# define gnutls_sign_get_name fn_gnutls_sign_get_name
+# define gnutls_strerror fn_gnutls_strerror
+# define gnutls_transport_set_errno fn_gnutls_transport_set_errno
+# define gnutls_transport_set_lowat fn_gnutls_transport_set_lowat
+# define gnutls_transport_set_ptr2 fn_gnutls_transport_set_ptr2
+# define gnutls_transport_set_pull_function 
fn_gnutls_transport_set_pull_function
+# define gnutls_transport_set_push_function 
fn_gnutls_transport_set_push_function
+# define gnutls_x509_crt_check_hostname fn_gnutls_x509_crt_check_hostname
+# define gnutls_x509_crt_deinit fn_gnutls_x509_crt_deinit
+# define gnutls_x509_crt_get_activation_time 
fn_gnutls_x509_crt_get_activation_time
+# define gnutls_x509_crt_get_dn fn_gnutls_x509_crt_get_dn
+# define gnutls_x509_crt_get_expiration_time 
fn_gnutls_x509_crt_get_expiration_time
+# define gnutls_x509_crt_get_fingerprint fn_gnutls_x509_crt_get_fingerprint
+# define gnutls_x509_crt_get_issuer_dn fn_gnutls_x509_crt_get_issuer_dn
+# define gnutls_x509_crt_get_issuer_unique_id 
fn_gnutls_x509_crt_get_issuer_unique_id
+# define gnutls_x509_crt_get_key_id fn_gnutls_x509_crt_get_key_id
+# define gnutls_x509_crt_get_pk_algorithm fn_gnutls_x509_crt_get_pk_algorithm
+# define gnutls_x509_crt_get_serial fn_gnutls_x509_crt_get_serial
+# define gnutls_x509_crt_get_signature fn_gnutls_x509_crt_get_signature
+# define gnutls_x509_crt_get_signature_algorithm 
fn_gnutls_x509_crt_get_signature_algorithm
+# define gnutls_x509_crt_get_subject_unique_id 
fn_gnutls_x509_crt_get_subject_unique_id
+# define gnutls_x509_crt_get_version fn_gnutls_x509_crt_get_version
+# define gnutls_x509_crt_import fn_gnutls_x509_crt_import
+# define gnutls_x509_crt_init fn_gnutls_x509_crt_init
+
 #endif
-#define fn_gnutls_global_set_log_function      gnutls_global_set_log_function
-#define fn_gnutls_global_set_log_level         gnutls_global_set_log_level
-#define fn_gnutls_global_set_mem_functions     gnutls_global_set_mem_functions
-#define fn_gnutls_handshake                    gnutls_handshake
-#define fn_gnutls_init                         gnutls_init
-#define fn_gnutls_kx_get                        gnutls_kx_get
-#define fn_gnutls_kx_get_name                   gnutls_kx_get_name
-#define fn_gnutls_mac_get                       gnutls_mac_get
-#define fn_gnutls_mac_get_name                  gnutls_mac_get_name
-#define fn_gnutls_pk_algorithm_get_name         gnutls_pk_algorithm_get_name
-#define fn_gnutls_pk_bits_to_sec_param          gnutls_pk_bits_to_sec_param
-#define fn_gnutls_priority_set_direct          gnutls_priority_set_direct
-#define fn_gnutls_protocol_get_name             gnutls_protocol_get_name
-#define fn_gnutls_protocol_get_version          gnutls_protocol_get_version
-#define fn_gnutls_record_check_pending         gnutls_record_check_pending
-#define fn_gnutls_record_recv                  gnutls_record_recv
-#define fn_gnutls_record_send                  gnutls_record_send
-#define fn_gnutls_sec_param_get_name            gnutls_sec_param_get_name
-#define fn_gnutls_server_name_set               gnutls_server_name_set
-#define fn_gnutls_sign_get_name                 gnutls_sign_get_name
-#define fn_gnutls_strerror                     gnutls_strerror
-#define fn_gnutls_transport_set_ptr2           gnutls_transport_set_ptr2
-#define fn_gnutls_x509_crt_check_hostname      gnutls_x509_crt_check_hostname
-#define fn_gnutls_x509_crt_deinit              gnutls_x509_crt_deinit
-#define fn_gnutls_x509_crt_get_activation_time  
gnutls_x509_crt_get_activation_time
-#define fn_gnutls_x509_crt_get_dn               gnutls_x509_crt_get_dn
-#define fn_gnutls_x509_crt_get_expiration_time  
gnutls_x509_crt_get_expiration_time
-#define fn_gnutls_x509_crt_get_fingerprint     gnutls_x509_crt_get_fingerprint
-#define fn_gnutls_x509_crt_get_issuer_dn        gnutls_x509_crt_get_issuer_dn
-#define fn_gnutls_x509_crt_get_issuer_unique_id 
gnutls_x509_crt_get_issuer_unique_id
-#define fn_gnutls_x509_crt_get_key_id           gnutls_x509_crt_get_key_id
-#define fn_gnutls_x509_crt_get_pk_algorithm     
gnutls_x509_crt_get_pk_algorithm
-#define fn_gnutls_x509_crt_get_serial           gnutls_x509_crt_get_serial
-#define fn_gnutls_x509_crt_get_signature_algorithm 
gnutls_x509_crt_get_signature_algorithm
-#define fn_gnutls_x509_crt_get_subject_unique_id 
gnutls_x509_crt_get_subject_unique_id
-#define fn_gnutls_x509_crt_get_version          gnutls_x509_crt_get_version
-#define fn_gnutls_x509_crt_import              gnutls_x509_crt_import
-#define fn_gnutls_x509_crt_init                        gnutls_x509_crt_init
-
-#endif /* !WINDOWSNT */
 
 
+/* Report memory exhaustion if ERR is an out-of-memory indication.  */
+static void
+check_memory_full (int err)
+{
+  /* When GnuTLS exhausts memory, it doesn't say how much memory it
+     asked for, so tell the Emacs allocator that GnuTLS asked for no
+     bytes.  This isn't accurate, but it's good enough.  */
+  if (err == GNUTLS_E_MEMORY_ERROR)
+    memory_full (0);
+}
+
 #ifdef HAVE_GNUTLS3
 /* Log a simple audit message.  */
 static void
@@ -432,11 +428,11 @@ emacs_gnutls_handshake (struct Lisp_Process *proc)
       /* On W32 we cannot transfer socket handles between different runtime
         libraries, so we tell GnuTLS to use our special push/pull
         functions.  */
-      fn_gnutls_transport_set_ptr2 (state,
-                                   (gnutls_transport_ptr_t) proc,
-                                   (gnutls_transport_ptr_t) proc);
-      fn_gnutls_transport_set_push_function (state, &emacs_gnutls_push);
-      fn_gnutls_transport_set_pull_function (state, &emacs_gnutls_pull);
+      gnutls_transport_set_ptr2 (state,
+                                (gnutls_transport_ptr_t) proc,
+                                (gnutls_transport_ptr_t) proc);
+      gnutls_transport_set_push_function (state, &emacs_gnutls_push);
+      gnutls_transport_set_pull_function (state, &emacs_gnutls_pull);
 
       /* For non blocking sockets or other custom made pull/push
         functions the gnutls_transport_set_lowat must be called, with
@@ -449,15 +445,15 @@ emacs_gnutls_handshake (struct Lisp_Process *proc)
         zero by default in version 2.11.1, and the function
         gnutls_transport_set_lowat was removed from the library in
         version 2.99.0.  */
-      if (!fn_gnutls_check_version ("2.11.1"))
-       fn_gnutls_transport_set_lowat (state, 0);
+      if (!gnutls_check_version ("2.11.1"))
+       gnutls_transport_set_lowat (state, 0);
 #else
       /* This is how GnuTLS takes sockets: as file descriptors passed
         in.  For an Emacs process socket, infd and outfd are the
         same but we use this two-argument version for clarity.  */
-      fn_gnutls_transport_set_ptr2 (state,
-                                   (void *) (intptr_t) proc->infd,
-                                   (void *) (intptr_t) proc->outfd);
+      gnutls_transport_set_ptr2 (state,
+                                (void *) (intptr_t) proc->infd,
+                                (void *) (intptr_t) proc->outfd);
 #endif
 
       proc->gnutls_initstage = GNUTLS_STAGE_TRANSPORT_POINTERS_SET;
@@ -465,11 +461,11 @@ emacs_gnutls_handshake (struct Lisp_Process *proc)
 
   do
     {
-      ret = fn_gnutls_handshake (state);
+      ret = gnutls_handshake (state);
       emacs_gnutls_handle_error (state, ret);
       QUIT;
     }
-  while (ret < 0 && fn_gnutls_error_is_fatal (ret) == 0);
+  while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
 
   proc->gnutls_initstage = GNUTLS_STAGE_HANDSHAKE_TRIED;
 
@@ -480,7 +476,7 @@ emacs_gnutls_handshake (struct Lisp_Process *proc)
     }
   else
     {
-      fn_gnutls_alert_send_appropriate (state, ret);
+      check_memory_full (gnutls_alert_send_appropriate (state, ret));
     }
   return ret;
 }
@@ -488,14 +484,14 @@ emacs_gnutls_handshake (struct Lisp_Process *proc)
 ptrdiff_t
 emacs_gnutls_record_check_pending (gnutls_session_t state)
 {
-  return fn_gnutls_record_check_pending (state);
+  return gnutls_record_check_pending (state);
 }
 
 #ifdef WINDOWSNT
 void
 emacs_gnutls_transport_set_errno (gnutls_session_t state, int err)
 {
-  fn_gnutls_transport_set_errno (state, err);
+  gnutls_transport_set_errno (state, err);
 }
 #endif
 
@@ -516,7 +512,7 @@ emacs_gnutls_write (struct Lisp_Process *proc, const char 
*buf, ptrdiff_t nbyte)
 
   while (nbyte > 0)
     {
-      rtnval = fn_gnutls_record_send (state, buf, nbyte);
+      rtnval = gnutls_record_send (state, buf, nbyte);
 
       if (rtnval < 0)
        {
@@ -568,7 +564,7 @@ emacs_gnutls_read (struct Lisp_Process *proc, char *buf, 
ptrdiff_t nbyte)
       proc->gnutls_handshakes_tried = 0;
       return 0;
     }
-  rtnval = fn_gnutls_record_recv (state, buf, nbyte);
+  rtnval = gnutls_record_recv (state, buf, nbyte);
   if (rtnval >= 0)
     return rtnval;
   else if (rtnval == GNUTLS_E_UNEXPECTED_PACKET_LENGTH)
@@ -597,15 +593,17 @@ emacs_gnutls_handle_error (gnutls_session_t session, int 
err)
   if (err >= 0)
     return 1;
 
+  check_memory_full (err);
+
   max_log_level = global_gnutls_log_level;
 
   /* TODO: use gnutls-error-fatalp and gnutls-error-string.  */
 
-  str = fn_gnutls_strerror (err);
+  str = gnutls_strerror (err);
   if (!str)
     str = "unknown";
 
-  if (fn_gnutls_error_is_fatal (err))
+  if (gnutls_error_is_fatal (err))
     {
       ret = 0;
       GNUTLS_LOG2 (1, max_log_level, "fatal error:", str);
@@ -632,9 +630,9 @@ emacs_gnutls_handle_error (gnutls_session_t session, int 
err)
   if (err == GNUTLS_E_WARNING_ALERT_RECEIVED
       || err == GNUTLS_E_FATAL_ALERT_RECEIVED)
     {
-      int alert = fn_gnutls_alert_get (session);
+      int alert = gnutls_alert_get (session);
       int level = (err == GNUTLS_E_FATAL_ALERT_RECEIVED) ? 0 : 1;
-      str = fn_gnutls_alert_get_name (alert);
+      str = gnutls_alert_get_name (alert);
       if (!str)
        str = "unknown";
 
@@ -662,6 +660,7 @@ gnutls_make_error (int err)
       return Qgnutls_e_invalid_session;
     }
 
+  check_memory_full (err);
   return make_number (err);
 }
 
@@ -680,20 +679,20 @@ emacs_gnutls_deinit (Lisp_Object proc)
   if (XPROCESS (proc)->gnutls_x509_cred)
     {
       GNUTLS_LOG (2, log_level, "Deallocating x509 credentials");
-      fn_gnutls_certificate_free_credentials (XPROCESS 
(proc)->gnutls_x509_cred);
+      gnutls_certificate_free_credentials (XPROCESS (proc)->gnutls_x509_cred);
       XPROCESS (proc)->gnutls_x509_cred = NULL;
     }
 
   if (XPROCESS (proc)->gnutls_anon_cred)
     {
       GNUTLS_LOG (2, log_level, "Deallocating anon credentials");
-      fn_gnutls_anon_free_client_credentials (XPROCESS 
(proc)->gnutls_anon_cred);
+      gnutls_anon_free_client_credentials (XPROCESS (proc)->gnutls_anon_cred);
       XPROCESS (proc)->gnutls_anon_cred = NULL;
     }
 
   if (XPROCESS (proc)->gnutls_state)
     {
-      fn_gnutls_deinit (XPROCESS (proc)->gnutls_state);
+      gnutls_deinit (XPROCESS (proc)->gnutls_state);
       XPROCESS (proc)->gnutls_state = NULL;
       if (GNUTLS_INITSTAGE (proc) >= GNUTLS_STAGE_INIT)
        GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_INIT - 1;
@@ -750,7 +749,7 @@ Usage: (gnutls-error-fatalp ERROR)  */)
   if (! TYPE_RANGED_INTEGERP (int, err))
     error ("Not an error symbol or code");
 
-  if (0 == fn_gnutls_error_is_fatal (XINT (err)))
+  if (0 == gnutls_error_is_fatal (XINT (err)))
     return Qnil;
 
   return Qt;
@@ -782,7 +781,7 @@ usage: (gnutls-error-string ERROR)  */)
   if (! TYPE_RANGED_INTEGERP (int, err))
     return build_string ("Not an error symbol or code");
 
-  return build_string (fn_gnutls_strerror (XINT (err)));
+  return build_string (gnutls_strerror (XINT (err)));
 }
 
 DEFUN ("gnutls-deinit", Fgnutls_deinit, Sgnutls_deinit, 1, 1, 0,
@@ -821,7 +820,8 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
 
   /* Version. */
   {
-    int version = fn_gnutls_x509_crt_get_version (cert);
+    int version = gnutls_x509_crt_get_version (cert);
+    check_memory_full (version);
     if (version >= GNUTLS_E_SUCCESS)
       res = nconc2 (res, list2 (intern (":version"),
                                make_number (version)));
@@ -829,11 +829,13 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
 
   /* Serial. */
   buf_size = 0;
-  err = fn_gnutls_x509_crt_get_serial (cert, NULL, &buf_size);
+  err = gnutls_x509_crt_get_serial (cert, NULL, &buf_size);
+  check_memory_full (err);
   if (err == GNUTLS_E_SHORT_MEMORY_BUFFER)
     {
       void *serial = xmalloc (buf_size);
-      err = fn_gnutls_x509_crt_get_serial (cert, serial, &buf_size);
+      err = gnutls_x509_crt_get_serial (cert, serial, &buf_size);
+      check_memory_full (err);
       if (err >= GNUTLS_E_SUCCESS)
        res = nconc2 (res, list2 (intern (":serial-number"),
                                  gnutls_hex_string (serial, buf_size, "")));
@@ -842,11 +844,13 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
 
   /* Issuer. */
   buf_size = 0;
-  err = fn_gnutls_x509_crt_get_issuer_dn (cert, NULL, &buf_size);
+  err = gnutls_x509_crt_get_issuer_dn (cert, NULL, &buf_size);
+  check_memory_full (err);
   if (err == GNUTLS_E_SHORT_MEMORY_BUFFER)
     {
       char *dn = xmalloc (buf_size);
-      err = fn_gnutls_x509_crt_get_issuer_dn (cert, dn, &buf_size);
+      err = gnutls_x509_crt_get_issuer_dn (cert, dn, &buf_size);
+      check_memory_full (err);
       if (err >= GNUTLS_E_SUCCESS)
        res = nconc2 (res, list2 (intern (":issuer"),
                                  make_string (dn, buf_size)));
@@ -859,23 +863,25 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
        that might add 1 to the year length.  */
     char buf[INT_STRLEN_BOUND (int) + 1 + sizeof "-12-31"];
     struct tm t;
-    time_t tim = fn_gnutls_x509_crt_get_activation_time (cert);
+    time_t tim = gnutls_x509_crt_get_activation_time (cert);
 
     if (gmtime_r (&tim, &t) && strftime (buf, sizeof buf, "%Y-%m-%d", &t))
       res = nconc2 (res, list2 (intern (":valid-from"), build_string (buf)));
 
-    tim = fn_gnutls_x509_crt_get_expiration_time (cert);
+    tim = gnutls_x509_crt_get_expiration_time (cert);
     if (gmtime_r (&tim, &t) && strftime (buf, sizeof buf, "%Y-%m-%d", &t))
       res = nconc2 (res, list2 (intern (":valid-to"), build_string (buf)));
   }
 
   /* Subject. */
   buf_size = 0;
-  err = fn_gnutls_x509_crt_get_dn (cert, NULL, &buf_size);
+  err = gnutls_x509_crt_get_dn (cert, NULL, &buf_size);
+  check_memory_full (err);
   if (err == GNUTLS_E_SHORT_MEMORY_BUFFER)
     {
       char *dn = xmalloc (buf_size);
-      err = fn_gnutls_x509_crt_get_dn (cert, dn, &buf_size);
+      err = gnutls_x509_crt_get_dn (cert, dn, &buf_size);
+      check_memory_full (err);
       if (err >= GNUTLS_E_SUCCESS)
        res = nconc2 (res, list2 (intern (":subject"),
                                  make_string (dn, buf_size)));
@@ -888,16 +894,17 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
   {
     unsigned int bits;
 
-    err = fn_gnutls_x509_crt_get_pk_algorithm (cert, &bits);
+    err = gnutls_x509_crt_get_pk_algorithm (cert, &bits);
+    check_memory_full (err);
     if (err >= GNUTLS_E_SUCCESS)
       {
-       const char *name = fn_gnutls_pk_algorithm_get_name (err);
+       const char *name = gnutls_pk_algorithm_get_name (err);
        if (name)
          res = nconc2 (res, list2 (intern (":public-key-algorithm"),
                                    build_string (name)));
 
-       name = fn_gnutls_sec_param_get_name (fn_gnutls_pk_bits_to_sec_param
-                                            (err, bits));
+       name = gnutls_sec_param_get_name (gnutls_pk_bits_to_sec_param
+                                         (err, bits));
        res = nconc2 (res, list2 (intern (":certificate-security-level"),
                                  build_string (name)));
       }
@@ -905,11 +912,13 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
 
   /* Unique IDs. */
   buf_size = 0;
-  err = fn_gnutls_x509_crt_get_issuer_unique_id (cert, NULL, &buf_size);
+  err = gnutls_x509_crt_get_issuer_unique_id (cert, NULL, &buf_size);
+  check_memory_full (err);
   if (err == GNUTLS_E_SHORT_MEMORY_BUFFER)
     {
       char *buf = xmalloc (buf_size);
-      err = fn_gnutls_x509_crt_get_issuer_unique_id (cert, buf, &buf_size);
+      err = gnutls_x509_crt_get_issuer_unique_id (cert, buf, &buf_size);
+      check_memory_full (err);
       if (err >= GNUTLS_E_SUCCESS)
        res = nconc2 (res, list2 (intern (":issuer-unique-id"),
                                  make_string (buf, buf_size)));
@@ -917,11 +926,13 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
     }
 
   buf_size = 0;
-  err = fn_gnutls_x509_crt_get_subject_unique_id (cert, NULL, &buf_size);
+  err = gnutls_x509_crt_get_subject_unique_id (cert, NULL, &buf_size);
+  check_memory_full (err);
   if (err == GNUTLS_E_SHORT_MEMORY_BUFFER)
     {
       char *buf = xmalloc (buf_size);
-      err = fn_gnutls_x509_crt_get_subject_unique_id (cert, buf, &buf_size);
+      err = gnutls_x509_crt_get_subject_unique_id (cert, buf, &buf_size);
+      check_memory_full (err);
       if (err >= GNUTLS_E_SUCCESS)
        res = nconc2 (res, list2 (intern (":subject-unique-id"),
                                  make_string (buf, buf_size)));
@@ -930,10 +941,11 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
 #endif
 
   /* Signature. */
-  err = fn_gnutls_x509_crt_get_signature_algorithm (cert);
+  err = gnutls_x509_crt_get_signature_algorithm (cert);
+  check_memory_full (err);
   if (err >= GNUTLS_E_SUCCESS)
     {
-      const char *name = fn_gnutls_sign_get_name (err);
+      const char *name = gnutls_sign_get_name (err);
       if (name)
        res = nconc2 (res, list2 (intern (":signature-algorithm"),
                                  build_string (name)));
@@ -941,11 +953,13 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
 
   /* Public key ID. */
   buf_size = 0;
-  err = fn_gnutls_x509_crt_get_key_id (cert, 0, NULL, &buf_size);
+  err = gnutls_x509_crt_get_key_id (cert, 0, NULL, &buf_size);
+  check_memory_full (err);
   if (err == GNUTLS_E_SHORT_MEMORY_BUFFER)
     {
       void *buf = xmalloc (buf_size);
-      err = fn_gnutls_x509_crt_get_key_id (cert, 0, buf, &buf_size);
+      err = gnutls_x509_crt_get_key_id (cert, 0, buf, &buf_size);
+      check_memory_full (err);
       if (err >= GNUTLS_E_SUCCESS)
        res = nconc2 (res, list2 (intern (":public-key-id"),
                                  gnutls_hex_string (buf, buf_size, "sha1:")));
@@ -954,13 +968,15 @@ gnutls_certificate_details (gnutls_x509_crt_t cert)
 
   /* Certificate fingerprint. */
   buf_size = 0;
-  err = fn_gnutls_x509_crt_get_fingerprint (cert, GNUTLS_DIG_SHA1,
-                                           NULL, &buf_size);
+  err = gnutls_x509_crt_get_fingerprint (cert, GNUTLS_DIG_SHA1,
+                                        NULL, &buf_size);
+  check_memory_full (err);
   if (err == GNUTLS_E_SHORT_MEMORY_BUFFER)
     {
       void *buf = xmalloc (buf_size);
-      err = fn_gnutls_x509_crt_get_fingerprint (cert, GNUTLS_DIG_SHA1,
-                                               buf, &buf_size);
+      err = gnutls_x509_crt_get_fingerprint (cert, GNUTLS_DIG_SHA1,
+                                            buf, &buf_size);
+      check_memory_full (err);
       if (err >= GNUTLS_E_SUCCESS)
        res = nconc2 (res, list2 (intern (":certificate-id"),
                                  gnutls_hex_string (buf, buf_size, "sha1:")));
@@ -1061,7 +1077,8 @@ The return value is a property list with top-level keys 
:warnings and
 
   /* Diffie-Hellman prime bits. */
   {
-    int bits = fn_gnutls_dh_get_prime_bits (state);
+    int bits = gnutls_dh_get_prime_bits (state);
+    check_memory_full (bits);
     if (bits > 0)
       result = nconc2 (result, list2 (intern (":diffie-hellman-prime-bits"),
                                      make_number (bits)));
@@ -1070,26 +1087,26 @@ The return value is a property list with top-level keys 
:warnings and
   /* Key exchange. */
   result = nconc2
     (result, list2 (intern (":key-exchange"),
-                   build_string (fn_gnutls_kx_get_name
-                                 (fn_gnutls_kx_get (state)))));
+                   build_string (gnutls_kx_get_name
+                                 (gnutls_kx_get (state)))));
 
   /* Protocol name. */
   result = nconc2
     (result, list2 (intern (":protocol"),
-                   build_string (fn_gnutls_protocol_get_name
-                                 (fn_gnutls_protocol_get_version (state)))));
+                   build_string (gnutls_protocol_get_name
+                                 (gnutls_protocol_get_version (state)))));
 
   /* Cipher name. */
   result = nconc2
     (result, list2 (intern (":cipher"),
-                   build_string (fn_gnutls_cipher_get_name
-                                 (fn_gnutls_cipher_get (state)))));
+                   build_string (gnutls_cipher_get_name
+                                 (gnutls_cipher_get (state)))));
 
   /* MAC name. */
   result = nconc2
     (result, list2 (intern (":mac"),
-                   build_string (fn_gnutls_mac_get_name
-                                 (fn_gnutls_mac_get (state)))));
+                   build_string (gnutls_mac_get_name
+                                 (gnutls_mac_get (state)))));
 
 
   return result;
@@ -1104,11 +1121,8 @@ emacs_gnutls_global_init (void)
   int ret = GNUTLS_E_SUCCESS;
 
   if (!gnutls_global_initialized)
-    {
-      fn_gnutls_global_set_mem_functions (xmalloc, xmalloc, NULL,
-                                         xrealloc, xfree);
-      ret = fn_gnutls_global_init ();
-    }
+    ret = gnutls_global_init ();
+
   gnutls_global_initialized = 1;
 
   return gnutls_make_error (ret);
@@ -1257,11 +1271,11 @@ one trustfile (usually a CA bundle).  */)
 
   if (TYPE_RANGED_INTEGERP (int, loglevel))
     {
-      fn_gnutls_global_set_log_function (gnutls_log_function);
+      gnutls_global_set_log_function (gnutls_log_function);
 #ifdef HAVE_GNUTLS3
-      fn_gnutls_global_set_audit_log_function (gnutls_audit_log_function);
+      gnutls_global_set_audit_log_function (gnutls_audit_log_function);
 #endif
-      fn_gnutls_global_set_log_level (XINT (loglevel));
+      gnutls_global_set_log_level (XINT (loglevel));
       max_log_level = XINT (loglevel);
       XPROCESS (proc)->gnutls_log_level = max_log_level;
     }
@@ -1291,7 +1305,7 @@ one trustfile (usually a CA bundle).  */)
       unsigned int gnutls_verify_flags = GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT;
 
       GNUTLS_LOG (2, max_log_level, "allocating x509 credentials");
-      fn_gnutls_certificate_allocate_credentials (&x509_cred);
+      check_memory_full (gnutls_certificate_allocate_credentials (&x509_cred));
       XPROCESS (proc)->gnutls_x509_cred = x509_cred;
 
       verify_flags = Fplist_get (proplist, QCgnutls_bootprop_verify_flags);
@@ -1305,12 +1319,12 @@ one trustfile (usually a CA bundle).  */)
       else
        GNUTLS_LOG (2, max_log_level, "ignoring invalid verify-flags");
 
-      fn_gnutls_certificate_set_verify_flags (x509_cred, gnutls_verify_flags);
+      gnutls_certificate_set_verify_flags (x509_cred, gnutls_verify_flags);
     }
   else /* Qgnutls_anon: */
     {
       GNUTLS_LOG (2, max_log_level, "allocating anon credentials");
-      fn_gnutls_anon_allocate_client_credentials (&anon_cred);
+      check_memory_full (gnutls_anon_allocate_client_credentials (&anon_cred));
       XPROCESS (proc)->gnutls_anon_cred = anon_cred;
     }
 
@@ -1324,10 +1338,13 @@ one trustfile (usually a CA bundle).  */)
 
 #if GNUTLS_VERSION_MAJOR +                                     \
   (GNUTLS_VERSION_MINOR > 0 || GNUTLS_VERSION_PATCH >= 20) > 3
-      ret = fn_gnutls_certificate_set_x509_system_trust (x509_cred);
+      ret = gnutls_certificate_set_x509_system_trust (x509_cred);
       if (ret < GNUTLS_E_SUCCESS)
-       GNUTLS_LOG2i (4, max_log_level,
-                     "setting system trust failed with code ", ret);
+       {
+         check_memory_full (ret);
+         GNUTLS_LOG2i (4, max_log_level,
+                       "setting system trust failed with code ", ret);
+       }
 #endif
 
       for (tail = trustfiles; CONSP (tail); tail = XCDR (tail))
@@ -1344,7 +1361,7 @@ one trustfile (usually a CA bundle).  */)
                 name using the current ANSI codepage.  */
              trustfile = ansi_encode_filename (trustfile);
 #endif
-             ret = fn_gnutls_certificate_set_x509_trust_file
+             ret = gnutls_certificate_set_x509_trust_file
                (x509_cred,
                 SSDATA (trustfile),
                 file_format);
@@ -1370,7 +1387,7 @@ one trustfile (usually a CA bundle).  */)
 #ifdef WINDOWSNT
              crlfile = ansi_encode_filename (crlfile);
 #endif
-             ret = fn_gnutls_certificate_set_x509_crl_file
+             ret = gnutls_certificate_set_x509_crl_file
                (x509_cred, SSDATA (crlfile), file_format);
 
              if (ret < GNUTLS_E_SUCCESS)
@@ -1399,7 +1416,7 @@ one trustfile (usually a CA bundle).  */)
              keyfile = ansi_encode_filename (keyfile);
              certfile = ansi_encode_filename (certfile);
 #endif
-             ret = fn_gnutls_certificate_set_x509_key_file
+             ret = gnutls_certificate_set_x509_key_file
                (x509_cred, SSDATA (certfile), SSDATA (keyfile), file_format);
 
              if (ret < GNUTLS_E_SUCCESS)
@@ -1421,7 +1438,7 @@ one trustfile (usually a CA bundle).  */)
   /* Call gnutls_init here: */
 
   GNUTLS_LOG (1, max_log_level, "gnutls_init");
-  ret = fn_gnutls_init (&state, GNUTLS_CLIENT);
+  ret = gnutls_init (&state, GNUTLS_CLIENT);
   XPROCESS (proc)->gnutls_state = state;
   if (ret < GNUTLS_E_SUCCESS)
     return gnutls_make_error (ret);
@@ -1440,27 +1457,25 @@ one trustfile (usually a CA bundle).  */)
     }
 
   GNUTLS_LOG (1, max_log_level, "setting the priority string");
-  ret = fn_gnutls_priority_set_direct (state,
-                                      priority_string_ptr,
-                                      NULL);
+  ret = gnutls_priority_set_direct (state, priority_string_ptr, NULL);
   if (ret < GNUTLS_E_SUCCESS)
     return gnutls_make_error (ret);
 
   GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_PRIORITY;
 
   if (INTEGERP (prime_bits))
-    fn_gnutls_dh_set_prime_bits (state, XUINT (prime_bits));
+    gnutls_dh_set_prime_bits (state, XUINT (prime_bits));
 
   ret = EQ (type, Qgnutls_x509pki)
-    ? fn_gnutls_credentials_set (state, GNUTLS_CRD_CERTIFICATE, x509_cred)
-    : fn_gnutls_credentials_set (state, GNUTLS_CRD_ANON, anon_cred);
+    ? gnutls_credentials_set (state, GNUTLS_CRD_CERTIFICATE, x509_cred)
+    : gnutls_credentials_set (state, GNUTLS_CRD_ANON, anon_cred);
   if (ret < GNUTLS_E_SUCCESS)
     return gnutls_make_error (ret);
 
   if (!gnutls_ip_address_p (c_hostname))
     {
-      ret = fn_gnutls_server_name_set (state, GNUTLS_NAME_DNS, c_hostname,
-                                      strlen (c_hostname));
+      ret = gnutls_server_name_set (state, GNUTLS_NAME_DNS, c_hostname,
+                                   strlen (c_hostname));
       if (ret < GNUTLS_E_SUCCESS)
        return gnutls_make_error (ret);
     }
@@ -1476,7 +1491,7 @@ one trustfile (usually a CA bundle).  */)
      check of the certificate's hostname with
      gnutls_x509_crt_check_hostname against :hostname.  */
 
-  ret = fn_gnutls_certificate_verify_peers2 (state, &peer_verification);
+  ret = gnutls_certificate_verify_peers2 (state, &peer_verification);
   if (ret < GNUTLS_E_SUCCESS)
     return gnutls_make_error (ret);
 
@@ -1514,47 +1529,50 @@ one trustfile (usually a CA bundle).  */)
   /* Up to here the process is the same for X.509 certificates and
      OpenPGP keys.  From now on X.509 certificates are assumed.  This
      can be easily extended to work with openpgp keys as well.  */
-  if (fn_gnutls_certificate_type_get (state) == GNUTLS_CRT_X509)
+  if (gnutls_certificate_type_get (state) == GNUTLS_CRT_X509)
     {
       gnutls_x509_crt_t gnutls_verify_cert;
       const gnutls_datum_t *gnutls_verify_cert_list;
       unsigned int gnutls_verify_cert_list_size;
 
-      ret = fn_gnutls_x509_crt_init (&gnutls_verify_cert);
+      ret = gnutls_x509_crt_init (&gnutls_verify_cert);
       if (ret < GNUTLS_E_SUCCESS)
        return gnutls_make_error (ret);
 
       gnutls_verify_cert_list =
-       fn_gnutls_certificate_get_peers (state, &gnutls_verify_cert_list_size);
+       gnutls_certificate_get_peers (state, &gnutls_verify_cert_list_size);
 
       if (gnutls_verify_cert_list == NULL)
        {
-         fn_gnutls_x509_crt_deinit (gnutls_verify_cert);
+         gnutls_x509_crt_deinit (gnutls_verify_cert);
          emacs_gnutls_deinit (proc);
          error ("No x509 certificate was found\n");
        }
 
       /* We only check the first certificate in the given chain.  */
-      ret = fn_gnutls_x509_crt_import (gnutls_verify_cert,
+      ret = gnutls_x509_crt_import (gnutls_verify_cert,
                                       &gnutls_verify_cert_list[0],
                                       GNUTLS_X509_FMT_DER);
 
       if (ret < GNUTLS_E_SUCCESS)
        {
-         fn_gnutls_x509_crt_deinit (gnutls_verify_cert);
+         gnutls_x509_crt_deinit (gnutls_verify_cert);
          return gnutls_make_error (ret);
        }
 
       XPROCESS (proc)->gnutls_certificate = gnutls_verify_cert;
 
-      if (!fn_gnutls_x509_crt_check_hostname (gnutls_verify_cert, c_hostname))
+      int err = gnutls_x509_crt_check_hostname (gnutls_verify_cert,
+                                               c_hostname);
+      check_memory_full (err);
+      if (!err)
        {
          XPROCESS (proc)->gnutls_extra_peer_verification |=
            CERTIFICATE_NOT_MATCHING;
           if (verify_error_all
               || !NILP (Fmember (QCgnutls_bootprop_hostname, verify_error)))
             {
-             fn_gnutls_x509_crt_deinit (gnutls_verify_cert);
+             gnutls_x509_crt_deinit (gnutls_verify_cert);
              emacs_gnutls_deinit (proc);
              error ("The x509 certificate does not match \"%s\"", c_hostname);
             }
@@ -1595,10 +1613,9 @@ This function may also return `gnutls-e-again', or
 
   state = XPROCESS (proc)->gnutls_state;
 
-  fn_gnutls_x509_crt_deinit (XPROCESS (proc)->gnutls_certificate);
+  gnutls_x509_crt_deinit (XPROCESS (proc)->gnutls_certificate);
 
-  ret = fn_gnutls_bye (state,
-                      NILP (cont) ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
+  ret = gnutls_bye (state, NILP (cont) ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
 
   return gnutls_make_error (ret);
 }
diff --git a/src/image.c b/src/image.c
index a73a725..4cba886 100644
--- a/src/image.c
+++ b/src/image.c
@@ -1859,19 +1859,6 @@ mark_image_cache (struct image_cache *c)
                          X / NS / W32 support code
  ***********************************************************************/
 
-#ifdef WINDOWSNT
-
-/* Macro for defining functions that will be loaded from image DLLs.  */
-#define DEF_IMGLIB_FN(rettype,func,args) static rettype (FAR CDECL 
*fn_##func)args
-
-/* Macro for loading those image functions from the library.  */
-#define LOAD_IMGLIB_FN(lib,func) {                                     \
-    fn_##func = (void *) GetProcAddress (lib, #func);                  \
-    if (!fn_##func) return 0;                                          \
-  }
-
-#endif /* WINDOWSNT */
-
 /* Return true if XIMG's size WIDTH x HEIGHT doesn't break the
    windowing system.
    WIDTH and HEIGHT must both be positive.
@@ -3377,12 +3364,14 @@ xpm_free_colors (Display *dpy, Colormap cmap, Pixel 
*pixels, int npixels, void *
 
 /* XPM library details.  */
 
-DEF_IMGLIB_FN (void, XpmFreeAttributes, (XpmAttributes *));
-DEF_IMGLIB_FN (int, XpmCreateImageFromBuffer, (Display *, char *, xpm_XImage 
**,
-                                         xpm_XImage **, XpmAttributes *));
-DEF_IMGLIB_FN (int, XpmReadFileToImage, (Display *, char *, xpm_XImage **,
-                                   xpm_XImage **, XpmAttributes *));
-DEF_IMGLIB_FN (void, XImageFree, (xpm_XImage *));
+DEF_DLL_FN (void, XpmFreeAttributes, (XpmAttributes *));
+DEF_DLL_FN (int, XpmCreateImageFromBuffer,
+           (Display *, char *, xpm_XImage **,
+            xpm_XImage **, XpmAttributes *));
+DEF_DLL_FN (int, XpmReadFileToImage,
+           (Display *, char *, xpm_XImage **,
+            xpm_XImage **, XpmAttributes *));
+DEF_DLL_FN (void, XImageFree, (xpm_XImage *));
 
 static bool
 init_xpm_functions (void)
@@ -3392,22 +3381,24 @@ init_xpm_functions (void)
   if (!(library = w32_delayed_load (Qxpm)))
     return 0;
 
-  LOAD_IMGLIB_FN (library, XpmFreeAttributes);
-  LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
-  LOAD_IMGLIB_FN (library, XpmReadFileToImage);
-  LOAD_IMGLIB_FN (library, XImageFree);
+  LOAD_DLL_FN (library, XpmFreeAttributes);
+  LOAD_DLL_FN (library, XpmCreateImageFromBuffer);
+  LOAD_DLL_FN (library, XpmReadFileToImage);
+  LOAD_DLL_FN (library, XImageFree);
   return 1;
 }
 
-#endif /* WINDOWSNT */
+# undef XImageFree
+# undef XpmCreateImageFromBuffer
+# undef XpmFreeAttributes
+# undef XpmReadFileToImage
 
-#if defined HAVE_NTGUI && !defined WINDOWSNT
-/* Glue for code below */
-#define fn_XpmReadFileToImage XpmReadFileToImage
-#define fn_XpmCreateImageFromBuffer XpmCreateImageFromBuffer
-#define fn_XImageFree XImageFree
-#define fn_XpmFreeAttributes XpmFreeAttributes
-#endif /* HAVE_NTGUI && !WINDOWSNT */
+# define XImageFree fn_XImageFree
+# define XpmCreateImageFromBuffer fn_XpmCreateImageFromBuffer
+# define XpmFreeAttributes fn_XpmFreeAttributes
+# define XpmReadFileToImage fn_XpmReadFileToImage
+
+#endif /* WINDOWSNT */
 
 /* Value is true if COLOR_SYMBOLS is a valid color symbols list
    for XPM images.  Such a list must consist of conses whose car and
@@ -3624,9 +3615,9 @@ xpm_load (struct frame *f, struct image *img)
 #endif
       /* XpmReadFileToPixmap is not available in the Windows port of
         libxpm.  But XpmReadFileToImage almost does what we want.  */
-      rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
-                                 &xpm_image, &xpm_mask,
-                                 &attrs);
+      rc = XpmReadFileToImage (&hdc, SDATA (file),
+                              &xpm_image, &xpm_mask,
+                              &attrs);
 #else
       rc = XpmReadFileToImage (FRAME_X_DISPLAY (f), SSDATA (file),
                               &img->ximg, &img->mask_img,
@@ -3648,9 +3639,9 @@ xpm_load (struct frame *f, struct image *img)
 #ifdef HAVE_NTGUI
       /* XpmCreatePixmapFromBuffer is not available in the Windows port
         of libxpm.  But XpmCreateImageFromBuffer almost does what we want.  */
-      rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
-                                       &xpm_image, &xpm_mask,
-                                       &attrs);
+      rc = XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
+                                    &xpm_image, &xpm_mask,
+                                    &attrs);
 #else
       rc = XpmCreateImageFromBuffer (FRAME_X_DISPLAY (f), SSDATA (buffer),
                                     &img->ximg, &img->mask_img,
@@ -3699,7 +3690,7 @@ xpm_load (struct frame *f, struct image *img)
          img->pixmap = xpm_image->bitmap;
          /* XImageFree in libXpm frees XImage struct without destroying
             the bitmap, which is what we want.  */
-         fn_XImageFree (xpm_image);
+         XImageFree (xpm_image);
        }
       if (xpm_mask && xpm_mask->bitmap)
        {
@@ -3713,7 +3704,7 @@ xpm_load (struct frame *f, struct image *img)
          SelectObject (hdc, old_obj);
 
          img->mask = xpm_mask->bitmap;
-         fn_XImageFree (xpm_mask);
+         XImageFree (xpm_mask);
          DeleteDC (hdc);
        }
 
@@ -3737,11 +3728,7 @@ xpm_load (struct frame *f, struct image *img)
       eassert (img->width > 0 && img->height > 0);
 
       /* The call to XpmFreeAttributes below frees attrs.alloc_pixels.  */
-#ifdef HAVE_NTGUI
-      fn_XpmFreeAttributes (&attrs);
-#else
       XpmFreeAttributes (&attrs);
-#endif /* HAVE_NTGUI */
 
 #ifdef HAVE_X_WINDOWS
       /* Maybe fill in the background field while we have ximg handy.  */
@@ -5535,39 +5522,42 @@ png_image_p (Lisp_Object object)
 
 #if defined HAVE_PNG && !defined HAVE_NS
 
-#ifdef WINDOWSNT
+# ifdef WINDOWSNT
 /* PNG library details.  */
 
-DEF_IMGLIB_FN (png_voidp, png_get_io_ptr, (png_structp));
-DEF_IMGLIB_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
-DEF_IMGLIB_FN (png_structp, png_create_read_struct, (png_const_charp, 
png_voidp,
-                                                    png_error_ptr, 
png_error_ptr));
-DEF_IMGLIB_FN (png_infop, png_create_info_struct, (png_structp));
-DEF_IMGLIB_FN (void, png_destroy_read_struct, (png_structpp, png_infopp, 
png_infopp));
-DEF_IMGLIB_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
-DEF_IMGLIB_FN (void, png_set_sig_bytes, (png_structp, int));
-DEF_IMGLIB_FN (void, png_read_info, (png_structp, png_infop));
-DEF_IMGLIB_FN (png_uint_32, png_get_IHDR, (png_structp, png_infop,
-                             png_uint_32 *, png_uint_32 *,
-                             int *, int *, int *, int *, int *));
-DEF_IMGLIB_FN (png_uint_32, png_get_valid, (png_structp, png_infop, 
png_uint_32));
-DEF_IMGLIB_FN (void, png_set_strip_16, (png_structp));
-DEF_IMGLIB_FN (void, png_set_expand, (png_structp));
-DEF_IMGLIB_FN (void, png_set_gray_to_rgb, (png_structp));
-DEF_IMGLIB_FN (void, png_set_background, (png_structp, png_color_16p,
-                                   int, int, double));
-DEF_IMGLIB_FN (png_uint_32, png_get_bKGD, (png_structp, png_infop, 
png_color_16p *));
-DEF_IMGLIB_FN (void, png_read_update_info, (png_structp, png_infop));
-DEF_IMGLIB_FN (png_byte, png_get_channels, (png_structp, png_infop));
-DEF_IMGLIB_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
-DEF_IMGLIB_FN (void, png_read_image, (png_structp, png_bytepp));
-DEF_IMGLIB_FN (void, png_read_end, (png_structp, png_infop));
-DEF_IMGLIB_FN (void, png_error, (png_structp, png_const_charp));
-
-#if (PNG_LIBPNG_VER >= 10500)
-DEF_IMGLIB_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
-DEF_IMGLIB_FN (jmp_buf *, png_set_longjmp_fn, (png_structp, png_longjmp_ptr, 
size_t));
-#endif /* libpng version >= 1.5 */
+DEF_DLL_FN (png_voidp, png_get_io_ptr, (png_structp));
+DEF_DLL_FN (int, png_sig_cmp, (png_bytep, png_size_t, png_size_t));
+DEF_DLL_FN (png_structp, png_create_read_struct,
+           (png_const_charp, png_voidp, png_error_ptr, png_error_ptr));
+DEF_DLL_FN (png_infop, png_create_info_struct, (png_structp));
+DEF_DLL_FN (void, png_destroy_read_struct,
+           (png_structpp, png_infopp, png_infopp));
+DEF_DLL_FN (void, png_set_read_fn, (png_structp, png_voidp, png_rw_ptr));
+DEF_DLL_FN (void, png_set_sig_bytes, (png_structp, int));
+DEF_DLL_FN (void, png_read_info, (png_structp, png_infop));
+DEF_DLL_FN (png_uint_32, png_get_IHDR,
+           (png_structp, png_infop, png_uint_32 *, png_uint_32 *,
+            int *, int *, int *, int *, int *));
+DEF_DLL_FN (png_uint_32, png_get_valid, (png_structp, png_infop, png_uint_32));
+DEF_DLL_FN (void, png_set_strip_16, (png_structp));
+DEF_DLL_FN (void, png_set_expand, (png_structp));
+DEF_DLL_FN (void, png_set_gray_to_rgb, (png_structp));
+DEF_DLL_FN (void, png_set_background,
+           (png_structp, png_color_16p, int, int, double));
+DEF_DLL_FN (png_uint_32, png_get_bKGD,
+           (png_structp, png_infop, png_color_16p *));
+DEF_DLL_FN (void, png_read_update_info, (png_structp, png_infop));
+DEF_DLL_FN (png_byte, png_get_channels, (png_structp, png_infop));
+DEF_DLL_FN (png_size_t, png_get_rowbytes, (png_structp, png_infop));
+DEF_DLL_FN (void, png_read_image, (png_structp, png_bytepp));
+DEF_DLL_FN (void, png_read_end, (png_structp, png_infop));
+DEF_DLL_FN (void, png_error, (png_structp, png_const_charp));
+
+#  if (PNG_LIBPNG_VER >= 10500)
+DEF_DLL_FN (void, png_longjmp, (png_structp, int)) PNG_NORETURN;
+DEF_DLL_FN (jmp_buf *, png_set_longjmp_fn,
+           (png_structp, png_longjmp_ptr, size_t));
+#  endif /* libpng version >= 1.5 */
 
 static bool
 init_png_functions (void)
@@ -5577,87 +5567,107 @@ init_png_functions (void)
   if (!(library = w32_delayed_load (Qpng)))
     return 0;
 
-  LOAD_IMGLIB_FN (library, png_get_io_ptr);
-  LOAD_IMGLIB_FN (library, png_sig_cmp);
-  LOAD_IMGLIB_FN (library, png_create_read_struct);
-  LOAD_IMGLIB_FN (library, png_create_info_struct);
-  LOAD_IMGLIB_FN (library, png_destroy_read_struct);
-  LOAD_IMGLIB_FN (library, png_set_read_fn);
-  LOAD_IMGLIB_FN (library, png_set_sig_bytes);
-  LOAD_IMGLIB_FN (library, png_read_info);
-  LOAD_IMGLIB_FN (library, png_get_IHDR);
-  LOAD_IMGLIB_FN (library, png_get_valid);
-  LOAD_IMGLIB_FN (library, png_set_strip_16);
-  LOAD_IMGLIB_FN (library, png_set_expand);
-  LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
-  LOAD_IMGLIB_FN (library, png_set_background);
-  LOAD_IMGLIB_FN (library, png_get_bKGD);
-  LOAD_IMGLIB_FN (library, png_read_update_info);
-  LOAD_IMGLIB_FN (library, png_get_channels);
-  LOAD_IMGLIB_FN (library, png_get_rowbytes);
-  LOAD_IMGLIB_FN (library, png_read_image);
-  LOAD_IMGLIB_FN (library, png_read_end);
-  LOAD_IMGLIB_FN (library, png_error);
-
-#if (PNG_LIBPNG_VER >= 10500)
-  LOAD_IMGLIB_FN (library, png_longjmp);
-  LOAD_IMGLIB_FN (library, png_set_longjmp_fn);
-#endif /* libpng version >= 1.5 */
+  LOAD_DLL_FN (library, png_get_io_ptr);
+  LOAD_DLL_FN (library, png_sig_cmp);
+  LOAD_DLL_FN (library, png_create_read_struct);
+  LOAD_DLL_FN (library, png_create_info_struct);
+  LOAD_DLL_FN (library, png_destroy_read_struct);
+  LOAD_DLL_FN (library, png_set_read_fn);
+  LOAD_DLL_FN (library, png_set_sig_bytes);
+  LOAD_DLL_FN (library, png_read_info);
+  LOAD_DLL_FN (library, png_get_IHDR);
+  LOAD_DLL_FN (library, png_get_valid);
+  LOAD_DLL_FN (library, png_set_strip_16);
+  LOAD_DLL_FN (library, png_set_expand);
+  LOAD_DLL_FN (library, png_set_gray_to_rgb);
+  LOAD_DLL_FN (library, png_set_background);
+  LOAD_DLL_FN (library, png_get_bKGD);
+  LOAD_DLL_FN (library, png_read_update_info);
+  LOAD_DLL_FN (library, png_get_channels);
+  LOAD_DLL_FN (library, png_get_rowbytes);
+  LOAD_DLL_FN (library, png_read_image);
+  LOAD_DLL_FN (library, png_read_end);
+  LOAD_DLL_FN (library, png_error);
+
+#  if (PNG_LIBPNG_VER >= 10500)
+  LOAD_DLL_FN (library, png_longjmp);
+  LOAD_DLL_FN (library, png_set_longjmp_fn);
+#  endif /* libpng version >= 1.5 */
 
   return 1;
 }
-#else
-
-#define fn_png_get_io_ptr              png_get_io_ptr
-#define fn_png_sig_cmp                 png_sig_cmp
-#define fn_png_create_read_struct      png_create_read_struct
-#define fn_png_create_info_struct      png_create_info_struct
-#define fn_png_destroy_read_struct     png_destroy_read_struct
-#define fn_png_set_read_fn             png_set_read_fn
-#define fn_png_set_sig_bytes           png_set_sig_bytes
-#define fn_png_read_info               png_read_info
-#define fn_png_get_IHDR                        png_get_IHDR
-#define fn_png_get_valid               png_get_valid
-#define fn_png_set_strip_16            png_set_strip_16
-#define fn_png_set_expand              png_set_expand
-#define fn_png_set_gray_to_rgb         png_set_gray_to_rgb
-#define fn_png_set_background          png_set_background
-#define fn_png_get_bKGD                        png_get_bKGD
-#define fn_png_read_update_info                png_read_update_info
-#define fn_png_get_channels            png_get_channels
-#define fn_png_get_rowbytes            png_get_rowbytes
-#define fn_png_read_image              png_read_image
-#define fn_png_read_end                        png_read_end
-#define fn_png_error                   png_error
-
-#if (PNG_LIBPNG_VER >= 10500)
-#define fn_png_longjmp                 png_longjmp
-#define fn_png_set_longjmp_fn          png_set_longjmp_fn
-#endif /* libpng version >= 1.5 */
 
-#endif /* WINDOWSNT */
+#  undef png_create_info_struct
+#  undef png_create_read_struct
+#  undef png_destroy_read_struct
+#  undef png_error
+#  undef png_get_bKGD
+#  undef png_get_channels
+#  undef png_get_IHDR
+#  undef png_get_io_ptr
+#  undef png_get_rowbytes
+#  undef png_get_valid
+#  undef png_longjmp
+#  undef png_read_end
+#  undef png_read_image
+#  undef png_read_info
+#  undef png_read_update_info
+#  undef png_set_background
+#  undef png_set_expand
+#  undef png_set_gray_to_rgb
+#  undef png_set_longjmp_fn
+#  undef png_set_read_fn
+#  undef png_set_sig_bytes
+#  undef png_set_strip_16
+#  undef png_sig_cmp
+
+#  define png_create_info_struct fn_png_create_info_struct
+#  define png_create_read_struct fn_png_create_read_struct
+#  define png_destroy_read_struct fn_png_destroy_read_struct
+#  define png_error fn_png_error
+#  define png_get_bKGD fn_png_get_bKGD
+#  define png_get_channels fn_png_get_channels
+#  define png_get_IHDR fn_png_get_IHDR
+#  define png_get_io_ptr fn_png_get_io_ptr
+#  define png_get_rowbytes fn_png_get_rowbytes
+#  define png_get_valid fn_png_get_valid
+#  define png_longjmp fn_png_longjmp
+#  define png_read_end fn_png_read_end
+#  define png_read_image fn_png_read_image
+#  define png_read_info fn_png_read_info
+#  define png_read_update_info fn_png_read_update_info
+#  define png_set_background fn_png_set_background
+#  define png_set_expand fn_png_set_expand
+#  define png_set_gray_to_rgb fn_png_set_gray_to_rgb
+#  define png_set_longjmp_fn fn_png_set_longjmp_fn
+#  define png_set_read_fn fn_png_set_read_fn
+#  define png_set_sig_bytes fn_png_set_sig_bytes
+#  define png_set_strip_16 fn_png_set_strip_16
+#  define png_sig_cmp fn_png_sig_cmp
+
+# endif /* WINDOWSNT */
 
 /* Fast implementations of setjmp and longjmp.  Although setjmp and longjmp
    will do, POSIX _setjmp and _longjmp (if available) are often faster.
    Do not use sys_setjmp, as PNG supports only jmp_buf.
    It's OK if the longjmp substitute restores the signal mask.  */
-#ifdef HAVE__SETJMP
-# define FAST_SETJMP(j) _setjmp (j)
-# define FAST_LONGJMP _longjmp
-#else
-# define FAST_SETJMP(j) setjmp (j)
-# define FAST_LONGJMP longjmp
-#endif
-
-#if PNG_LIBPNG_VER < 10500
-#define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
-#define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
-#else
+# ifdef HAVE__SETJMP
+#  define FAST_SETJMP(j) _setjmp (j)
+#  define FAST_LONGJMP _longjmp
+# else
+#  define FAST_SETJMP(j) setjmp (j)
+#  define FAST_LONGJMP longjmp
+# endif
+
+# if PNG_LIBPNG_VER < 10500
+#  define PNG_LONGJMP(ptr) FAST_LONGJMP ((ptr)->jmpbuf, 1)
+#  define PNG_JMPBUF(ptr) ((ptr)->jmpbuf)
+# else
 /* In libpng version 1.5, the jmpbuf member is hidden. (Bug#7908)  */
-#define PNG_LONGJMP(ptr) fn_png_longjmp (ptr, 1)
-#define PNG_JMPBUF(ptr) \
-  (*fn_png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
-#endif
+#  define PNG_LONGJMP(ptr) png_longjmp (ptr, 1)
+#  define PNG_JMPBUF(ptr) \
+     (*png_set_longjmp_fn (ptr, FAST_LONGJMP, sizeof (jmp_buf)))
+# endif
 
 /* Error and warning handlers installed when the PNG library
    is initialized.  */
@@ -5697,10 +5707,10 @@ struct png_memory_storage
 static void
 png_read_from_memory (png_structp png_ptr, png_bytep data, png_size_t length)
 {
-  struct png_memory_storage *tbr = fn_png_get_io_ptr (png_ptr);
+  struct png_memory_storage *tbr = png_get_io_ptr (png_ptr);
 
   if (length > tbr->len - tbr->index)
-    fn_png_error (png_ptr, "Read error");
+    png_error (png_ptr, "Read error");
 
   memcpy (data, tbr->bytes + tbr->index, length);
   tbr->index = tbr->index + length;
@@ -5714,10 +5724,10 @@ png_read_from_memory (png_structp png_ptr, png_bytep 
data, png_size_t length)
 static void
 png_read_from_file (png_structp png_ptr, png_bytep data, png_size_t length)
 {
-  FILE *fp = fn_png_get_io_ptr (png_ptr);
+  FILE *fp = png_get_io_ptr (png_ptr);
 
   if (fread (data, 1, length, fp) < length)
-    fn_png_error (png_ptr, "Read error");
+    png_error (png_ptr, "Read error");
 }
 
 
@@ -5779,7 +5789,7 @@ png_load_body (struct frame *f, struct image *img, struct 
png_load_context *c)
 
       /* Check PNG signature.  */
       if (fread (sig, 1, sizeof sig, fp) != sizeof sig
-         || fn_png_sig_cmp (sig, 0, sizeof sig))
+         || png_sig_cmp (sig, 0, sizeof sig))
        {
          fclose (fp);
          image_error ("Not a PNG file: `%s'", file, Qnil);
@@ -5801,7 +5811,7 @@ png_load_body (struct frame *f, struct image *img, struct 
png_load_context *c)
 
       /* Check PNG signature.  */
       if (tbr.len < sizeof sig
-         || fn_png_sig_cmp (tbr.bytes, 0, sizeof sig))
+         || png_sig_cmp (tbr.bytes, 0, sizeof sig))
        {
          image_error ("Not a PNG image: `%s'", img->spec, Qnil);
          return 0;
@@ -5812,13 +5822,13 @@ png_load_body (struct frame *f, struct image *img, 
struct png_load_context *c)
     }
 
   /* Initialize read and info structs for PNG lib.  */
-  png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
+  png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
                                       NULL, my_png_error,
                                       my_png_warning);
   if (png_ptr)
     {
-      info_ptr = fn_png_create_info_struct (png_ptr);
-      end_info = fn_png_create_info_struct (png_ptr);
+      info_ptr = png_create_info_struct (png_ptr);
+      end_info = png_create_info_struct (png_ptr);
     }
 
   c->png_ptr = png_ptr;
@@ -5830,7 +5840,7 @@ png_load_body (struct frame *f, struct image *img, struct 
png_load_context *c)
 
   if (! (info_ptr && end_info))
     {
-      fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
+      png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
       png_ptr = 0;
     }
   if (! png_ptr)
@@ -5845,7 +5855,7 @@ png_load_body (struct frame *f, struct image *img, struct 
png_load_context *c)
     {
     error:
       if (c->png_ptr)
-       fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
+       png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
       xfree (c->pixels);
       xfree (c->rows);
       if (c->fp)
@@ -5858,14 +5868,14 @@ png_load_body (struct frame *f, struct image *img, 
struct png_load_context *c)
 
   /* Read image info.  */
   if (!NILP (specified_data))
-    fn_png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
+    png_set_read_fn (png_ptr, &tbr, png_read_from_memory);
   else
-    fn_png_set_read_fn (png_ptr, fp, png_read_from_file);
+    png_set_read_fn (png_ptr, fp, png_read_from_file);
 
-  fn_png_set_sig_bytes (png_ptr, sizeof sig);
-  fn_png_read_info (png_ptr, info_ptr);
-  fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
-                  &interlace_type, NULL, NULL);
+  png_set_sig_bytes (png_ptr, sizeof sig);
+  png_read_info (png_ptr, info_ptr);
+  png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
+               &interlace_type, NULL, NULL);
 
   if (! (width <= INT_MAX && height <= INT_MAX
         && check_image_size (f, width, height)))
@@ -5881,7 +5891,7 @@ png_load_body (struct frame *f, struct image *img, struct 
png_load_context *c)
 
   /* If image contains simply transparency data, we prefer to
      construct a clipping mask.  */
-  if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
+  if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
     transparent_p = 1;
   else
     transparent_p = 0;
@@ -5892,16 +5902,16 @@ png_load_body (struct frame *f, struct image *img, 
struct png_load_context *c)
 
   /* Strip more than 8 bits per channel.  */
   if (bit_depth == 16)
-    fn_png_set_strip_16 (png_ptr);
+    png_set_strip_16 (png_ptr);
 
   /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
      if available.  */
-  fn_png_set_expand (png_ptr);
+  png_set_expand (png_ptr);
 
   /* Convert grayscale images to RGB.  */
   if (color_type == PNG_COLOR_TYPE_GRAY
       || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
-    fn_png_set_gray_to_rgb (png_ptr);
+    png_set_gray_to_rgb (png_ptr);
 
   /* Handle alpha channel by combining the image with a background
      color.  Do this only if a real alpha channel is supplied.  For
@@ -5927,24 +5937,24 @@ png_load_body (struct frame *f, struct image *img, 
struct png_load_context *c)
          bg.green = color.green >> shift;
          bg.blue = color.blue >> shift;
 
-         fn_png_set_background (png_ptr, &bg,
-                                PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
+         png_set_background (png_ptr, &bg,
+                             PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
        }
     }
 
   /* Update info structure.  */
-  fn_png_read_update_info (png_ptr, info_ptr);
+  png_read_update_info (png_ptr, info_ptr);
 
   /* Get number of channels.  Valid values are 1 for grayscale images
      and images with a palette, 2 for grayscale images with transparency
      information (alpha channel), 3 for RGB images, and 4 for RGB
      images with alpha channel, i.e. RGBA.  If conversions above were
      sufficient we should only have 3 or 4 channels here.  */
-  channels = fn_png_get_channels (png_ptr, info_ptr);
+  channels = png_get_channels (png_ptr, info_ptr);
   eassert (channels == 3 || channels == 4);
 
   /* Number of bytes needed for one row of the image.  */
-  row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
+  row_bytes = png_get_rowbytes (png_ptr, info_ptr);
 
   /* Allocate memory for the image.  */
   if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *rows < height
@@ -5956,8 +5966,8 @@ png_load_body (struct frame *f, struct image *img, struct 
png_load_context *c)
     rows[i] = pixels + i * row_bytes;
 
   /* Read the entire image.  */
-  fn_png_read_image (png_ptr, rows);
-  fn_png_read_end (png_ptr, info_ptr);
+  png_read_image (png_ptr, rows);
+  png_read_end (png_ptr, info_ptr);
   if (fp)
     {
       fclose (fp);
@@ -6021,21 +6031,21 @@ png_load_body (struct frame *f, struct image *img, 
struct png_load_context *c)
        overrode it.  */
     {
       png_color_16 *bg;
-      if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
+      if (png_get_bKGD (png_ptr, info_ptr, &bg))
        {
          img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
          img->background_valid = 1;
        }
     }
 
-#ifdef COLOR_TABLE_SUPPORT
+# ifdef COLOR_TABLE_SUPPORT
   /* Remember colors allocated for this image.  */
   img->colors = colors_in_color_table (&img->ncolors);
   free_color_table ();
-#endif /* COLOR_TABLE_SUPPORT */
+# endif /* COLOR_TABLE_SUPPORT */
 
   /* Clean up.  */
-  fn_png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
+  png_destroy_read_struct (&c->png_ptr, &c->info_ptr, &c->end_info);
   xfree (rows);
   xfree (pixels);
 
@@ -6170,15 +6180,15 @@ jpeg_image_p (Lisp_Object object)
 
 /* Work around a warning about HAVE_STDLIB_H being redefined in
    jconfig.h.  */
-#ifdef HAVE_STDLIB_H
-#undef HAVE_STDLIB_H
-#endif /* HAVE_STLIB_H */
+# ifdef HAVE_STDLIB_H
+#  undef HAVE_STDLIB_H
+# endif
 
-#if defined (HAVE_NTGUI) && !defined (__WIN32__)
+# if defined (HAVE_NTGUI) && !defined (__WIN32__)
 /* In older releases of the jpeg library, jpeglib.h will define boolean
    differently depending on __WIN32__, so make sure it is defined.  */
-#define __WIN32__ 1
-#endif
+#  define __WIN32__ 1
+# endif
 
 /* rpcndr.h (via windows.h) and jpeglib.h both define boolean types.
    Some versions of jpeglib try to detect whether rpcndr.h is loaded,
@@ -6194,23 +6204,25 @@ jpeg_image_p (Lisp_Object object)
    different name.  This name, jpeg_boolean, remains in effect through
    the rest of image.c.
 */
-#if defined CYGWIN && defined HAVE_NTGUI
-#define boolean jpeg_boolean
-#endif
-#include <jpeglib.h>
-#include <jerror.h>
+# if defined CYGWIN && defined HAVE_NTGUI
+#  define boolean jpeg_boolean
+# endif
+# include <jpeglib.h>
+# include <jerror.h>
 
-#ifdef WINDOWSNT
+# ifdef WINDOWSNT
 
 /* JPEG library details.  */
-DEF_IMGLIB_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
-DEF_IMGLIB_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
-DEF_IMGLIB_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
-DEF_IMGLIB_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
-DEF_IMGLIB_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
-DEF_IMGLIB_FN (JDIMENSION, jpeg_read_scanlines, (j_decompress_ptr, JSAMPARRAY, 
JDIMENSION));
-DEF_IMGLIB_FN (struct jpeg_error_mgr *, jpeg_std_error, (struct jpeg_error_mgr 
*));
-DEF_IMGLIB_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
+DEF_DLL_FN (void, jpeg_CreateDecompress, (j_decompress_ptr, int, size_t));
+DEF_DLL_FN (boolean, jpeg_start_decompress, (j_decompress_ptr));
+DEF_DLL_FN (boolean, jpeg_finish_decompress, (j_decompress_ptr));
+DEF_DLL_FN (void, jpeg_destroy_decompress, (j_decompress_ptr));
+DEF_DLL_FN (int, jpeg_read_header, (j_decompress_ptr, boolean));
+DEF_DLL_FN (JDIMENSION, jpeg_read_scanlines,
+           (j_decompress_ptr, JSAMPARRAY, JDIMENSION));
+DEF_DLL_FN (struct jpeg_error_mgr *, jpeg_std_error,
+           (struct jpeg_error_mgr *));
+DEF_DLL_FN (boolean, jpeg_resync_to_restart, (j_decompress_ptr, int));
 
 static bool
 init_jpeg_functions (void)
@@ -6220,37 +6232,46 @@ init_jpeg_functions (void)
   if (!(library = w32_delayed_load (Qjpeg)))
     return 0;
 
-  LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
-  LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
-  LOAD_IMGLIB_FN (library, jpeg_start_decompress);
-  LOAD_IMGLIB_FN (library, jpeg_read_header);
-  LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
-  LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
-  LOAD_IMGLIB_FN (library, jpeg_std_error);
-  LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
+  LOAD_DLL_FN (library, jpeg_finish_decompress);
+  LOAD_DLL_FN (library, jpeg_read_scanlines);
+  LOAD_DLL_FN (library, jpeg_start_decompress);
+  LOAD_DLL_FN (library, jpeg_read_header);
+  LOAD_DLL_FN (library, jpeg_CreateDecompress);
+  LOAD_DLL_FN (library, jpeg_destroy_decompress);
+  LOAD_DLL_FN (library, jpeg_std_error);
+  LOAD_DLL_FN (library, jpeg_resync_to_restart);
   return 1;
 }
 
+#  undef jpeg_CreateDecompress
+#  undef jpeg_destroy_decompress
+#  undef jpeg_finish_decompress
+#  undef jpeg_read_header
+#  undef jpeg_read_scanlines
+#  undef jpeg_resync_to_restart
+#  undef jpeg_start_decompress
+#  undef jpeg_std_error
+
+#  define jpeg_CreateDecompress fn_jpeg_CreateDecompress
+#  define jpeg_destroy_decompress fn_jpeg_destroy_decompress
+#  define jpeg_finish_decompress fn_jpeg_finish_decompress
+#  define jpeg_read_header fn_jpeg_read_header
+#  define jpeg_read_scanlines fn_jpeg_read_scanlines
+#  define jpeg_resync_to_restart fn_jpeg_resync_to_restart
+#  define jpeg_start_decompress fn_jpeg_start_decompress
+#  define jpeg_std_error fn_jpeg_std_error
+
 /* Wrapper since we can't directly assign the function pointer
    to another function pointer that was declared more completely easily.  */
 static boolean
 jpeg_resync_to_restart_wrapper (j_decompress_ptr cinfo, int desired)
 {
-  return fn_jpeg_resync_to_restart (cinfo, desired);
+  return jpeg_resync_to_restart (cinfo, desired);
 }
+#  undef jpeg_resync_to_restart
+#  define jpeg_resync_to_restart jpeg_resync_to_restart_wrapper
 
-#else
-
-#define fn_jpeg_CreateDecompress(a,b,c)        jpeg_create_decompress (a)
-#define fn_jpeg_start_decompress       jpeg_start_decompress
-#define fn_jpeg_finish_decompress      jpeg_finish_decompress
-#define fn_jpeg_destroy_decompress     jpeg_destroy_decompress
-#define fn_jpeg_read_header            jpeg_read_header
-#define fn_jpeg_read_scanlines         jpeg_read_scanlines
-#define fn_jpeg_std_error              jpeg_std_error
-#define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
-
-#endif /* WINDOWSNT */
+# endif /* WINDOWSNT */
 
 struct my_jpeg_error_mgr
 {
@@ -6358,7 +6379,7 @@ jpeg_memory_src (j_decompress_ptr cinfo, JOCTET *data, 
ptrdiff_t len)
   src->init_source = our_common_init_source;
   src->fill_input_buffer = our_memory_fill_input_buffer;
   src->skip_input_data = our_memory_skip_input_data;
-  src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default 
method.  */
+  src->resync_to_restart = jpeg_resync_to_restart; /* Use default method.  */
   src->term_source = our_common_term_source;
   src->bytes_in_buffer = len;
   src->next_input_byte = data;
@@ -6464,7 +6485,7 @@ jpeg_file_src (j_decompress_ptr cinfo, FILE *fp)
   src->mgr.init_source = our_common_init_source;
   src->mgr.fill_input_buffer = our_stdio_fill_input_buffer;
   src->mgr.skip_input_data = our_stdio_skip_input_data;
-  src->mgr.resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default 
method.  */
+  src->mgr.resync_to_restart = jpeg_resync_to_restart; /* Use default.  */
   src->mgr.term_source = our_common_term_source;
   src->mgr.bytes_in_buffer = 0;
   src->mgr.next_input_byte = NULL;
@@ -6515,7 +6536,7 @@ jpeg_load_body (struct frame *f, struct image *img,
 
   /* Customize libjpeg's error handling to call my_error_exit when an
      error is detected.  This function will perform a longjmp.  */
-  mgr->cinfo.err = fn_jpeg_std_error (&mgr->pub);
+  mgr->cinfo.err = jpeg_std_error (&mgr->pub);
   mgr->pub.error_exit = my_error_exit;
   if (sys_setjmp (mgr->setjmp_buffer))
     {
@@ -6541,7 +6562,7 @@ jpeg_load_body (struct frame *f, struct image *img,
       /* Close the input file and destroy the JPEG object.  */
       if (fp)
        fclose (fp);
-      fn_jpeg_destroy_decompress (&mgr->cinfo);
+      jpeg_destroy_decompress (&mgr->cinfo);
 
       /* If we already have an XImage, free that.  */
       x_destroy_x_image (ximg);
@@ -6553,7 +6574,7 @@ jpeg_load_body (struct frame *f, struct image *img,
 
   /* Create the JPEG decompression object.  Let it read from fp.
         Read the JPEG image header.  */
-  fn_jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof 
*&mgr->cinfo);
+  jpeg_CreateDecompress (&mgr->cinfo, JPEG_LIB_VERSION, sizeof *&mgr->cinfo);
 
   if (NILP (specified_data))
     jpeg_file_src (&mgr->cinfo, fp);
@@ -6561,12 +6582,12 @@ jpeg_load_body (struct frame *f, struct image *img,
     jpeg_memory_src (&mgr->cinfo, SDATA (specified_data),
                     SBYTES (specified_data));
 
-  fn_jpeg_read_header (&mgr->cinfo, 1);
+  jpeg_read_header (&mgr->cinfo, 1);
 
   /* Customize decompression so that color quantization will be used.
         Start decompression.  */
   mgr->cinfo.quantize_colors = 1;
-  fn_jpeg_start_decompress (&mgr->cinfo);
+  jpeg_start_decompress (&mgr->cinfo);
   width = img->width = mgr->cinfo.output_width;
   height = img->height = mgr->cinfo.output_height;
 
@@ -6629,14 +6650,14 @@ jpeg_load_body (struct frame *f, struct image *img,
                                         JPOOL_IMAGE, row_stride, 1);
   for (y = 0; y < height; ++y)
     {
-      fn_jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
+      jpeg_read_scanlines (&mgr->cinfo, buffer, 1);
       for (x = 0; x < mgr->cinfo.output_width; ++x)
        XPutPixel (ximg, x, y, colors[buffer[0][x]]);
     }
 
   /* Clean up.  */
-  fn_jpeg_finish_decompress (&mgr->cinfo);
-  fn_jpeg_destroy_decompress (&mgr->cinfo);
+  jpeg_finish_decompress (&mgr->cinfo);
+  jpeg_destroy_decompress (&mgr->cinfo);
   if (fp)
     fclose (fp);
 
@@ -6760,22 +6781,22 @@ tiff_image_p (Lisp_Object object)
 
 #ifdef HAVE_TIFF
 
-#include <tiffio.h>
+# include <tiffio.h>
 
-#ifdef WINDOWSNT
+# ifdef WINDOWSNT
 
 /* TIFF library details.  */
-DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
-DEF_IMGLIB_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
-DEF_IMGLIB_FN (TIFF *, TIFFOpen, (const char *, const char *));
-DEF_IMGLIB_FN (TIFF *, TIFFClientOpen, (const char *, const char *, thandle_t,
-                               TIFFReadWriteProc, TIFFReadWriteProc,
-                               TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
-                               TIFFMapFileProc, TIFFUnmapFileProc));
-DEF_IMGLIB_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
-DEF_IMGLIB_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, 
int));
-DEF_IMGLIB_FN (void, TIFFClose, (TIFF *));
-DEF_IMGLIB_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
+DEF_DLL_FN (TIFFErrorHandler, TIFFSetErrorHandler, (TIFFErrorHandler));
+DEF_DLL_FN (TIFFErrorHandler, TIFFSetWarningHandler, (TIFFErrorHandler));
+DEF_DLL_FN (TIFF *, TIFFOpen, (const char *, const char *));
+DEF_DLL_FN (TIFF *, TIFFClientOpen,
+           (const char *, const char *, thandle_t, TIFFReadWriteProc,
+            TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc,
+            TIFFMapFileProc, TIFFUnmapFileProc));
+DEF_DLL_FN (int, TIFFGetField, (TIFF *, ttag_t, ...));
+DEF_DLL_FN (int, TIFFReadRGBAImage, (TIFF *, uint32, uint32, uint32 *, int));
+DEF_DLL_FN (void, TIFFClose, (TIFF *));
+DEF_DLL_FN (int, TIFFSetDirectory, (TIFF *, tdir_t));
 
 static bool
 init_tiff_functions (void)
@@ -6785,28 +6806,36 @@ init_tiff_functions (void)
   if (!(library = w32_delayed_load (Qtiff)))
     return 0;
 
-  LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
-  LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
-  LOAD_IMGLIB_FN (library, TIFFOpen);
-  LOAD_IMGLIB_FN (library, TIFFClientOpen);
-  LOAD_IMGLIB_FN (library, TIFFGetField);
-  LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
-  LOAD_IMGLIB_FN (library, TIFFClose);
-  LOAD_IMGLIB_FN (library, TIFFSetDirectory);
+  LOAD_DLL_FN (library, TIFFSetErrorHandler);
+  LOAD_DLL_FN (library, TIFFSetWarningHandler);
+  LOAD_DLL_FN (library, TIFFOpen);
+  LOAD_DLL_FN (library, TIFFClientOpen);
+  LOAD_DLL_FN (library, TIFFGetField);
+  LOAD_DLL_FN (library, TIFFReadRGBAImage);
+  LOAD_DLL_FN (library, TIFFClose);
+  LOAD_DLL_FN (library, TIFFSetDirectory);
   return 1;
 }
 
-#else
+#  undef TIFFClientOpen
+#  undef TIFFClose
+#  undef TIFFGetField
+#  undef TIFFOpen
+#  undef TIFFReadRGBAImage
+#  undef TIFFSetDirectory
+#  undef TIFFSetErrorHandler
+#  undef TIFFSetWarningHandler
 
-#define fn_TIFFSetErrorHandler         TIFFSetErrorHandler
-#define fn_TIFFSetWarningHandler       TIFFSetWarningHandler
-#define fn_TIFFOpen                    TIFFOpen
-#define fn_TIFFClientOpen              TIFFClientOpen
-#define fn_TIFFGetField                        TIFFGetField
-#define fn_TIFFReadRGBAImage           TIFFReadRGBAImage
-#define fn_TIFFClose                   TIFFClose
-#define fn_TIFFSetDirectory            TIFFSetDirectory
-#endif /* WINDOWSNT */
+#  define TIFFClientOpen fn_TIFFClientOpen
+#  define TIFFClose fn_TIFFClose
+#  define TIFFGetField fn_TIFFGetField
+#  define TIFFOpen fn_TIFFOpen
+#  define TIFFReadRGBAImage fn_TIFFReadRGBAImage
+#  define TIFFSetDirectory fn_TIFFSetDirectory
+#  define TIFFSetErrorHandler fn_TIFFSetErrorHandler
+#  define TIFFSetWarningHandler fn_TIFFSetWarningHandler
+
+# endif /* WINDOWSNT */
 
 
 /* Reading from a memory buffer for TIFF images Based on the PNG
@@ -6904,11 +6933,11 @@ tiff_size_of_memory (thandle_t data)
    compiler error compiling tiff_handler, see Bugzilla bug #17406
    (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17406).  Declaring
    this function as external works around that problem.  */
-#if defined (__MINGW32__) && __GNUC__ == 3
-# define MINGW_STATIC
-#else
-# define MINGW_STATIC static
-#endif
+# if defined (__MINGW32__) && __GNUC__ == 3
+#  define MINGW_STATIC
+# else
+#  define MINGW_STATIC static
+# endif
 
 MINGW_STATIC void
 tiff_handler (const char *, const char *, const char *, va_list)
@@ -6927,7 +6956,7 @@ tiff_handler (const char *log_format, const char *title,
   add_to_log (log_format, build_string (title),
              make_string (buf, max (0, min (len, sizeof buf - 1))));
 }
-#undef MINGW_STATIC
+# undef MINGW_STATIC
 
 static void tiff_error_handler (const char *, const char *, va_list)
   ATTRIBUTE_FORMAT_PRINTF (2, 0);
@@ -6966,8 +6995,8 @@ tiff_load (struct frame *f, struct image *img)
   specified_file = image_spec_value (img->spec, QCfile, NULL);
   specified_data = image_spec_value (img->spec, QCdata, NULL);
 
-  fn_TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
-  fn_TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
+  TIFFSetErrorHandler ((TIFFErrorHandler) tiff_error_handler);
+  TIFFSetWarningHandler ((TIFFErrorHandler) tiff_warning_handler);
 
   if (NILP (specified_data))
     {
@@ -6978,12 +7007,12 @@ tiff_load (struct frame *f, struct image *img)
          image_error ("Cannot find image file `%s'", specified_file, Qnil);
          return 0;
        }
-#ifdef WINDOWSNT
+# ifdef WINDOWSNT
       file = ansi_encode_filename (file);
-#endif
+# endif
 
       /* Try to open the image file.  */
-      tiff = fn_TIFFOpen (SSDATA (file), "r");
+      tiff = TIFFOpen (SSDATA (file), "r");
       if (tiff == NULL)
        {
          image_error ("Cannot open `%s'", file, Qnil);
@@ -7003,14 +7032,14 @@ tiff_load (struct frame *f, struct image *img)
       memsrc.len = SBYTES (specified_data);
       memsrc.index = 0;
 
-      tiff = fn_TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
-                               tiff_read_from_memory,
-                               tiff_write_from_memory,
-                               tiff_seek_in_memory,
-                               tiff_close_memory,
-                               tiff_size_of_memory,
-                               tiff_mmap_memory,
-                               tiff_unmap_memory);
+      tiff = TIFFClientOpen ("memory_source", "r", (thandle_t)&memsrc,
+                            tiff_read_from_memory,
+                            tiff_write_from_memory,
+                            tiff_seek_in_memory,
+                            tiff_close_memory,
+                            tiff_size_of_memory,
+                            tiff_mmap_memory,
+                            tiff_unmap_memory);
 
       if (!tiff)
        {
@@ -7024,24 +7053,24 @@ tiff_load (struct frame *f, struct image *img)
     {
       EMACS_INT ino = XFASTINT (image);
       if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
-            && fn_TIFFSetDirectory (tiff, ino)))
+            && TIFFSetDirectory (tiff, ino)))
        {
          image_error ("Invalid image number `%s' in image `%s'",
                       image, img->spec);
-         fn_TIFFClose (tiff);
+         TIFFClose (tiff);
          return 0;
        }
     }
 
   /* Get width and height of the image, and allocate a raster buffer
      of width x height 32-bit values.  */
-  fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
-  fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
+  TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
+  TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
 
   if (!check_image_size (f, width, height))
     {
       image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
-      fn_TIFFClose (tiff);
+      TIFFClose (tiff);
       return 0;
     }
 
@@ -7050,16 +7079,16 @@ tiff_load (struct frame *f, struct image *img)
         && image_create_x_image_and_pixmap (f, img, width, height, 0,
                                             &ximg, 0)))
     {
-      fn_TIFFClose (tiff);
+      TIFFClose (tiff);
       return 0;
     }
 
   buf = xmalloc (sizeof *buf * width * height);
 
-  rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
+  rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
 
   /* Count the number of images in the file.  */
-  for (count = 1; fn_TIFFSetDirectory (tiff, count); count++)
+  for (count = 1; TIFFSetDirectory (tiff, count); count++)
     continue;
 
   if (count > 1)
@@ -7067,7 +7096,7 @@ tiff_load (struct frame *f, struct image *img)
                            Fcons (make_number (count),
                                   img->lisp_data));
 
-  fn_TIFFClose (tiff);
+  TIFFClose (tiff);
   if (!rc)
     {
       image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
@@ -7093,11 +7122,11 @@ tiff_load (struct frame *f, struct image *img)
        }
     }
 
-#ifdef COLOR_TABLE_SUPPORT
+# ifdef COLOR_TABLE_SUPPORT
   /* Remember the colors allocated for the image.  Free the color table.  */
   img->colors = colors_in_color_table (&img->ncolors);
   free_color_table ();
-#endif /* COLOR_TABLE_SUPPORT */
+# endif /* COLOR_TABLE_SUPPORT */
 
   img->width = width;
   img->height = height;
@@ -7114,9 +7143,8 @@ tiff_load (struct frame *f, struct image *img)
   return 1;
 }
 
-#else /* HAVE_TIFF */
+#elif defined HAVE_NS
 
-#ifdef HAVE_NS
 static bool
 tiff_load (struct frame *f, struct image *img)
 {
@@ -7124,9 +7152,8 @@ tiff_load (struct frame *f, struct image *img)
                         image_spec_value (img->spec, QCfile, NULL),
                         image_spec_value (img->spec, QCdata, NULL));
 }
-#endif  /* HAVE_NS */
 
-#endif /* !HAVE_TIFF */
+#endif
 
 
 
@@ -7226,54 +7253,54 @@ gif_image_p (Lisp_Object object)
 
 #ifdef HAVE_GIF
 
-#if defined (HAVE_NTGUI)
+# ifdef HAVE_NTGUI
 
 /* winuser.h might define DrawText to DrawTextA or DrawTextW.
    Undefine before redefining to avoid a preprocessor warning.  */
-#ifdef DrawText
-#undef DrawText
-#endif
+#  ifdef DrawText
+#   undef DrawText
+#  endif
 /* avoid conflict with QuickdrawText.h */
-#define DrawText gif_DrawText
-#include <gif_lib.h>
-#undef DrawText
+#  define DrawText gif_DrawText
+#  include <gif_lib.h>
+#  undef DrawText
 
 /* Giflib before 5.0 didn't define these macros (used only if HAVE_NTGUI).  */
-#ifndef GIFLIB_MINOR
-#define GIFLIB_MINOR 0
-#endif
-#ifndef GIFLIB_RELEASE
-#define GIFLIB_RELEASE 0
-#endif
+#  ifndef GIFLIB_MINOR
+#   define GIFLIB_MINOR 0
+#  endif
+#  ifndef GIFLIB_RELEASE
+#   define GIFLIB_RELEASE 0
+#  endif
 
-#else /* HAVE_NTGUI */
+# else /* HAVE_NTGUI */
 
-#include <gif_lib.h>
+#  include <gif_lib.h>
 
-#endif /* HAVE_NTGUI */
+# endif /* HAVE_NTGUI */
 
 /* Giflib before 5.0 didn't define these macros.  */
-#ifndef GIFLIB_MAJOR
-#define GIFLIB_MAJOR 4
-#endif
+# ifndef GIFLIB_MAJOR
+#  define GIFLIB_MAJOR 4
+# endif
 
-#ifdef WINDOWSNT
+# ifdef WINDOWSNT
 
 /* GIF library details.  */
-#if 5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR)
-DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *, int *));
-#else
-DEF_IMGLIB_FN (int, DGifCloseFile, (GifFileType *));
-#endif
-DEF_IMGLIB_FN (int, DGifSlurp, (GifFileType *));
-#if GIFLIB_MAJOR < 5
-DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc));
-DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *));
-#else
-DEF_IMGLIB_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
-DEF_IMGLIB_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
-DEF_IMGLIB_FN (char *, GifErrorString, (int));
-#endif
+#  if 5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR)
+DEF_DLL_FN (int, DGifCloseFile, (GifFileType *, int *));
+#   else
+DEF_DLL_FN (int, DGifCloseFile, (GifFileType *));
+#  endif
+DEF_DLL_FN (int, DGifSlurp, (GifFileType *));
+#  if GIFLIB_MAJOR < 5
+DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc));
+DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *));
+#  else
+DEF_DLL_FN (GifFileType *, DGifOpen, (void *, InputFunc, int *));
+DEF_DLL_FN (GifFileType *, DGifOpenFileName, (const char *, int *));
+DEF_DLL_FN (char *, GifErrorString, (int));
+#  endif
 
 static bool
 init_gif_functions (void)
@@ -7283,27 +7310,29 @@ init_gif_functions (void)
   if (!(library = w32_delayed_load (Qgif)))
     return 0;
 
-  LOAD_IMGLIB_FN (library, DGifCloseFile);
-  LOAD_IMGLIB_FN (library, DGifSlurp);
-  LOAD_IMGLIB_FN (library, DGifOpen);
-  LOAD_IMGLIB_FN (library, DGifOpenFileName);
-#if GIFLIB_MAJOR >= 5
-  LOAD_IMGLIB_FN (library, GifErrorString);
-#endif
+  LOAD_DLL_FN (library, DGifCloseFile);
+  LOAD_DLL_FN (library, DGifSlurp);
+  LOAD_DLL_FN (library, DGifOpen);
+  LOAD_DLL_FN (library, DGifOpenFileName);
+#  if GIFLIB_MAJOR >= 5
+  LOAD_DLL_FN (library, GifErrorString);
+#  endif
   return 1;
 }
 
-#else
+#  undef DGifCloseFile
+#  undef DGifOpen
+#  undef DGifOpenFileName
+#  undef DGifSlurp
+#  undef GifErrorString
 
-#define fn_DGifCloseFile       DGifCloseFile
-#define fn_DGifSlurp           DGifSlurp
-#define fn_DGifOpen            DGifOpen
-#define fn_DGifOpenFileName    DGifOpenFileName
-#if 5 <= GIFLIB_MAJOR
-# define fn_GifErrorString     GifErrorString
-#endif
+#  define DGifCloseFile fn_DGifCloseFile
+#  define DGifOpen fn_DGifOpen
+#  define DGifOpenFileName fn_DGifOpenFileName
+#  define DGifSlurp fn_DGifSlurp
+#  define GifErrorString fn_GifErrorString
 
-#endif /* WINDOWSNT */
+# endif /* WINDOWSNT */
 
 /* Reading a GIF image from memory
    Based on the PNG memory stuff to a certain extent. */
@@ -7340,9 +7369,9 @@ gif_close (GifFileType *gif, int *err)
   int retval;
 
 #if 5 < GIFLIB_MAJOR + (1 <= GIFLIB_MINOR)
-  retval = fn_DGifCloseFile (gif, err);
+  retval = DGifCloseFile (gif, err);
 #else
-  retval = fn_DGifCloseFile (gif);
+  retval = DGifCloseFile (gif);
 #if GIFLIB_MAJOR >= 5
   if (err)
     *err = gif->Error;
@@ -7390,18 +7419,18 @@ gif_load (struct frame *f, struct image *img)
 
       /* Open the GIF file.  */
 #if GIFLIB_MAJOR < 5
-      gif = fn_DGifOpenFileName (SSDATA (file));
+      gif = DGifOpenFileName (SSDATA (file));
       if (gif == NULL)
        {
          image_error ("Cannot open `%s'", file, Qnil);
          return 0;
        }
 #else
-      gif = fn_DGifOpenFileName (SSDATA (file), &gif_err);
+      gif = DGifOpenFileName (SSDATA (file), &gif_err);
       if (gif == NULL)
        {
          image_error ("Cannot open `%s': %s",
-                      file, build_string (fn_GifErrorString (gif_err)));
+                      file, build_string (GifErrorString (gif_err)));
          return 0;
        }
 #endif
@@ -7421,18 +7450,18 @@ gif_load (struct frame *f, struct image *img)
       memsrc.index = 0;
 
 #if GIFLIB_MAJOR < 5
-      gif = fn_DGifOpen (&memsrc, gif_read_from_memory);
+      gif = DGifOpen (&memsrc, gif_read_from_memory);
       if (!gif)
        {
          image_error ("Cannot open memory source `%s'", img->spec, Qnil);
          return 0;
        }
 #else
-      gif = fn_DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
+      gif = DGifOpen (&memsrc, gif_read_from_memory, &gif_err);
       if (!gif)
        {
          image_error ("Cannot open memory source `%s': %s",
-                      img->spec, build_string (fn_GifErrorString (gif_err)));
+                      img->spec, build_string (GifErrorString (gif_err)));
          return 0;
        }
 #endif
@@ -7447,7 +7476,7 @@ gif_load (struct frame *f, struct image *img)
     }
 
   /* Read entire contents.  */
-  rc = fn_DGifSlurp (gif);
+  rc = DGifSlurp (gif);
   if (rc == GIF_ERROR || gif->ImageCount <= 0)
     {
       image_error ("Error reading `%s'", img->spec, Qnil);
@@ -7681,7 +7710,7 @@ gif_load (struct frame *f, struct image *img)
   if (gif_close (gif, &gif_err) == GIF_ERROR)
     {
 #if 5 <= GIFLIB_MAJOR
-      char *error_text = fn_GifErrorString (gif_err);
+      char *error_text = GifErrorString (gif_err);
 
       if (error_text)
        image_error ("Error closing `%s': %s",
@@ -8593,7 +8622,7 @@ and `imagemagick-types-inhibit'.  */)
                                 SVG
  ***********************************************************************/
 
-#if defined (HAVE_RSVG)
+#ifdef HAVE_RSVG
 
 /* Function prototypes.  */
 
@@ -8641,11 +8670,11 @@ static const struct image_keyword svg_format[SVG_LAST] =
   {":background",      IMAGE_STRING_OR_NIL_VALUE,              0}
 };
 
-#if defined HAVE_NTGUI && defined WINDOWSNT
+# if defined HAVE_NTGUI && defined WINDOWSNT
 static bool init_svg_functions (void);
-#else
+# else
 #define init_svg_functions NULL
-#endif
+# endif
 
 /* Structure describing the image type `svg'.  Its the same type of
    structure defined for all image formats, handled by emacs image
@@ -8679,32 +8708,34 @@ svg_image_p (Lisp_Object object)
   return fmt[SVG_FILE].count + fmt[SVG_DATA].count == 1;
 }
 
-#include <librsvg/rsvg.h>
+# include <librsvg/rsvg.h>
 
-#ifdef WINDOWSNT
+# ifdef WINDOWSNT
 
 /* SVG library functions.  */
-DEF_IMGLIB_FN (RsvgHandle *, rsvg_handle_new, (void));
-DEF_IMGLIB_FN (void, rsvg_handle_get_dimensions, (RsvgHandle *, 
RsvgDimensionData *));
-DEF_IMGLIB_FN (gboolean, rsvg_handle_write, (RsvgHandle *, const guchar *, 
gsize, GError **));
-DEF_IMGLIB_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
-DEF_IMGLIB_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
-DEF_IMGLIB_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
-
-DEF_IMGLIB_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
-DEF_IMGLIB_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
-DEF_IMGLIB_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
-DEF_IMGLIB_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
-DEF_IMGLIB_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
-DEF_IMGLIB_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
-DEF_IMGLIB_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
-DEF_IMGLIB_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
-
-#if ! GLIB_CHECK_VERSION (2, 36, 0)
-DEF_IMGLIB_FN (void, g_type_init, (void));
-#endif
-DEF_IMGLIB_FN (void, g_object_unref, (gpointer));
-DEF_IMGLIB_FN (void, g_error_free, (GError *));
+DEF_DLL_FN (RsvgHandle *, rsvg_handle_new, (void));
+DEF_DLL_FN (void, rsvg_handle_get_dimensions,
+           (RsvgHandle *, RsvgDimensionData *));
+DEF_DLL_FN (gboolean, rsvg_handle_write,
+           (RsvgHandle *, const guchar *, gsize, GError **));
+DEF_DLL_FN (gboolean, rsvg_handle_close, (RsvgHandle *, GError **));
+DEF_DLL_FN (GdkPixbuf *, rsvg_handle_get_pixbuf, (RsvgHandle *));
+DEF_DLL_FN (void, rsvg_handle_set_base_uri, (RsvgHandle *, const char *));
+
+DEF_DLL_FN (int, gdk_pixbuf_get_width, (const GdkPixbuf *));
+DEF_DLL_FN (int, gdk_pixbuf_get_height, (const GdkPixbuf *));
+DEF_DLL_FN (guchar *, gdk_pixbuf_get_pixels, (const GdkPixbuf *));
+DEF_DLL_FN (int, gdk_pixbuf_get_rowstride, (const GdkPixbuf *));
+DEF_DLL_FN (GdkColorspace, gdk_pixbuf_get_colorspace, (const GdkPixbuf *));
+DEF_DLL_FN (int, gdk_pixbuf_get_n_channels, (const GdkPixbuf *));
+DEF_DLL_FN (gboolean, gdk_pixbuf_get_has_alpha, (const GdkPixbuf *));
+DEF_DLL_FN (int, gdk_pixbuf_get_bits_per_sample, (const GdkPixbuf *));
+
+#  if ! GLIB_CHECK_VERSION (2, 36, 0)
+DEF_DLL_FN (void, g_type_init, (void));
+#  endif
+DEF_DLL_FN (void, g_object_unref, (gpointer));
+DEF_DLL_FN (void, g_error_free, (GError *));
 
 Lisp_Object Qgdk_pixbuf, Qglib, Qgobject;
 
@@ -8724,56 +8755,71 @@ init_svg_functions (void)
       return 0;
     }
 
-  LOAD_IMGLIB_FN (library, rsvg_handle_new);
-  LOAD_IMGLIB_FN (library, rsvg_handle_get_dimensions);
-  LOAD_IMGLIB_FN (library, rsvg_handle_write);
-  LOAD_IMGLIB_FN (library, rsvg_handle_close);
-  LOAD_IMGLIB_FN (library, rsvg_handle_get_pixbuf);
-  LOAD_IMGLIB_FN (library, rsvg_handle_set_base_uri);
-
-  LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_width);
-  LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_height);
-  LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_pixels);
-  LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_rowstride);
-  LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_colorspace);
-  LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_n_channels);
-  LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_has_alpha);
-  LOAD_IMGLIB_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
-
-#if ! GLIB_CHECK_VERSION (2, 36, 0)
-  LOAD_IMGLIB_FN (gobject, g_type_init);
-#endif
-  LOAD_IMGLIB_FN (gobject, g_object_unref);
-  LOAD_IMGLIB_FN (glib, g_error_free);
+  LOAD_DLL_FN (library, rsvg_handle_new);
+  LOAD_DLL_FN (library, rsvg_handle_get_dimensions);
+  LOAD_DLL_FN (library, rsvg_handle_write);
+  LOAD_DLL_FN (library, rsvg_handle_close);
+  LOAD_DLL_FN (library, rsvg_handle_get_pixbuf);
+  LOAD_DLL_FN (library, rsvg_handle_set_base_uri);
+
+  LOAD_DLL_FN (gdklib, gdk_pixbuf_get_width);
+  LOAD_DLL_FN (gdklib, gdk_pixbuf_get_height);
+  LOAD_DLL_FN (gdklib, gdk_pixbuf_get_pixels);
+  LOAD_DLL_FN (gdklib, gdk_pixbuf_get_rowstride);
+  LOAD_DLL_FN (gdklib, gdk_pixbuf_get_colorspace);
+  LOAD_DLL_FN (gdklib, gdk_pixbuf_get_n_channels);
+  LOAD_DLL_FN (gdklib, gdk_pixbuf_get_has_alpha);
+  LOAD_DLL_FN (gdklib, gdk_pixbuf_get_bits_per_sample);
+
+#  if ! GLIB_CHECK_VERSION (2, 36, 0)
+  LOAD_DLL_FN (gobject, g_type_init);
+#  endif
+  LOAD_DLL_FN (gobject, g_object_unref);
+  LOAD_DLL_FN (glib, g_error_free);
 
   return 1;
 }
 
-#else
 /* The following aliases for library functions allow dynamic loading
    to be used on some platforms.  */
-#define fn_rsvg_handle_new             rsvg_handle_new
-#define fn_rsvg_handle_get_dimensions   rsvg_handle_get_dimensions
-#define fn_rsvg_handle_write           rsvg_handle_write
-#define fn_rsvg_handle_close           rsvg_handle_close
-#define fn_rsvg_handle_get_pixbuf      rsvg_handle_get_pixbuf
-#define fn_rsvg_handle_set_base_uri    rsvg_handle_set_base_uri
-
-#define fn_gdk_pixbuf_get_width                  gdk_pixbuf_get_width
-#define fn_gdk_pixbuf_get_height         gdk_pixbuf_get_height
-#define fn_gdk_pixbuf_get_pixels         gdk_pixbuf_get_pixels
-#define fn_gdk_pixbuf_get_rowstride      gdk_pixbuf_get_rowstride
-#define fn_gdk_pixbuf_get_colorspace     gdk_pixbuf_get_colorspace
-#define fn_gdk_pixbuf_get_n_channels     gdk_pixbuf_get_n_channels
-#define fn_gdk_pixbuf_get_has_alpha      gdk_pixbuf_get_has_alpha
-#define fn_gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_bits_per_sample
 
-#if ! GLIB_CHECK_VERSION (2, 36, 0)
-#define fn_g_type_init                    g_type_init
-#endif
-#define fn_g_object_unref                 g_object_unref
-#define fn_g_error_free                   g_error_free
-#endif /* !WINDOWSNT  */
+#  undef gdk_pixbuf_get_bits_per_sample
+#  undef gdk_pixbuf_get_colorspace
+#  undef gdk_pixbuf_get_has_alpha
+#  undef gdk_pixbuf_get_height
+#  undef gdk_pixbuf_get_n_channels
+#  undef gdk_pixbuf_get_pixels
+#  undef gdk_pixbuf_get_rowstride
+#  undef gdk_pixbuf_get_width
+#  undef g_error_free
+#  undef g_object_unref
+#  undef g_type_init
+#  undef rsvg_handle_close
+#  undef rsvg_handle_get_dimensions
+#  undef rsvg_handle_get_pixbuf
+#  undef rsvg_handle_new
+#  undef rsvg_handle_set_base_uri
+#  undef rsvg_handle_write
+
+#  define gdk_pixbuf_get_bits_per_sample fn_gdk_pixbuf_get_bits_per_sample
+#  define gdk_pixbuf_get_colorspace fn_gdk_pixbuf_get_colorspace
+#  define gdk_pixbuf_get_has_alpha fn_gdk_pixbuf_get_has_alpha
+#  define gdk_pixbuf_get_height fn_gdk_pixbuf_get_height
+#  define gdk_pixbuf_get_n_channels fn_gdk_pixbuf_get_n_channels
+#  define gdk_pixbuf_get_pixels fn_gdk_pixbuf_get_pixels
+#  define gdk_pixbuf_get_rowstride fn_gdk_pixbuf_get_rowstride
+#  define gdk_pixbuf_get_width fn_gdk_pixbuf_get_width
+#  define g_error_free fn_g_error_free
+#  define g_object_unref fn_g_object_unref
+#  define g_type_init fn_g_type_init
+#  define rsvg_handle_close fn_rsvg_handle_close
+#  define rsvg_handle_get_dimensions fn_rsvg_handle_get_dimensions
+#  define rsvg_handle_get_pixbuf fn_rsvg_handle_get_pixbuf
+#  define rsvg_handle_new fn_rsvg_handle_new
+#  define rsvg_handle_set_base_uri fn_rsvg_handle_set_base_uri
+#  define rsvg_handle_write fn_rsvg_handle_write
+
+# endif /* !WINDOWSNT  */
 
 /* Load SVG image IMG for use on frame F.  Value is true if
    successful.  */
@@ -8862,28 +8908,28 @@ svg_load_image (struct frame *f,         /* Pointer to 
emacs frame structure.  *
 #if ! GLIB_CHECK_VERSION (2, 36, 0)
   /* g_type_init is a glib function that must be called prior to
      using gnome type library functions (obsolete since 2.36.0).  */
-  fn_g_type_init ();
+  g_type_init ();
 #endif
 
   /* Make a handle to a new rsvg object.  */
-  rsvg_handle = fn_rsvg_handle_new ();
+  rsvg_handle = rsvg_handle_new ();
 
   /* Set base_uri for properly handling referenced images (via 'href').
      See rsvg bug 596114 - "image refs are relative to curdir, not .svg file"
      (https://bugzilla.gnome.org/show_bug.cgi?id=596114). */
   if (filename)
-    fn_rsvg_handle_set_base_uri(rsvg_handle, filename);
+    rsvg_handle_set_base_uri(rsvg_handle, filename);
 
   /* Parse the contents argument and fill in the rsvg_handle.  */
-  fn_rsvg_handle_write (rsvg_handle, contents, size, &err);
+  rsvg_handle_write (rsvg_handle, contents, size, &err);
   if (err) goto rsvg_error;
 
   /* The parsing is complete, rsvg_handle is ready to used, close it
      for further writes.  */
-  fn_rsvg_handle_close (rsvg_handle, &err);
+  rsvg_handle_close (rsvg_handle, &err);
   if (err) goto rsvg_error;
 
-  fn_rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
+  rsvg_handle_get_dimensions (rsvg_handle, &dimension_data);
   if (! check_image_size (f, dimension_data.width, dimension_data.height))
     {
       image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
@@ -8892,26 +8938,26 @@ svg_load_image (struct frame *f,         /* Pointer to 
emacs frame structure.  *
 
   /* We can now get a valid pixel buffer from the svg file, if all
      went ok.  */
-  pixbuf = fn_rsvg_handle_get_pixbuf (rsvg_handle);
+  pixbuf = rsvg_handle_get_pixbuf (rsvg_handle);
   if (!pixbuf) goto rsvg_error;
-  fn_g_object_unref (rsvg_handle);
+  g_object_unref (rsvg_handle);
 
   /* Extract some meta data from the svg handle.  */
-  width     = fn_gdk_pixbuf_get_width (pixbuf);
-  height    = fn_gdk_pixbuf_get_height (pixbuf);
-  pixels    = fn_gdk_pixbuf_get_pixels (pixbuf);
-  rowstride = fn_gdk_pixbuf_get_rowstride (pixbuf);
+  width     = gdk_pixbuf_get_width (pixbuf);
+  height    = gdk_pixbuf_get_height (pixbuf);
+  pixels    = gdk_pixbuf_get_pixels (pixbuf);
+  rowstride = gdk_pixbuf_get_rowstride (pixbuf);
 
   /* Validate the svg meta data.  */
-  eassert (fn_gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
-  eassert (fn_gdk_pixbuf_get_n_channels (pixbuf) == 4);
-  eassert (fn_gdk_pixbuf_get_has_alpha (pixbuf));
-  eassert (fn_gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
+  eassert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
+  eassert (gdk_pixbuf_get_n_channels (pixbuf) == 4);
+  eassert (gdk_pixbuf_get_has_alpha (pixbuf));
+  eassert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
 
   /* Try to create a x pixmap to hold the svg pixmap.  */
   if (!image_create_x_image_and_pixmap (f, img, width, height, 0, &ximg, 0))
     {
-      fn_g_object_unref (pixbuf);
+      g_object_unref (pixbuf);
       return 0;
     }
 
@@ -8968,7 +9014,7 @@ svg_load_image (struct frame *f,         /* Pointer to 
emacs frame structure.  *
   free_color_table ();
 #endif /* COLOR_TABLE_SUPPORT */
 
-  fn_g_object_unref (pixbuf);
+  g_object_unref (pixbuf);
 
   img->width  = width;
   img->height = height;
@@ -8983,11 +9029,11 @@ svg_load_image (struct frame *f,         /* Pointer to 
emacs frame structure.  *
   return 1;
 
  rsvg_error:
-  fn_g_object_unref (rsvg_handle);
+  g_object_unref (rsvg_handle);
   /* FIXME: Use error->message so the user knows what is the actual
      problem with the image.  */
   image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
-  fn_g_error_free (err);
+  g_error_free (err);
   return 0;
 }
 
diff --git a/src/nsimage.m b/src/nsimage.m
index 640dfcb..d5c0647 100644
--- a/src/nsimage.m
+++ b/src/nsimage.m
@@ -351,15 +351,15 @@ ns_set_alpha (void *img, int x, int y, unsigned char a)
     {
       if ([rep respondsToSelector: @selector (getBitmapDataPlanes:)])
         {
-          NSBitmapImageRep *bmRep = (NSBitmapImageRep *) rep;
+          NSBitmapImageRep *bmr = (NSBitmapImageRep *) rep;
 
-          if ([bmRep numberOfPlanes] >= 3)
-              [bmRep getBitmapDataPlanes: pixmapData];
+          if ([bmr numberOfPlanes] >= 3)
+              [bmr getBitmapDataPlanes: pixmapData];
 
           /* The next two lines cause the DPI of the image to be ignored.
              This seems to be the behavior users expect. */
           [self setScalesWhenResized: YES];
-          [self setSize: NSMakeSize([bmRep pixelsWide], [bmRep pixelsHigh])];
+          [self setSize: NSMakeSize([bmr pixelsWide], [bmr pixelsHigh])];
 
           break;
         }
diff --git a/src/sysdep.c b/src/sysdep.c
index 24cc5cb..7158f38 100644
--- a/src/sysdep.c
+++ b/src/sysdep.c
@@ -110,6 +110,9 @@ along with GNU Emacs.  If not, see 
<http://www.gnu.org/licenses/>.  */
 #define _P_WAIT 0
 int _cdecl _spawnlp (int, const char *, const char *, ...);
 int _cdecl _getpid (void);
+/* The following is needed for O_CLOEXEC, F_SETFD, FD_CLOEXEC, and
+   several prototypes of functions called below.  */
+#include <sys/socket.h>
 #endif
 
 #include "syssignal.h"
@@ -1406,29 +1409,19 @@ setup_pty (int fd)
 }
 #endif /* HAVE_PTYS */
 
-#ifdef HAVE_SOCKETS
-#include <sys/socket.h>
-#include <netdb.h>
-#endif /* HAVE_SOCKETS */
-
-#ifdef TRY_AGAIN
-#ifndef HAVE_H_ERRNO
-extern int h_errno;
-#endif
-#endif /* TRY_AGAIN */
-
 void
 init_system_name (void)
 {
+  char *hostname_alloc = NULL;
+  char *hostname;
 #ifndef HAVE_GETHOSTNAME
   struct utsname uts;
   uname (&uts);
-  Vsystem_name = build_string (uts.nodename);
+  hostname = uts.nodename;
 #else /* HAVE_GETHOSTNAME */
-  char *hostname_alloc = NULL;
   char hostname_buf[256];
   ptrdiff_t hostname_size = sizeof hostname_buf;
-  char *hostname = hostname_buf;
+  hostname = hostname_buf;
 
   /* Try to get the host name; if the buffer is too short, try
      again.  Apparently, the only indication gethostname gives of
@@ -1446,110 +1439,15 @@ init_system_name (void)
       hostname = hostname_alloc = xpalloc (hostname_alloc, &hostname_size, 1,
                                           min (PTRDIFF_MAX, SIZE_MAX), 1);
     }
-#ifdef HAVE_SOCKETS
-  /* Turn the hostname into the official, fully-qualified hostname.
-     Don't do this if we're going to dump; this can confuse system
-     libraries on some machines and make the dumped emacs core dump. */
-#ifndef CANNOT_DUMP
-  if (initialized)
-#endif /* not CANNOT_DUMP */
-    if (! strchr (hostname, '.'))
-      {
-       int count;
-#ifdef HAVE_GETADDRINFO
-        struct addrinfo *res;
-        struct addrinfo hints;
-        int ret;
-
-        memset (&hints, 0, sizeof (hints));
-        hints.ai_socktype = SOCK_STREAM;
-        hints.ai_flags = AI_CANONNAME;
-
-       for (count = 0;; count++)
-         {
-            if ((ret = getaddrinfo (hostname, NULL, &hints, &res)) == 0
-                || ret != EAI_AGAIN)
-              break;
-
-            if (count >= 5)
-             break;
-           Fsleep_for (make_number (1), Qnil);
-         }
-
-        if (ret == 0)
-          {
-            struct addrinfo *it = res;
-            while (it)
-              {
-                char *fqdn = it->ai_canonname;
-                if (fqdn && strchr (fqdn, '.')
-                    && strcmp (fqdn, "localhost.localdomain") != 0)
-                  break;
-                it = it->ai_next;
-              }
-            if (it)
-              {
-               ptrdiff_t len = strlen (it->ai_canonname);
-               if (hostname_size <= len)
-                 {
-                   hostname_size = len + 1;
-                   hostname = hostname_alloc = xrealloc (hostname_alloc,
-                                                         hostname_size);
-                 }
-                strcpy (hostname, it->ai_canonname);
-              }
-            freeaddrinfo (res);
-          }
-#else /* !HAVE_GETADDRINFO */
-        struct hostent *hp;
-       for (count = 0;; count++)
-         {
-
-#ifdef TRY_AGAIN
-           h_errno = 0;
-#endif
-           hp = gethostbyname (hostname);
-#ifdef TRY_AGAIN
-           if (! (hp == 0 && h_errno == TRY_AGAIN))
-#endif
-
-             break;
-
-           if (count >= 5)
-             break;
-           Fsleep_for (make_number (1), Qnil);
-         }
-
-       if (hp)
-         {
-           char *fqdn = (char *) hp->h_name;
-
-           if (!strchr (fqdn, '.'))
-             {
-               /* We still don't have a fully qualified domain name.
-                  Try to find one in the list of alternate names */
-               char **alias = hp->h_aliases;
-               while (*alias
-                      && (!strchr (*alias, '.')
-                          || !strcmp (*alias, "localhost.localdomain")))
-                 alias++;
-               if (*alias)
-                 fqdn = *alias;
-             }
-           hostname = fqdn;
-         }
-#endif /* !HAVE_GETADDRINFO */
-      }
-#endif /* HAVE_SOCKETS */
-  Vsystem_name = build_string (hostname);
-  xfree (hostname_alloc);
 #endif /* HAVE_GETHOSTNAME */
-  {
-    char *p;
-    for (p = SSDATA (Vsystem_name); *p; p++)
-      if (*p == ' ' || *p == '\t')
-       *p = '-';
-  }
+  char *p;
+  for (p = hostname; *p; p++)
+    if (*p == ' ' || *p == '\t')
+      *p = '-';
+  if (! (STRINGP (Vsystem_name) && SBYTES (Vsystem_name) == p - hostname
+        && strcmp (SSDATA (Vsystem_name), hostname) == 0))
+    Vsystem_name = build_string (hostname);
+  xfree (hostname_alloc);
 }
 
 sigset_t empty_mask;
diff --git a/src/term.c b/src/term.c
index 04f6e33..bcb83e5 100644
--- a/src/term.c
+++ b/src/term.c
@@ -1736,7 +1736,7 @@ produce_composite_glyph (struct it *it)
     {
       struct composition *cmp = composition_table[it->cmp_it.id];
 
-      it->pixel_width = cmp->width;
+      it->pixel_width = cmp->pixel_width;
     }
   else
     {
diff --git a/src/w32.h b/src/w32.h
index e0aedcb..18e12b2 100644
--- a/src/w32.h
+++ b/src/w32.h
@@ -225,4 +225,17 @@ extern ssize_t emacs_gnutls_push (gnutls_transport_ptr_t p,
                                   const void* buf, size_t sz);
 #endif /* HAVE_GNUTLS */
 
+/* Definine a function that will be loaded from a DLL.  */
+#define DEF_DLL_FN(type, func, args) static type (FAR CDECL *fn_##func) args
+
+/* Load a function from the DLL.  */
+#define LOAD_DLL_FN(lib, func)                                         \
+  do                                                                   \
+    {                                                                  \
+      fn_##func = (void *) GetProcAddress (lib, #func);                        
\
+      if (!fn_##func)                                                  \
+       return false;                                                   \
+    }                                                                  \
+  while (false)
+
 #endif /* EMACS_W32_H */
diff --git a/src/xdisp.c b/src/xdisp.c
index 7074182..c87862d 100644
--- a/src/xdisp.c
+++ b/src/xdisp.c
@@ -7372,27 +7372,15 @@ set_iterator_to_next (struct it *it, int reseat_p)
       else if (it->cmp_it.id >= 0)
        {
          /* We are currently getting glyphs from a composition.  */
-         int i;
-
          if (! it->bidi_p)
            {
              IT_CHARPOS (*it) += it->cmp_it.nchars;
              IT_BYTEPOS (*it) += it->cmp_it.nbytes;
-             if (it->cmp_it.to < it->cmp_it.nglyphs)
-               {
-                 it->cmp_it.from = it->cmp_it.to;
-               }
-             else
-               {
-                 it->cmp_it.id = -1;
-                 composition_compute_stop_pos (&it->cmp_it, IT_CHARPOS (*it),
-                                               IT_BYTEPOS (*it),
-                                               it->end_charpos, Qnil);
-               }
            }
-         else if (! it->cmp_it.reversed_p)
+         else
            {
-             /* Composition created while scanning forward.  */
+             int i;
+
              /* Update IT's char/byte positions to point to the first
                 character of the next grapheme cluster, or to the
                 character visually after the current composition.  */
@@ -7400,52 +7388,34 @@ set_iterator_to_next (struct it *it, int reseat_p)
                bidi_move_to_visually_next (&it->bidi_it);
              IT_BYTEPOS (*it) = it->bidi_it.bytepos;
              IT_CHARPOS (*it) = it->bidi_it.charpos;
+           }
 
-             if (it->cmp_it.to < it->cmp_it.nglyphs)
-               {
-                 /* Proceed to the next grapheme cluster.  */
-                 it->cmp_it.from = it->cmp_it.to;
-               }
-             else
-               {
-                 /* No more grapheme clusters in this composition.
-                    Find the next stop position.  */
-                 ptrdiff_t stop = it->end_charpos;
-                 if (it->bidi_it.scan_dir < 0)
-                   /* Now we are scanning backward and don't know
-                      where to stop.  */
-                   stop = -1;
-                 composition_compute_stop_pos (&it->cmp_it, IT_CHARPOS (*it),
-                                               IT_BYTEPOS (*it), stop, Qnil);
-               }
+         if ((! it->bidi_p || ! it->cmp_it.reversed_p)
+             && it->cmp_it.to < it->cmp_it.nglyphs)
+           {
+             /* Composition created while scanning forward.  Proceed
+                to the next grapheme cluster.  */
+             it->cmp_it.from = it->cmp_it.to;
+           }
+         else if ((it->bidi_p && it->cmp_it.reversed_p)
+                  && it->cmp_it.from > 0)
+           {
+             /* Composition created while scanning backward.  Proceed
+                to the previous grapheme cluster.  */
+             it->cmp_it.to = it->cmp_it.from;
            }
          else
            {
-             /* Composition created while scanning backward.  */
-             /* Update IT's char/byte positions to point to the last
-                character of the previous grapheme cluster, or the
-                character visually after the current composition.  */
-             for (i = 0; i < it->cmp_it.nchars; i++)
-               bidi_move_to_visually_next (&it->bidi_it);
-             IT_BYTEPOS (*it) = it->bidi_it.bytepos;
-             IT_CHARPOS (*it) = it->bidi_it.charpos;
-             if (it->cmp_it.from > 0)
-               {
-                 /* Proceed to the previous grapheme cluster.  */
-                 it->cmp_it.to = it->cmp_it.from;
-               }
-             else
-               {
-                 /* No more grapheme clusters in this composition.
-                    Find the next stop position.  */
-                 ptrdiff_t stop = it->end_charpos;
-                 if (it->bidi_it.scan_dir < 0)
-                   /* Now we are scanning backward and don't know
-                      where to stop.  */
-                   stop = -1;
-                 composition_compute_stop_pos (&it->cmp_it, IT_CHARPOS (*it),
-                                               IT_BYTEPOS (*it), stop, Qnil);
-               }
+             /* No more grapheme clusters in this composition.
+                Find the next stop position.  */
+             ptrdiff_t stop = it->end_charpos;
+
+             if (it->bidi_it.scan_dir < 0)
+               /* Now we are scanning backward and don't know
+                  where to stop.  */
+               stop = -1;
+             composition_compute_stop_pos (&it->cmp_it, IT_CHARPOS (*it),
+                                           IT_BYTEPOS (*it), stop, Qnil);
            }
        }
       else
@@ -7574,61 +7544,63 @@ set_iterator_to_next (struct it *it, int reseat_p)
        }
       if (it->cmp_it.id >= 0)
        {
-         int i;
-
+         /* We are delivering display elements from a composition.
+            Update the string position past the grapheme cluster
+            we've just processed.  */
          if (! it->bidi_p)
            {
              IT_STRING_CHARPOS (*it) += it->cmp_it.nchars;
              IT_STRING_BYTEPOS (*it) += it->cmp_it.nbytes;
-             if (it->cmp_it.to < it->cmp_it.nglyphs)
-               it->cmp_it.from = it->cmp_it.to;
-             else
-               {
-                 it->cmp_it.id = -1;
-                 composition_compute_stop_pos (&it->cmp_it,
-                                               IT_STRING_CHARPOS (*it),
-                                               IT_STRING_BYTEPOS (*it),
-                                               it->end_charpos, it->string);
-               }
            }
-         else if (! it->cmp_it.reversed_p)
+         else
            {
+             int i;
+
              for (i = 0; i < it->cmp_it.nchars; i++)
                bidi_move_to_visually_next (&it->bidi_it);
              IT_STRING_BYTEPOS (*it) = it->bidi_it.bytepos;
              IT_STRING_CHARPOS (*it) = it->bidi_it.charpos;
+           }
 
-             if (it->cmp_it.to < it->cmp_it.nglyphs)
-               it->cmp_it.from = it->cmp_it.to;
-             else
-               {
-                 ptrdiff_t stop = it->end_charpos;
-                 if (it->bidi_it.scan_dir < 0)
-                   stop = -1;
-                 composition_compute_stop_pos (&it->cmp_it,
-                                               IT_STRING_CHARPOS (*it),
-                                               IT_STRING_BYTEPOS (*it), stop,
-                                               it->string);
-               }
+         /* Did we exhaust all the grapheme clusters of this
+            composition?  */
+         if ((! it->bidi_p || ! it->cmp_it.reversed_p)
+             && (it->cmp_it.to < it->cmp_it.nglyphs))
+           {
+             /* Not all the grapheme clusters were processed yet;
+                advance to the next cluster.  */
+             it->cmp_it.from = it->cmp_it.to;
+           }
+         else if ((it->bidi_p && it->cmp_it.reversed_p)
+                  && it->cmp_it.from > 0)
+           {
+             /* Likewise: advance to the next cluster, but going in
+                the reverse direction.  */
+             it->cmp_it.to = it->cmp_it.from;
            }
          else
            {
-             for (i = 0; i < it->cmp_it.nchars; i++)
-               bidi_move_to_visually_next (&it->bidi_it);
-             IT_STRING_BYTEPOS (*it) = it->bidi_it.bytepos;
-             IT_STRING_CHARPOS (*it) = it->bidi_it.charpos;
-             if (it->cmp_it.from > 0)
-               it->cmp_it.to = it->cmp_it.from;
-             else
+             /* This composition was fully processed; find the next
+                candidate place for checking for composed
+                characters.  */
+             /* Always limit string searches to the string length;
+                any padding spaces are not part of the string, and
+                there cannot be any compositions in that padding.  */
+             ptrdiff_t stop = SCHARS (it->string);
+
+             if (it->bidi_p && it->bidi_it.scan_dir < 0)
+               stop = -1;
+             else if (it->end_charpos < stop)
                {
-                 ptrdiff_t stop = it->end_charpos;
-                 if (it->bidi_it.scan_dir < 0)
-                   stop = -1;
-                 composition_compute_stop_pos (&it->cmp_it,
-                                               IT_STRING_CHARPOS (*it),
-                                               IT_STRING_BYTEPOS (*it), stop,
-                                               it->string);
+                 /* Cf. PRECISION in reseat_to_string: we might be
+                    limited in how many of the string characters we
+                    need to deliver.  */
+                 stop = it->end_charpos;
                }
+             composition_compute_stop_pos (&it->cmp_it,
+                                           IT_STRING_CHARPOS (*it),
+                                           IT_STRING_BYTEPOS (*it), stop,
+                                           it->string);
            }
        }
       else
@@ -7651,12 +7623,17 @@ set_iterator_to_next (struct it *it, int reseat_p)
              bidi_move_to_visually_next (&it->bidi_it);
              IT_STRING_BYTEPOS (*it) = it->bidi_it.bytepos;
              IT_STRING_CHARPOS (*it) = it->bidi_it.charpos;
+             /* If the scan direction changes, we may need to update
+                the place where to check for composed characters.  */
              if (prev_scan_dir != it->bidi_it.scan_dir)
                {
-                 ptrdiff_t stop = it->end_charpos;
+                 ptrdiff_t stop = SCHARS (it->string);
 
                  if (it->bidi_it.scan_dir < 0)
                    stop = -1;
+                 else if (it->end_charpos < stop)
+                   stop = it->end_charpos;
+
                  composition_compute_stop_pos (&it->cmp_it,
                                                IT_STRING_CHARPOS (*it),
                                                IT_STRING_BYTEPOS (*it), stop,
diff --git a/src/xml.c b/src/xml.c
index d418202..6be3bc7 100644
--- a/src/xml.c
+++ b/src/xml.c
@@ -33,26 +33,17 @@ static Lisp_Object Qlibxml2_dll;
 
 #ifdef WINDOWSNT
 
-#include <windows.h>
-#include "w32.h"
+# include <windows.h>
+# include "w32.h"
 
-/* Macro for defining functions that will be loaded from the libxml2 DLL.  */
-#define DEF_XML2_FN(rettype,func,args) static rettype (FAR CDECL 
*fn_##func)args
-
-/* Macro for loading libxml2 functions from the library.  */
-#define LOAD_XML2_FN(lib,func) {                                       \
-    fn_##func = (void *) GetProcAddress (lib, #func);                  \
-    if (!fn_##func) goto bad_library;                                  \
-  }
-
-DEF_XML2_FN (htmlDocPtr, htmlReadMemory,
+DEF_DLL_FN (htmlDocPtr, htmlReadMemory,
             (const char *, int, const char *, const char *, int));
-DEF_XML2_FN (xmlDocPtr, xmlReadMemory,
+DEF_DLL_FN (xmlDocPtr, xmlReadMemory,
             (const char *, int, const char *, const char *, int));
-DEF_XML2_FN (xmlNodePtr, xmlDocGetRootElement, (xmlDocPtr));
-DEF_XML2_FN (void, xmlFreeDoc, (xmlDocPtr));
-DEF_XML2_FN (void, xmlCleanupParser, (void));
-DEF_XML2_FN (void, xmlCheckVersion, (int));
+DEF_DLL_FN (xmlNodePtr, xmlDocGetRootElement, (xmlDocPtr));
+DEF_DLL_FN (void, xmlFreeDoc, (xmlDocPtr));
+DEF_DLL_FN (void, xmlCleanupParser, (void));
+DEF_DLL_FN (void, xmlCheckVersion, (int));
 
 static int
 libxml2_loaded_p (void)
@@ -64,14 +55,33 @@ libxml2_loaded_p (void)
   return 0;
 }
 
-#else  /* !WINDOWSNT */
+# undef htmlReadMemory
+# undef xmlCheckVersion
+# undef xmlCleanupParser
+# undef xmlDocGetRootElement
+# undef xmlFreeDoc
+# undef xmlReadMemory
+
+# define htmlReadMemory fn_htmlReadMemory
+# define xmlCheckVersion fn_xmlCheckVersion
+# define xmlCleanupParser fn_xmlCleanupParser
+# define xmlDocGetRootElement fn_xmlDocGetRootElement
+# define xmlFreeDoc fn_xmlFreeDoc
+# define xmlReadMemory fn_xmlReadMemory
+
+static bool
+load_dll_functions (HMODULE library)
+{
+  LOAD_DLL_FN (library, htmlReadMemory);
+  LOAD_DLL_FN (library, xmlReadMemory);
+  LOAD_DLL_FN (library, xmlDocGetRootElement);
+  LOAD_DLL_FN (library, xmlFreeDoc);
+  LOAD_DLL_FN (library, xmlCleanupParser);
+  LOAD_DLL_FN (library, xmlCheckVersion);
+  return true;
+}
 
-#define fn_htmlReadMemory       htmlReadMemory
-#define fn_xmlReadMemory        xmlReadMemory
-#define fn_xmlDocGetRootElement xmlDocGetRootElement
-#define fn_xmlFreeDoc           xmlFreeDoc
-#define fn_xmlCleanupParser     xmlCleanupParser
-#define fn_xmlCheckVersion      xmlCheckVersion
+#else  /* !WINDOWSNT */
 
 static int
 libxml2_loaded_p (void)
@@ -97,14 +107,8 @@ init_libxml2_functions (void)
          return 0;
        }
 
-      /* LOAD_XML2_FN jumps to bad_library if it fails to find the
-        named function.  */
-      LOAD_XML2_FN (library, htmlReadMemory);
-      LOAD_XML2_FN (library, xmlReadMemory);
-      LOAD_XML2_FN (library, xmlDocGetRootElement);
-      LOAD_XML2_FN (library, xmlFreeDoc);
-      LOAD_XML2_FN (library, xmlCleanupParser);
-      LOAD_XML2_FN (library, xmlCheckVersion);
+      if (! load_dll_functions (library))
+       goto bad_library;
 
       Vlibrary_cache = Fcons (Fcons (Qlibxml2_dll, Qt), Vlibrary_cache);
       return 1;
@@ -182,7 +186,7 @@ parse_region (Lisp_Object start, Lisp_Object end, 
Lisp_Object base_url, Lisp_Obj
   const char *burl = "";
   ptrdiff_t istart, iend, istart_byte, iend_byte;
 
-  fn_xmlCheckVersion (LIBXML_VERSION);
+  xmlCheckVersion (LIBXML_VERSION);
 
   validate_region (&start, &end);
 
@@ -201,16 +205,16 @@ parse_region (Lisp_Object start, Lisp_Object end, 
Lisp_Object base_url, Lisp_Obj
     }
 
   if (htmlp)
-    doc = fn_htmlReadMemory ((char *) BYTE_POS_ADDR (istart_byte),
-                            iend_byte - istart_byte, burl, "utf-8",
-                            HTML_PARSE_RECOVER|HTML_PARSE_NONET|
-                            HTML_PARSE_NOWARNING|HTML_PARSE_NOERROR|
-                            HTML_PARSE_NOBLANKS);
+    doc = htmlReadMemory ((char *) BYTE_POS_ADDR (istart_byte),
+                         iend_byte - istart_byte, burl, "utf-8",
+                         HTML_PARSE_RECOVER|HTML_PARSE_NONET|
+                         HTML_PARSE_NOWARNING|HTML_PARSE_NOERROR|
+                         HTML_PARSE_NOBLANKS);
   else
-    doc = fn_xmlReadMemory ((char *) BYTE_POS_ADDR (istart_byte),
-                           iend_byte - istart_byte, burl, "utf-8",
-                           XML_PARSE_NONET|XML_PARSE_NOWARNING|
-                           XML_PARSE_NOBLANKS |XML_PARSE_NOERROR);
+    doc = xmlReadMemory ((char *) BYTE_POS_ADDR (istart_byte),
+                        iend_byte - istart_byte, burl, "utf-8",
+                        XML_PARSE_NONET|XML_PARSE_NOWARNING|
+                        XML_PARSE_NOBLANKS |XML_PARSE_NOERROR);
 
   if (doc != NULL)
     {
@@ -232,14 +236,14 @@ parse_region (Lisp_Object start, Lisp_Object end, 
Lisp_Object base_url, Lisp_Obj
       if (NILP (result)) {
        /* The document doesn't have toplevel comments or we discarded
           them.  Get the tree the proper way. */
-       xmlNode *node = fn_xmlDocGetRootElement (doc);
+       xmlNode *node = xmlDocGetRootElement (doc);
        if (node != NULL)
          result = make_dom (node);
       } else
        result = Fcons (intern ("top"),
                        Fcons (Qnil, Fnreverse (Fcons (r, result))));
 
-      fn_xmlFreeDoc (doc);
+      xmlFreeDoc (doc);
     }
 
   return result;
@@ -249,7 +253,7 @@ void
 xml_cleanup_parser (void)
 {
   if (libxml2_loaded_p ())
-    fn_xmlCleanupParser ();
+    xmlCleanupParser ();
 }
 
 DEFUN ("libxml-parse-html-region", Flibxml_parse_html_region,
diff --git a/src/xrdb.c b/src/xrdb.c
index e21206d..8500fb1 100644
--- a/src/xrdb.c
+++ b/src/xrdb.c
@@ -385,10 +385,11 @@ get_environ_db (void)
     {
       char *home = gethomedir ();
       ptrdiff_t homelen = strlen (home);
+      Lisp_Object system_name = Fsystem_name ();
       ptrdiff_t filenamesize = (homelen + sizeof xdefaults
-                               + SBYTES (Vsystem_name));
+                               + SBYTES (system_name));
       p = filename = xrealloc (home, filenamesize);
-      lispstpcpy (stpcpy (filename + homelen, xdefaults), Vsystem_name);
+      lispstpcpy (stpcpy (filename + homelen, xdefaults), system_name);
     }
 
   db = XrmGetFileDatabase (p);
diff --git a/src/xselect.c b/src/xselect.c
index 92e8982..3f8a132 100644
--- a/src/xselect.c
+++ b/src/xselect.c
@@ -46,9 +46,10 @@ struct prop_location;
 struct selection_data;
 
 static void x_decline_selection_request (struct input_event *);
-static int x_convert_selection (struct input_event *, Lisp_Object, Lisp_Object,
-                               Atom, int, struct x_display_info *);
-static int waiting_for_other_props_on_window (Display *, Window);
+static bool x_convert_selection (struct input_event *, Lisp_Object,
+                                Lisp_Object, Atom, bool,
+                                struct x_display_info *);
+static bool waiting_for_other_props_on_window (Display *, Window);
 static struct prop_location *expect_property_change (Display *, Window,
                                                      Atom, int);
 static void unexpect_property_change (struct prop_location *);
@@ -360,7 +361,7 @@ x_own_selection (Lisp_Object selection_name, Lisp_Object 
selection_value,
 
 static Lisp_Object
 x_get_local_selection (Lisp_Object selection_symbol, Lisp_Object target_type,
-                      int local_request, struct x_display_info *dpyinfo)
+                      bool local_request, struct x_display_info *dpyinfo)
 {
   Lisp_Object local_value;
   Lisp_Object handler_fn, value, check;
@@ -470,7 +471,7 @@ struct selection_data
   ptrdiff_t size;
   int format;
   Atom type;
-  int nofree;
+  bool nofree;
   Atom property;
   /* This can be set to non-NULL during x_reply_selection_request, if
      the selection is waiting for an INCR transfer to complete.  Don't
@@ -498,7 +499,7 @@ x_selection_request_lisp_error (void)
   for (cs = converted_selections; cs; cs = next)
     {
       next = cs->next;
-      if (cs->nofree == 0 && cs->data)
+      if (! cs->nofree && cs->data)
        xfree (cs->data);
       xfree (cs);
     }
@@ -531,7 +532,7 @@ struct prop_location
   Window window;
   Atom property;
   int desired_state;
-  int arrived;
+  bool arrived;
   struct prop_location *next;
 };
 
@@ -747,7 +748,7 @@ x_handle_selection_request (struct input_event *event)
   Lisp_Object target_symbol = x_atom_to_symbol (dpyinfo, target);
   Atom property = SELECTION_EVENT_PROPERTY (event);
   Lisp_Object local_selection_data;
-  int success = 0;
+  bool success = false;
   ptrdiff_t count = SPECPDL_INDEX ();
   GCPRO2 (local_selection_data, target_symbol);
 
@@ -805,9 +806,9 @@ x_handle_selection_request (struct input_event *event)
 
          if (subproperty != None)
            x_convert_selection (event, selection_symbol, subtarget,
-                                subproperty, 1, dpyinfo);
+                                subproperty, true, dpyinfo);
        }
-      success = 1;
+      success = true;
     }
   else
     {
@@ -815,7 +816,7 @@ x_handle_selection_request (struct input_event *event)
        property = SELECTION_EVENT_TARGET (event);
       success = x_convert_selection (event, selection_symbol,
                                     target_symbol, property,
-                                    0, dpyinfo);
+                                    false, dpyinfo);
     }
 
  DONE:
@@ -844,15 +845,15 @@ x_handle_selection_request (struct input_event *event)
 
 /* Perform the requested selection conversion, and write the data to
    the converted_selections linked list, where it can be accessed by
-   x_reply_selection_request.  If FOR_MULTIPLE is non-zero, write out
+   x_reply_selection_request.  If FOR_MULTIPLE, write out
    the data even if conversion fails, using conversion_fail_tag.
 
-   Return 0 if the selection failed to convert, 1 otherwise.  */
+   Return true iff successful.  */
 
-static int
+static bool
 x_convert_selection (struct input_event *event, Lisp_Object selection_symbol,
                     Lisp_Object target_symbol, Atom property,
-                    int for_multiple, struct x_display_info *dpyinfo)
+                    bool for_multiple, struct x_display_info *dpyinfo)
 {
   struct gcpro gcpro1;
   Lisp_Object lisp_selection;
@@ -861,7 +862,7 @@ x_convert_selection (struct input_event *event, Lisp_Object 
selection_symbol,
 
   lisp_selection
     = x_get_local_selection (selection_symbol, target_symbol,
-                            0, dpyinfo);
+                            false, dpyinfo);
 
   /* A nil return value means we can't perform the conversion.  */
   if (NILP (lisp_selection)
@@ -874,7 +875,7 @@ x_convert_selection (struct input_event *event, Lisp_Object 
selection_symbol,
          cs->size = 1;
          cs->format = 32;
          cs->type = XA_ATOM;
-         cs->nofree = 1;
+         cs->nofree = true;
          cs->property = property;
          cs->wait_object = NULL;
          cs->next = converted_selections;
@@ -882,20 +883,20 @@ x_convert_selection (struct input_event *event, 
Lisp_Object selection_symbol,
        }
 
       UNGCPRO;
-      return 0;
+      return false;
     }
 
   /* Otherwise, record the converted selection to binary.  */
   cs = xmalloc (sizeof *cs);
   cs->data = NULL;
-  cs->nofree = 1;
+  cs->nofree = true;
   cs->property = property;
   cs->wait_object = NULL;
   cs->next = converted_selections;
   converted_selections = cs;
   lisp_data_to_selection_data (dpyinfo, lisp_selection, cs);
   UNGCPRO;
-  return 1;
+  return true;
 }
 
 /* Handle a SelectionClear event EVENT, which indicates that some
@@ -1012,19 +1013,16 @@ x_clear_frame_selections (struct frame *f)
       }
 }
 
-/* Nonzero if any properties for DISPLAY and WINDOW
+/* True if any properties for DISPLAY and WINDOW
    are on the list of what we are waiting for.  */
 
-static int
+static bool
 waiting_for_other_props_on_window (Display *display, Window window)
 {
-  struct prop_location *rest = property_change_wait_list;
-  while (rest)
-    if (rest->display == display && rest->window == window)
-      return 1;
-    else
-      rest = rest->next;
-  return 0;
+  for (struct prop_location *p = property_change_wait_list; p; p = p->next)
+    if (p->display == display && p->window == window)
+      return true;
+  return false;
 }
 
 /* Add an entry to the list of property changes we are waiting for.
@@ -1043,7 +1041,7 @@ expect_property_change (Display *display, Window window,
   pl->property = property;
   pl->desired_state = state;
   pl->next = property_change_wait_list;
-  pl->arrived = 0;
+  pl->arrived = false;
   property_change_wait_list = pl;
   return pl;
 }
@@ -1106,7 +1104,7 @@ wait_for_property_change (struct prop_location *location)
       EMACS_INT secs = timeout / 1000;
       int nsecs = (timeout % 1000) * 1000000;
       TRACE2 ("  Waiting %"pI"d secs, %d nsecs", secs, nsecs);
-      wait_reading_process_output (secs, nsecs, 0, 0,
+      wait_reading_process_output (secs, nsecs, 0, false,
                                   property_change_reply, NULL, 0);
 
       if (NILP (XCAR (property_change_reply)))
@@ -1138,7 +1136,7 @@ x_handle_property_notify (const XPropertyEvent *event)
                  (event->state == PropertyDelete ? "deletion" : "change"),
                  XGetAtomName (event->display, event->atom));
 
-         rest->arrived = 1;
+         rest->arrived = true;
 
          /* If this is the one wait_for_property_change is waiting for,
             tell it to wake up.  */
@@ -1204,7 +1202,7 @@ x_get_foreign_selection (Lisp_Object selection_symbol, 
Lisp_Object target_type,
      during this time.  In fact, the SAVE_TARGETS mechanism requires
      us to handle a clipboard manager's requests before it returns
      SelectionNotify. */
-#if 0
+#if false
   x_start_queuing_selection_requests ();
   record_unwind_protect_void (x_stop_queuing_selection_requests);
 #endif
@@ -1216,7 +1214,7 @@ x_get_foreign_selection (Lisp_Object selection_symbol, 
Lisp_Object target_type,
   secs = timeout / 1000;
   nsecs = (timeout % 1000) * 1000000;
   TRACE1 ("  Start waiting %"pI"d secs for SelectionNotify", secs);
-  wait_reading_process_output (secs, nsecs, 0, 0,
+  wait_reading_process_output (secs, nsecs, 0, false,
                               reading_selection_reply, NULL, 0);
   TRACE1 ("  Got event = %d", !NILP (XCAR (reading_selection_reply)));
 
@@ -1240,7 +1238,7 @@ static void
 x_get_window_property (Display *display, Window window, Atom property,
                       unsigned char **data_ret, ptrdiff_t *bytes_ret,
                       Atom *actual_type_ret, int *actual_format_ret,
-                      unsigned long *actual_size_ret, int delete_p)
+                      unsigned long *actual_size_ret)
 {
   ptrdiff_t total_size;
   unsigned long bytes_remaining;
@@ -1413,7 +1411,7 @@ receive_incremental_selection (struct x_display_info 
*dpyinfo,
   XFlush (display);
   unblock_input ();
 
-  while (1)
+  while (true)
     {
       unsigned char *tmp_data;
       ptrdiff_t tmp_size_bytes;
@@ -1427,7 +1425,7 @@ receive_incremental_selection (struct x_display_info 
*dpyinfo,
       TRACE0 ("  Get property value");
       x_get_window_property (display, window, property,
                             &tmp_data, &tmp_size_bytes,
-                            type_ret, format_ret, size_ret, 1);
+                            type_ret, format_ret, size_ret);
 
       TRACE1 ("  Read increment of %"pD"d bytes", tmp_size_bytes);
 
@@ -1488,13 +1486,12 @@ x_get_window_property_as_lisp_data (struct 
x_display_info *dpyinfo,
   TRACE0 ("Reading selection data");
 
   x_get_window_property (display, window, property, &data, &bytes,
-                        &actual_type, &actual_format, &actual_size, 1);
+                        &actual_type, &actual_format, &actual_size);
   if (! data)
     {
-      int there_is_a_selection_owner;
       block_input ();
-      there_is_a_selection_owner
-       = XGetSelectionOwner (display, selection_atom);
+      bool there_is_a_selection_owner
+       = XGetSelectionOwner (display, selection_atom) != 0;
       unblock_input ();
       if (there_is_a_selection_owner)
        signal_error ("Selection owner couldn't convert",
@@ -1687,7 +1684,7 @@ lisp_data_to_selection_data (struct x_display_info 
*dpyinfo,
   Lisp_Object type = Qnil;
 
   eassert (cs != NULL);
-  cs->nofree = 0;
+  cs->nofree = false;
 
   if (CONSP (obj) && SYMBOLP (XCAR (obj)))
     {
@@ -1714,7 +1711,7 @@ lisp_data_to_selection_data (struct x_display_info 
*dpyinfo,
       cs->format = 8;
       cs->size = SBYTES (obj);
       cs->data = SDATA (obj);
-      cs->nofree = 1;
+      cs->nofree = true;
     }
   else if (SYMBOLP (obj))
     {
@@ -1981,7 +1978,7 @@ On Nextstep, TIME-STAMP and TERMINAL are unused.  */)
   if (!f)
     error ("X selection unavailable for this frame");
 
-  val = x_get_local_selection (selection_symbol, target_type, 1,
+  val = x_get_local_selection (selection_symbol, target_type, true,
                               FRAME_DISPLAY_INFO (f));
 
   if (NILP (val) && FRAME_LIVE_P (f))
@@ -2432,7 +2429,7 @@ FRAME is on.  If FRAME is nil, the selected frame is 
used.  */)
 
 /* Convert an XClientMessageEvent to a Lisp event of type DRAG_N_DROP_EVENT.  
*/
 
-int
+bool
 x_handle_dnd_message (struct frame *f, const XClientMessageEvent *event,
                       struct x_display_info *dpyinfo, struct input_event *bufp)
 {
@@ -2448,7 +2445,7 @@ x_handle_dnd_message (struct frame *f, const 
XClientMessageEvent *event,
   for (i = 0; i < dpyinfo->x_dnd_atoms_length; ++i)
     if (dpyinfo->x_dnd_atoms[i] == event->message_type) break;
 
-  if (i == dpyinfo->x_dnd_atoms_length) return 0;
+  if (i == dpyinfo->x_dnd_atoms_length) return false;
 
   XSETFRAME (frame, f);
 
@@ -2484,7 +2481,7 @@ x_handle_dnd_message (struct frame *f, const 
XClientMessageEvent *event,
   bufp->arg = vec;
   bufp->modifiers = 0;
 
-  return 1;
+  return true;
 }
 
 DEFUN ("x-send-client-message", Fx_send_client_message,
@@ -2535,7 +2532,7 @@ x_send_client_event (Lisp_Object display, Lisp_Object 
dest, Lisp_Object from,
   Window wdest;
   XEvent event;
   struct frame *f = decode_window_system_frame (from);
-  int to_root;
+  bool to_root;
 
   CHECK_NUMBER (format);
   CHECK_CONS (values);
@@ -2592,7 +2589,7 @@ x_send_client_event (Lisp_Object display, Lisp_Object 
dest, Lisp_Object from,
      event then goes to clients selecting for events on the root window.  */
   x_catch_errors (dpyinfo->display);
   {
-    int propagate = to_root ? False : True;
+    bool propagate = !to_root;
     long mask = to_root ? 0xffffff : 0;
 
     XSendEvent (dpyinfo->display, wdest, propagate, mask, &event);
diff --git a/src/xsettings.c b/src/xsettings.c
index 5f4275d..066f426 100644
--- a/src/xsettings.c
+++ b/src/xsettings.c
@@ -68,11 +68,11 @@ store_config_changed_event (Lisp_Object arg, Lisp_Object 
display_name)
   kbd_buffer_store_event (&event);
 }
 
-/* Return non-zero if DPYINFO is still valid.  */
-static int
+/* Return true if DPYINFO is still valid.  */
+static bool
 dpyinfo_valid (struct x_display_info *dpyinfo)
 {
-  int found = 0;
+  bool found = false;
   if (dpyinfo != NULL)
     {
       struct x_display_info *d;
@@ -404,7 +404,7 @@ parse_settings (unsigned char *prop,
 
   /* First 4 bytes is a serial number, skip that.  */
 
-  if (bytes < 12) return BadLength;
+  if (bytes < 12) return settings_seen;
   memcpy (&n_settings, prop+8, 4);
   if (my_bo != that_bo) n_settings = bswap_32 (n_settings);
   bytes_parsed = 12;
@@ -419,7 +419,7 @@ parse_settings (unsigned char *prop,
       CARD32 vlen, ival = 0;
       char name[128]; /* The names we are looking for are not this long.  */
       char sval[128]; /* The values we are looking for are not this long.  */
-      int want_this;
+      bool want_this;
       int to_cpy;
 
       sval[0] = '\0';
@@ -429,8 +429,8 @@ parse_settings (unsigned char *prop,
       memcpy (&nlen, prop+bytes_parsed, 2);
       bytes_parsed += 2;
       if (my_bo != that_bo) nlen = bswap_16 (nlen);
-      if (bytes_parsed+nlen > bytes) return BadLength;
-      to_cpy = nlen > 127 ? 127 : nlen;
+      if (bytes_parsed + nlen > bytes) return settings_seen;
+      to_cpy = min (nlen, sizeof name - 1);
       memcpy (name, prop+bytes_parsed, to_cpy);
       name[to_cpy] = '\0';
 
@@ -438,20 +438,19 @@ parse_settings (unsigned char *prop,
       bytes_parsed = PAD (bytes_parsed);
 
       bytes_parsed += 4; /* Skip serial for this value */
-      if (bytes_parsed > bytes) return BadLength;
+      if (bytes_parsed > bytes) return settings_seen;
 
-      want_this =
+      want_this = strcmp (XSETTINGS_TOOL_BAR_STYLE, name) == 0;
 #ifdef HAVE_XFT
-        (nlen > 6 && strncmp (name, "Xft/", 4) == 0)
-        || strcmp (XSETTINGS_FONT_NAME, name) == 0
-        ||
+      if ((nlen > 6 && memcmp (name, "Xft/", 4) == 0)
+         || strcmp (XSETTINGS_FONT_NAME, name) == 0)
+       want_this = true;
 #endif
-        strcmp (XSETTINGS_TOOL_BAR_STYLE, name) == 0;
 
       switch (type)
         {
         case 0: /* Integer */
-          if (bytes_parsed+4 > bytes) return BadLength;
+          if (bytes_parsed + 4 > bytes) return settings_seen;
           if (want_this)
             {
               memcpy (&ival, prop+bytes_parsed, 4);
@@ -461,13 +460,13 @@ parse_settings (unsigned char *prop,
           break;
 
         case 1: /* String */
-          if (bytes_parsed+4 > bytes) return BadLength;
+          if (bytes_parsed + 4 > bytes) return settings_seen;
           memcpy (&vlen, prop+bytes_parsed, 4);
           bytes_parsed += 4;
           if (my_bo != that_bo) vlen = bswap_32 (vlen);
           if (want_this)
             {
-              to_cpy = vlen > 127 ? 127 : vlen;
+              to_cpy = min (vlen, sizeof sval - 1);
               memcpy (sval, prop+bytes_parsed, to_cpy);
               sval[to_cpy] = '\0';
             }
@@ -477,17 +476,16 @@ parse_settings (unsigned char *prop,
 
         case 2: /* RGB value */
           /* No need to parse this */
-          if (bytes_parsed+8 > bytes) return BadLength;
+          if (bytes_parsed + 8 > bytes) return settings_seen;
           bytes_parsed += 8; /* 4 values (r, b, g, alpha), 2 bytes each.  */
           break;
 
         default: /* Parse Error */
-          return BadValue;
+          return settings_seen;
         }
 
       if (want_this)
         {
-          ++settings_seen;
           if (strcmp (name, XSETTINGS_TOOL_BAR_STYLE) == 0)
             {
               dupstring (&settings->tb_style, sval);
@@ -557,6 +555,9 @@ parse_settings (unsigned char *prop,
                 settings->seen &= ~SEEN_LCDFILTER;
             }
 #endif /* HAVE_XFT */
+         else
+           want_this = false;
+         settings_seen += want_this;
         }
     }
 
@@ -565,9 +566,9 @@ parse_settings (unsigned char *prop,
 
 /* Read settings from the XSettings property window on display for DPYINFO.
    Store settings read in SETTINGS.
-   Return non-zero if successful, zero if not.  */
+   Return true iff successful.  */
 
-static int
+static bool
 read_settings (struct x_display_info *dpyinfo, struct xsettings *settings)
 {
   Atom act_type;
@@ -576,6 +577,7 @@ read_settings (struct x_display_info *dpyinfo, struct 
xsettings *settings)
   unsigned char *prop = NULL;
   Display *dpy = dpyinfo->display;
   int rc;
+  bool got_settings = false;
 
   x_catch_errors (dpy);
   rc = XGetWindowProperty (dpy,
@@ -587,27 +589,26 @@ read_settings (struct x_display_info *dpyinfo, struct 
xsettings *settings)
 
   if (rc == Success && prop != NULL && act_form == 8 && nitems > 0
       && act_type == dpyinfo->Xatom_xsettings_prop)
-    rc = parse_settings (prop, nitems, settings);
+    got_settings = parse_settings (prop, nitems, settings) != 0;
 
   XFree (prop);
 
   x_uncatch_errors ();
 
-  return rc != 0;
+  return got_settings;
 }
 
 /* Apply Xft settings in SETTINGS to the Xft library.
-   If SEND_EVENT_P is non-zero store a Lisp event that Xft settings changed.  
*/
+   Store a Lisp event that Xft settings changed.  */
 
 static void
 apply_xft_settings (struct x_display_info *dpyinfo,
-                    int send_event_p,
                     struct xsettings *settings)
 {
 #ifdef HAVE_XFT
   FcPattern *pat;
   struct xsettings oldsettings;
-  int changed = 0;
+  bool changed = false;
 
   memset (&oldsettings, 0, sizeof (oldsettings));
   pat = FcPatternCreate ();
@@ -627,7 +628,7 @@ apply_xft_settings (struct x_display_info *dpyinfo,
     {
       FcPatternDel (pat, FC_ANTIALIAS);
       FcPatternAddBool (pat, FC_ANTIALIAS, settings->aa);
-      ++changed;
+      changed = true;
       oldsettings.aa = settings->aa;
     }
 
@@ -636,7 +637,7 @@ apply_xft_settings (struct x_display_info *dpyinfo,
     {
       FcPatternDel (pat, FC_HINTING);
       FcPatternAddBool (pat, FC_HINTING, settings->hinting);
-      ++changed;
+      changed = true;
       oldsettings.hinting = settings->hinting;
     }
   if ((settings->seen & SEEN_RGBA) != 0 && oldsettings.rgba != settings->rgba)
@@ -644,7 +645,7 @@ apply_xft_settings (struct x_display_info *dpyinfo,
       FcPatternDel (pat, FC_RGBA);
       FcPatternAddInteger (pat, FC_RGBA, settings->rgba);
       oldsettings.rgba = settings->rgba;
-      ++changed;
+      changed = true;
     }
 
   /* Older fontconfig versions don't have FC_LCD_FILTER. */
@@ -653,7 +654,7 @@ apply_xft_settings (struct x_display_info *dpyinfo,
     {
       FcPatternDel (pat, FC_LCD_FILTER);
       FcPatternAddInteger (pat, FC_LCD_FILTER, settings->lcdfilter);
-      ++changed;
+      changed = true;
       oldsettings.lcdfilter = settings->lcdfilter;
     }
 
@@ -663,7 +664,7 @@ apply_xft_settings (struct x_display_info *dpyinfo,
     {
       FcPatternDel (pat, FC_HINT_STYLE);
       FcPatternAddInteger (pat, FC_HINT_STYLE, settings->hintstyle);
-      ++changed;
+      changed = true;
       oldsettings.hintstyle = settings->hintstyle;
     }
 #endif
@@ -673,7 +674,7 @@ apply_xft_settings (struct x_display_info *dpyinfo,
     {
       FcPatternDel (pat, FC_DPI);
       FcPatternAddDouble (pat, FC_DPI, settings->dpi);
-      ++changed;
+      changed = true;
       oldsettings.dpi = settings->dpi;
 
       /* Changing the DPI on this display affects all frames on it.
@@ -699,9 +700,8 @@ apply_xft_settings (struct x_display_info *dpyinfo,
       char buf[sizeof format + d_formats * d_growth + lf_formats * lf_growth];
 
       XftDefaultSet (dpyinfo->display, pat);
-      if (send_event_p)
-        store_config_changed_event (Qfont_render,
-                                    XCAR (dpyinfo->name_list_element));
+      store_config_changed_event (Qfont_render,
+                                 XCAR (dpyinfo->name_list_element));
       Vxft_settings
        = make_formatted_string (buf, format,
                                 oldsettings.aa, oldsettings.hinting,
@@ -715,17 +715,17 @@ apply_xft_settings (struct x_display_info *dpyinfo,
 }
 
 /* Read XSettings from the display for DPYINFO.
-   If SEND_EVENT_P is non-zero store a Lisp event settings that changed.  */
+   If SEND_EVENT_P store a Lisp event settings that changed.  */
 
 static void
-read_and_apply_settings (struct x_display_info *dpyinfo, int send_event_p)
+read_and_apply_settings (struct x_display_info *dpyinfo, bool send_event_p)
 {
   struct xsettings settings;
 
   if (!read_settings (dpyinfo, &settings))
     return;
 
-  apply_xft_settings (dpyinfo, True, &settings);
+  apply_xft_settings (dpyinfo, &settings);
   if (settings.seen & SEEN_TB_STYLE)
     {
       if (send_event_p)
@@ -751,27 +751,27 @@ read_and_apply_settings (struct x_display_info *dpyinfo, 
int send_event_p)
 void
 xft_settings_event (struct x_display_info *dpyinfo, const XEvent *event)
 {
-  bool check_window_p = 0, apply_settings_p = 0;
+  bool check_window_p = false, apply_settings_p = false;
 
   switch (event->type)
     {
     case DestroyNotify:
       if (dpyinfo->xsettings_window == event->xany.window)
-        check_window_p = 1;
+        check_window_p = true;
       break;
 
     case ClientMessage:
       if (event->xclient.message_type == dpyinfo->Xatom_xsettings_mgr
           && event->xclient.data.l[1] == dpyinfo->Xatom_xsettings_sel
           && event->xclient.window == dpyinfo->root_window)
-        check_window_p = 1;
+        check_window_p = true;
       break;
 
     case PropertyNotify:
       if (event->xproperty.window == dpyinfo->xsettings_window
           && event->xproperty.state == PropertyNewValue
           && event->xproperty.atom == dpyinfo->Xatom_xsettings_prop)
-        apply_settings_p = 1;
+        apply_settings_p = true;
       break;
     }
 
@@ -781,11 +781,11 @@ xft_settings_event (struct x_display_info *dpyinfo, const 
XEvent *event)
       dpyinfo->xsettings_window = None;
       get_prop_window (dpyinfo);
       if (dpyinfo->xsettings_window != None)
-        apply_settings_p = 1;
+        apply_settings_p = true;
     }
 
   if (apply_settings_p)
-    read_and_apply_settings (dpyinfo, True);
+    read_and_apply_settings (dpyinfo, true);
 }
 
 /* Initialize GSettings and read startup values.  */
@@ -795,7 +795,7 @@ init_gsettings (void)
 {
 #ifdef HAVE_GSETTINGS
   GVariant *val;
-  int schema_found = 0;
+  bool schema_found = false;
 
 #if ! GLIB_CHECK_VERSION (2, 36, 0)
   g_type_init ();
@@ -937,7 +937,7 @@ init_xsettings (struct x_display_info *dpyinfo)
 
   get_prop_window (dpyinfo);
   if (dpyinfo->xsettings_window != None)
-    read_and_apply_settings (dpyinfo, False);
+    read_and_apply_settings (dpyinfo, false);
 
   unblock_input ();
 }
@@ -1030,7 +1030,7 @@ syms_of_xsettings (void)
 When this is non-nil and the system defined fixed width font changes, we
 update frames dynamically.
 If this variable is nil, Emacs ignores system font changes.  */);
-  use_system_font = 0;
+  use_system_font = false;
 
   DEFVAR_LISP ("xft-settings", Vxft_settings,
                doc: /* Font settings applied to Xft.  */);
diff --git a/src/xterm.c b/src/xterm.c
index f3b9cbe..c9b9e84 100644
--- a/src/xterm.c
+++ b/src/xterm.c
@@ -9244,13 +9244,9 @@ do_ewmh_fullscreen (struct frame *f)
       switch (f->want_fullscreen)
         {
         case FULLSCREEN_BOTH:
-          if (cur == FULLSCREEN_WIDTH || cur == FULLSCREEN_MAXIMIZED
-              || cur == FULLSCREEN_HEIGHT)
-            set_wm_state (frame, false,
-                         dpyinfo->Xatom_net_wm_state_maximized_horz,
-                          dpyinfo->Xatom_net_wm_state_maximized_vert);
-          set_wm_state (frame, true,
-                       dpyinfo->Xatom_net_wm_state_fullscreen, None);
+          if (cur != FULLSCREEN_BOTH)
+            set_wm_state (frame, true, dpyinfo->Xatom_net_wm_state_fullscreen,
+                          None);
           break;
         case FULLSCREEN_WIDTH:
           if (cur == FULLSCREEN_BOTH || cur == FULLSCREEN_HEIGHT
@@ -10515,8 +10511,9 @@ static bool
 same_x_server (const char *name1, const char *name2)
 {
   bool seen_colon = false;
-  const char *system_name = SSDATA (Vsystem_name);
-  ptrdiff_t system_name_length = SBYTES (Vsystem_name);
+  Lisp_Object sysname = Fsystem_name ();
+  const char *system_name = SSDATA (sysname);
+  ptrdiff_t system_name_length = SBYTES (sysname);
   ptrdiff_t length_until_period = 0;
 
   while (system_name[length_until_period] != 0
@@ -10912,14 +10909,15 @@ x_term_init (Lisp_Object display_name, char 
*xrm_option, char *resource_name)
 #endif
 
   lim = min (PTRDIFF_MAX, SIZE_MAX) - sizeof "@";
-  if (lim - SBYTES (Vinvocation_name) < SBYTES (Vsystem_name))
+  Lisp_Object system_name = Fsystem_name ();
+  if (lim - SBYTES (Vinvocation_name) < SBYTES (system_name))
     memory_full (SIZE_MAX);
   dpyinfo->x_id = ++x_display_id;
   dpyinfo->x_id_name = xmalloc (SBYTES (Vinvocation_name)
-                               + SBYTES (Vsystem_name) + 2);
+                               + SBYTES (system_name) + 2);
   char *nametail = lispstpcpy (dpyinfo->x_id_name, Vinvocation_name);
   *nametail++ = '@';
-  lispstpcpy (nametail, Vsystem_name);
+  lispstpcpy (nametail, system_name);
 
   /* Figure out which modifier bits mean what.  */
   x_find_modifier_meanings (dpyinfo);
diff --git a/src/xterm.h b/src/xterm.h
index 84bb58c..13877d3 100644
--- a/src/xterm.h
+++ b/src/xterm.h
@@ -1049,10 +1049,10 @@ extern void x_send_client_event (Lisp_Object display,
                                  Lisp_Object format,
                                  Lisp_Object values);
 
-extern int x_handle_dnd_message (struct frame *,
-                                 const XClientMessageEvent *,
-                                 struct x_display_info *,
-                                 struct input_event *);
+extern bool x_handle_dnd_message (struct frame *,
+                                 const XClientMessageEvent *,
+                                 struct x_display_info *,
+                                 struct input_event *);
 extern int x_check_property_data (Lisp_Object);
 extern void x_fill_property_data (Display *,
                                   Lisp_Object,
diff --git a/test/ChangeLog b/test/ChangeLog
index 7d33014..2ea3254 100644
--- a/test/ChangeLog
+++ b/test/ChangeLog
@@ -1,3 +1,72 @@
+2014-12-27  Glenn Morris  <address@hidden>
+
+       * automated/let-alist.el: Load dependency.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       * automated/python-tests.el
+       (python-shell-completion-native-interpreter-disabled-p-1): New
+       test.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       * automated/python-tests.el (python-shell-get-or-create-process-1)
+       (python-shell-get-or-create-process-2)
+       (python-shell-get-or-create-process-3): Remove tests.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       (python-shell-buffer-substring-9): New test.
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       * automated/python-tests.el (python-shell-buffer-substring-1)
+       (python-shell-buffer-substring-2, python-shell-buffer-substring-3)
+       (python-shell-buffer-substring-4, python-shell-buffer-substring-5)
+       (python-shell-buffer-substring-6, python-shell-buffer-substring-7)
+       (python-shell-buffer-substring-8)
+       (python-info-encoding-from-cookie-1)
+       (python-info-encoding-from-cookie-2)
+       (python-info-encoding-from-cookie-3)
+       (python-info-encoding-from-cookie-4)
+       (python-info-encoding-from-cookie-5)
+       (python-info-encoding-from-cookie-6)
+       (python-info-encoding-from-cookie-7, python-info-encoding-1)
+       (python-info-encoding-2): New tests.
+
+2014-12-27  Michael Albinus  <address@hidden>
+
+       * automated/tramp-tests.el (tramp-test17-insert-directory): Do not
+       expect a given order of "." and "..".
+
+2014-12-27  Fabián Ezequiel Gallina  <address@hidden>
+
+       * automated/python-tests.el (python-indent-electric-colon-2)
+       (python-indent-electric-colon-3): New tests.
+
+2014-12-27  João Távora  <address@hidden>
+
+       * automated/electric-tests.el (autowrapping-7): Tests for
+       tex-mode.
+
+2014-12-27  Glenn Morris  <address@hidden>
+
+       * automated/flymake/warnpred/test.pl: Tweak format, since the
+       previous one seems to have stopped giving a warning with perl 5.20.1.
+
+2014-12-26  Fabián Ezequiel Gallina  <address@hidden>
+
+       * automated/python-tests.el (python-shell-get-process-name-1)
+       (python-shell-internal-get-process-name-1): Cleanup.
+       (python-shell-get-process-name-2)
+       (python-shell-internal-get-process-name-2): New tests.
+       (python-shell-calculate-command-1)
+       (python-shell-calculate-process-environment-3)
+       (python-shell-calculate-exec-path-2, python-shell-make-comint-1)
+       (python-shell-make-comint-2, python-shell-make-comint-4)
+       (python-shell-get-process-1, python-util-clone-local-variables-1):
+       Replace obsolete function and variable references with current.
+
 2014-12-19  Artur Malabarba  <address@hidden>
 
        * automated/let-alist.el: require `cl-lib'
diff --git a/test/automated/data/flymake/test.pl 
b/test/automated/data/flymake/test.pl
index 2013b2e..d5abcb4 100644
--- a/test/automated/data/flymake/test.pl
+++ b/test/automated/data/flymake/test.pl
@@ -1,2 +1,2 @@
 @arr = [1,2,3,4];
address@hidden = -1;
+my $b = @arr[1];
diff --git a/test/automated/electric-tests.el b/test/automated/electric-tests.el
index b1908e6..cd07213 100644
--- a/test/automated/electric-tests.el
+++ b/test/automated/electric-tests.el
@@ -60,7 +60,7 @@
         (cl-progv
             (mapcar #'car bindings)
             (mapcar #'cdr bindings)
-          (self-insert-command 1))))
+          (call-interactively (key-binding `[,last-command-event])))))
     (should (equal (buffer-substring-no-properties (point-min) (point-max))
                    expected-string))
     (should (equal (point)
@@ -575,5 +575,14 @@ baz\"\""
                   (skip-chars-backward "\"")
                   (mark-sexp -1)))
 
+(define-electric-pair-test autowrapping-7
+  "foo" "\"" :expected-string "``foo''" :expected-point 8
+  :modes '(tex-mode)
+  :fixture-fn #'(lambda ()
+                  (electric-pair-mode 1)
+                  (goto-char (point-max))
+                  (skip-chars-backward "\"")
+                  (mark-sexp -1)))
+
 (provide 'electric-tests)
 ;;; electric-tests.el ends here
diff --git a/test/automated/let-alist.el b/test/automated/let-alist.el
index 6f58908..a45864e 100644
--- a/test/automated/let-alist.el
+++ b/test/automated/let-alist.el
@@ -21,6 +21,7 @@
 
 (require 'ert)
 (require 'cl-lib)
+(require 'let-alist)
 
 (ert-deftest let-alist-surface-test ()
   "Tests basic macro expansion for `let-alist'."
diff --git a/test/automated/python-tests.el b/test/automated/python-tests.el
index de20a80..ca43c45 100644
--- a/test/automated/python-tests.el
+++ b/test/automated/python-tests.el
@@ -740,6 +740,39 @@ def b()
    (python-tests-self-insert ":")
    (should (= (current-indentation) 0))))
 
+(ert-deftest python-indent-electric-colon-2 ()
+  "Test indentation case for dedenter."
+  (python-tests-with-temp-buffer
+   "
+if do:
+    something()
+    else
+"
+   (python-tests-look-at "else")
+   (goto-char (line-end-position))
+   (python-tests-self-insert ":")
+   (should (= (current-indentation) 0))))
+
+(ert-deftest python-indent-electric-colon-3 ()
+  "Test indentation case for multi-line dedenter."
+  (python-tests-with-temp-buffer
+   "
+if do:
+    something()
+    elif (this
+          and
+          that)
+"
+   (python-tests-look-at "that)")
+   (goto-char (line-end-position))
+   (python-tests-self-insert ":")
+   (python-tests-look-at "elif" -1)
+   (should (= (current-indentation) 0))
+   (python-tests-look-at "and")
+   (should (= (current-indentation) 6))
+   (python-tests-look-at "that)")
+   (should (= (current-indentation) 6))))
+
 (ert-deftest python-indent-region-1 ()
   "Test indentation case from Bug#18843."
   (let ((contents "
@@ -1775,52 +1808,41 @@ def f():
 (defvar python-tests-shell-interpreter "python")
 
 (ert-deftest python-shell-get-process-name-1 ()
-  "Check process name calculation on different scenarios."
+  "Check process name calculation sans `buffer-file-name'."
   (python-tests-with-temp-buffer
-      ""
-    (should (string= (python-shell-get-process-name nil)
-                     python-shell-buffer-name))
-    ;; When the `current-buffer' doesn't have `buffer-file-name', even
-    ;; if dedicated flag is non-nil should not include its name.
-    (should (string= (python-shell-get-process-name t)
-                     python-shell-buffer-name)))
+   ""
+   (should (string= (python-shell-get-process-name nil)
+                    python-shell-buffer-name))
+   (should (string= (python-shell-get-process-name t)
+                    (format "%s[%s]" python-shell-buffer-name 
(buffer-name))))))
+
+(ert-deftest python-shell-get-process-name-2 ()
+  "Check process name calculation with `buffer-file-name'."
   (python-tests-with-temp-file
-      ""
-    ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
-    ;; should be respected.
-    (should (string= (python-shell-get-process-name nil)
-                     python-shell-buffer-name))
-    (should (string=
-             (python-shell-get-process-name t)
-             (format "%s[%s]" python-shell-buffer-name buffer-file-name)))))
+   ""
+   ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
+   ;; should be respected.
+   (should (string= (python-shell-get-process-name nil)
+                    python-shell-buffer-name))
+   (should (string=
+            (python-shell-get-process-name t)
+            (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
 
 (ert-deftest python-shell-internal-get-process-name-1 ()
-  "Check the internal process name is config-unique."
-  (let* ((python-shell-interpreter python-tests-shell-interpreter)
-         (python-shell-interpreter-args "")
-         (python-shell-prompt-regexp ">>> ")
-         (python-shell-prompt-block-regexp "[.][.][.] ")
-         (python-shell-setup-codes "")
-         (python-shell-process-environment "")
-         (python-shell-extra-pythonpaths "")
-         (python-shell-exec-path "")
-         (python-shell-virtualenv-path "")
-         (expected (python-tests-with-temp-buffer
-                       "" (python-shell-internal-get-process-name))))
-    ;; Same configurations should match.
-    (should
-     (string= expected
-              (python-tests-with-temp-buffer
-                  "" (python-shell-internal-get-process-name))))
-    (let ((python-shell-interpreter-args "-B"))
-      ;; A minimal change should generate different names.
-      (should
-       (not (string=
-             expected
-             (python-tests-with-temp-buffer
-                 "" (python-shell-internal-get-process-name))))))))
-
-(ert-deftest python-shell-parse-command-1 ()
+  "Check the internal process name is buffer-unique sans `buffer-file-name'."
+  (python-tests-with-temp-buffer
+   ""
+   (should (string= (python-shell-internal-get-process-name)
+                    (format "%s[%s]" python-shell-internal-buffer-name 
(buffer-name))))))
+
+(ert-deftest python-shell-internal-get-process-name-2 ()
+  "Check the internal process name is buffer-unique with `buffer-file-name'."
+  (python-tests-with-temp-file
+   ""
+   (should (string= (python-shell-internal-get-process-name)
+                    (format "%s[%s]" python-shell-internal-buffer-name 
(buffer-name))))))
+
+(ert-deftest python-shell-calculate-command-1 ()
   "Check the command to execute is calculated correctly.
 Using `python-shell-interpreter' and
 `python-shell-interpreter-args'."
@@ -1832,7 +1854,7 @@ Using `python-shell-interpreter' and
              (format "%s %s"
                      python-shell-interpreter
                      python-shell-interpreter-args)
-             (python-shell-parse-command)))))
+             (python-shell-calculate-command)))))
 
 (ert-deftest python-shell-calculate-process-environment-1 ()
   "Test `python-shell-process-environment' modification."
@@ -1857,17 +1879,17 @@ Using `python-shell-interpreter' and
                     path-separator original-pythonpath)))))
 
 (ert-deftest python-shell-calculate-process-environment-3 ()
-  "Test `python-shell-virtualenv-path' modification."
+  "Test `python-shell-virtualenv-root' modification."
   (let* ((original-path (or (getenv "PATH") ""))
-         (python-shell-virtualenv-path
+         (python-shell-virtualenv-root
           (directory-file-name user-emacs-directory))
          (process-environment
           (python-shell-calculate-process-environment)))
     (should (not (getenv "PYTHONHOME")))
-    (should (string= (getenv "VIRTUAL_ENV") python-shell-virtualenv-path))
+    (should (string= (getenv "VIRTUAL_ENV") python-shell-virtualenv-root))
     (should (equal (getenv "PATH")
                    (format "%s/bin%s%s"
-                           python-shell-virtualenv-path
+                           python-shell-virtualenv-root
                            path-separator original-path)))))
 
 (ert-deftest python-shell-calculate-process-environment-4 ()
@@ -1900,13 +1922,13 @@ Using `python-shell-interpreter' and
 (ert-deftest python-shell-calculate-exec-path-2 ()
   "Test `python-shell-exec-path' modification."
   (let* ((original-exec-path exec-path)
-         (python-shell-virtualenv-path
+         (python-shell-virtualenv-root
           (directory-file-name (expand-file-name user-emacs-directory)))
          (exec-path (python-shell-calculate-exec-path)))
     (should (equal
              exec-path
              (append (cons
-                      (format "%s/bin" python-shell-virtualenv-path)
+                      (format "%s/bin" python-shell-virtualenv-root)
                       original-exec-path))))))
 
 (ert-deftest python-shell-make-comint-1 ()
@@ -1922,7 +1944,7 @@ Using `python-shell-interpreter' and
          (shell-buffer
           (python-tests-with-temp-buffer
            "" (python-shell-make-comint
-               (python-shell-parse-command) proc-name)))
+               (python-shell-calculate-command) proc-name)))
          (process (get-buffer-process shell-buffer)))
     (unwind-protect
         (progn
@@ -1943,7 +1965,7 @@ Using `python-shell-interpreter' and
          (shell-buffer
           (python-tests-with-temp-buffer
            "" (python-shell-make-comint
-               (python-shell-parse-command) proc-name nil t)))
+               (python-shell-calculate-command) proc-name nil t)))
          (process (get-buffer-process shell-buffer)))
     (unwind-protect
         (progn
@@ -2010,7 +2032,7 @@ and `python-shell-interpreter-args' in the new shell 
buffer."
             (setenv "PYTHONSTARTUP" startup-file)
             (python-tests-with-temp-buffer
              "" (python-shell-make-comint
-                 (python-shell-parse-command) proc-name nil))))
+                 (python-shell-calculate-command) proc-name nil))))
          (process (get-buffer-process shell-buffer)))
     (unwind-protect
         (progn
@@ -2040,10 +2062,10 @@ and `python-shell-interpreter-args' in the new shell 
buffer."
            (dedicated-proc-name (python-shell-get-process-name t))
            (global-shell-buffer
             (python-shell-make-comint
-             (python-shell-parse-command) global-proc-name))
+             (python-shell-calculate-command) global-proc-name))
            (dedicated-shell-buffer
             (python-shell-make-comint
-             (python-shell-parse-command) dedicated-proc-name))
+             (python-shell-calculate-command) dedicated-proc-name))
            (global-process (get-buffer-process global-shell-buffer))
            (dedicated-process (get-buffer-process dedicated-shell-buffer)))
       (unwind-protect
@@ -2061,84 +2083,6 @@ and `python-shell-interpreter-args' in the new shell 
buffer."
         (ignore-errors (kill-buffer global-shell-buffer))
         (ignore-errors (kill-buffer dedicated-shell-buffer))))))
 
-(ert-deftest python-shell-get-or-create-process-1 ()
-  "Check shell dedicated process creation."
-  (skip-unless (executable-find python-tests-shell-interpreter))
-  (python-tests-with-temp-file
-   ""
-   (let* ((cmd
-           (concat (executable-find python-tests-shell-interpreter) " -i"))
-          (use-dialog-box)
-          (dedicated-process-name (python-shell-get-process-name t))
-          (dedicated-process (python-shell-get-or-create-process cmd t))
-          (dedicated-shell-buffer (process-buffer dedicated-process)))
-     (unwind-protect
-         (progn
-           (set-process-query-on-exit-flag dedicated-process nil)
-           ;; should be dedicated.
-           (should (equal (process-name dedicated-process)
-                          dedicated-process-name))
-           (kill-buffer dedicated-shell-buffer)
-           ;; Check there are no processes for current buffer.
-           (should (not (python-shell-get-process))))
-       (ignore-errors (kill-buffer dedicated-shell-buffer))))))
-
-(ert-deftest python-shell-get-or-create-process-2 ()
-  "Check shell global process creation."
-  (skip-unless (executable-find python-tests-shell-interpreter))
-  (python-tests-with-temp-file
-   ""
-   (let* ((cmd
-           (concat (executable-find python-tests-shell-interpreter) " -i"))
-          (use-dialog-box)
-          (process-name (python-shell-get-process-name nil))
-          (process (python-shell-get-or-create-process cmd))
-          (shell-buffer (process-buffer process)))
-     (unwind-protect
-         (progn
-           (set-process-query-on-exit-flag process nil)
-           ;; should be global.
-           (should (equal (process-name process) process-name))
-           (kill-buffer shell-buffer)
-           ;; Check there are no processes for current buffer.
-           (should (not (python-shell-get-process))))
-       (ignore-errors (kill-buffer shell-buffer))))))
-
-(ert-deftest python-shell-get-or-create-process-3 ()
-  "Check shell dedicated/global process preference."
-  (skip-unless (executable-find python-tests-shell-interpreter))
-  (python-tests-with-temp-file
-   ""
-   (let* ((cmd
-           (concat (executable-find python-tests-shell-interpreter) " -i"))
-          (python-shell-interpreter python-tests-shell-interpreter)
-          (use-dialog-box)
-          (dedicated-process-name (python-shell-get-process-name t))
-          (global-process)
-          (dedicated-process))
-     (progn
-       ;; Create global process
-       (run-python cmd nil)
-       (setq global-process (get-buffer-process "*Python*"))
-       (should global-process)
-       (set-process-query-on-exit-flag global-process nil)
-       ;; Create dedicated process
-       (run-python cmd t)
-       (setq dedicated-process (get-process dedicated-process-name))
-       (should dedicated-process)
-       (set-process-query-on-exit-flag dedicated-process nil)
-       ;; Prefer dedicated.
-       (should (equal (python-shell-get-or-create-process)
-                      dedicated-process))
-       ;; Kill the dedicated so the global takes over.
-       (kill-buffer (process-buffer dedicated-process))
-       ;; Detect global.
-       (should (equal (python-shell-get-or-create-process) global-process))
-       ;; Kill the global.
-       (kill-buffer (process-buffer global-process))
-       ;; Check there are no processes for current buffer.
-       (should (not (python-shell-get-process)))))))
-
 (ert-deftest python-shell-internal-get-or-create-process-1 ()
   "Check internal shell process creation fallback."
   (skip-unless (executable-find python-tests-shell-interpreter))
@@ -2424,9 +2368,229 @@ and `python-shell-interpreter-args' in the new shell 
buffer."
                            "^\\(o\\.t \\|\\)")))
       (ignore-errors (delete-file startup-file)))))
 
+(ert-deftest python-shell-buffer-substring-1 ()
+  "Selecting a substring of the whole buffer must match its contents."
+  (python-tests-with-temp-buffer
+   "
+class Foo(models.Model):
+    pass
+
+
+class Bar(models.Model):
+    pass
+"
+   (should (string= (buffer-string)
+                    (python-shell-buffer-substring (point-min) (point-max))))))
+
+(ert-deftest python-shell-buffer-substring-2 ()
+  "Main block should be removed if NOMAIN is non-nil."
+  (python-tests-with-temp-buffer
+   "
+class Foo(models.Model):
+    pass
+
+class Bar(models.Model):
+    pass
+
+if __name__ == \"__main__\":
+    foo = Foo()
+    print (foo)
+"
+   (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
+                    "
+class Foo(models.Model):
+    pass
+
+class Bar(models.Model):
+    pass
+
+
+
+
+"))))
+
+(ert-deftest python-shell-buffer-substring-3 ()
+  "Main block should be removed if NOMAIN is non-nil."
+  (python-tests-with-temp-buffer
+   "
+class Foo(models.Model):
+    pass
+
+if __name__ == \"__main__\":
+    foo = Foo()
+    print (foo)
+
+class Bar(models.Model):
+    pass
+"
+   (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
+                    "
+class Foo(models.Model):
+    pass
+
+
+
+
+
+class Bar(models.Model):
+    pass
+"))))
+
+(ert-deftest python-shell-buffer-substring-4 ()
+  "Coding cookie should be added for substrings."
+  (python-tests-with-temp-buffer
+   "# coding: latin-1
+
+class Foo(models.Model):
+    pass
+
+if __name__ == \"__main__\":
+    foo = Foo()
+    print (foo)
+
+class Bar(models.Model):
+    pass
+"
+   (should (string= (python-shell-buffer-substring
+                     (python-tests-look-at "class Foo(models.Model):")
+                     (progn (python-nav-forward-sexp) (point)))
+                    "# -*- coding: latin-1 -*-
+
+class Foo(models.Model):
+    pass"))))
+
+(ert-deftest python-shell-buffer-substring-5 ()
+  "The proper amount of blank lines is added for a substring."
+  (python-tests-with-temp-buffer
+   "# coding: latin-1
+
+class Foo(models.Model):
+    pass
+
+if __name__ == \"__main__\":
+    foo = Foo()
+    print (foo)
+
+class Bar(models.Model):
+    pass
+"
+   (should (string= (python-shell-buffer-substring
+                     (python-tests-look-at "class Bar(models.Model):")
+                     (progn (python-nav-forward-sexp) (point)))
+                    "# -*- coding: latin-1 -*-
+
+
+
+
+
+
+
+
+class Bar(models.Model):
+    pass"))))
+
+(ert-deftest python-shell-buffer-substring-6 ()
+  "Handle substring with coding cookie in the second line."
+  (python-tests-with-temp-buffer
+   "
+# coding: latin-1
+
+class Foo(models.Model):
+    pass
+
+if __name__ == \"__main__\":
+    foo = Foo()
+    print (foo)
+
+class Bar(models.Model):
+    pass
+"
+   (should (string= (python-shell-buffer-substring
+                     (python-tests-look-at "# coding: latin-1")
+                     (python-tests-look-at "if __name__ == \"__main__\":"))
+                    "# -*- coding: latin-1 -*-
+
+
+class Foo(models.Model):
+    pass
+
+"))))
+
+(ert-deftest python-shell-buffer-substring-7 ()
+  "Ensure first coding cookie gets precedence."
+  (python-tests-with-temp-buffer
+   "# coding: utf-8
+# coding: latin-1
+
+class Foo(models.Model):
+    pass
+
+if __name__ == \"__main__\":
+    foo = Foo()
+    print (foo)
+
+class Bar(models.Model):
+    pass
+"
+   (should (string= (python-shell-buffer-substring
+                     (python-tests-look-at "# coding: latin-1")
+                     (python-tests-look-at "if __name__ == \"__main__\":"))
+                    "# -*- coding: utf-8 -*-
+
+
+class Foo(models.Model):
+    pass
+
+"))))
+
+(ert-deftest python-shell-buffer-substring-8 ()
+  "Ensure first coding cookie gets precedence when sending whole buffer."
+  (python-tests-with-temp-buffer
+   "# coding: utf-8
+# coding: latin-1
+
+class Foo(models.Model):
+    pass
+"
+   (should (string= (python-shell-buffer-substring (point-min) (point-max))
+                    "# coding: utf-8
+
+
+class Foo(models.Model):
+    pass
+"))))
+
+(ert-deftest python-shell-buffer-substring-9 ()
+  "Check substring starting from `point-min'."
+  (python-tests-with-temp-buffer
+   "# coding: utf-8
+
+class Foo(models.Model):
+    pass
+
+class Bar(models.Model):
+    pass
+"
+   (should (string= (python-shell-buffer-substring
+                     (point-min)
+                     (python-tests-look-at "class Bar(models.Model):"))
+                    "# coding: utf-8
+
+class Foo(models.Model):
+    pass
+
+"))))
+
 
 ;;; Shell completion
 
+(ert-deftest python-shell-completion-native-interpreter-disabled-p-1 ()
+  (let* ((python-shell-completion-native-disabled-interpreters (list "pypy"))
+         (python-shell-interpreter "/some/path/to/bin/pypy"))
+    (should (python-shell-completion-native-interpreter-disabled-p))))
+
+
+
 
 ;;; PDB Track integration
 
@@ -3738,6 +3902,85 @@ foo = True  # another comment
    (forward-line 1)
    (should (python-info-current-line-empty-p))))
 
+(ert-deftest python-info-encoding-from-cookie-1 ()
+  "Should detect it on first line."
+  (python-tests-with-temp-buffer
+   "# coding=latin-1
+
+foo = True  # another comment
+"
+   (should (eq (python-info-encoding-from-cookie) 'latin-1))))
+
+(ert-deftest python-info-encoding-from-cookie-2 ()
+  "Should detect it on second line."
+  (python-tests-with-temp-buffer
+   "
+# coding=latin-1
+
+foo = True  # another comment
+"
+   (should (eq (python-info-encoding-from-cookie) 'latin-1))))
+
+(ert-deftest python-info-encoding-from-cookie-3 ()
+  "Should not be detected on third line (and following ones)."
+  (python-tests-with-temp-buffer
+   "
+
+# coding=latin-1
+foo = True  # another comment
+"
+   (should (not (python-info-encoding-from-cookie)))))
+
+(ert-deftest python-info-encoding-from-cookie-4 ()
+  "Should detect Emacs style."
+  (python-tests-with-temp-buffer
+   "# -*- coding: latin-1 -*-
+
+foo = True  # another comment"
+   (should (eq (python-info-encoding-from-cookie) 'latin-1))))
+
+(ert-deftest python-info-encoding-from-cookie-5 ()
+  "Should detect Vim style."
+  (python-tests-with-temp-buffer
+   "# vim: set fileencoding=latin-1 :
+
+foo = True  # another comment"
+   (should (eq (python-info-encoding-from-cookie) 'latin-1))))
+
+(ert-deftest python-info-encoding-from-cookie-6 ()
+  "First cookie wins."
+  (python-tests-with-temp-buffer
+   "# -*- coding: iso-8859-1 -*-
+# vim: set fileencoding=latin-1 :
+
+foo = True  # another comment"
+   (should (eq (python-info-encoding-from-cookie) 'iso-8859-1))))
+
+(ert-deftest python-info-encoding-from-cookie-7 ()
+  "First cookie wins."
+  (python-tests-with-temp-buffer
+   "# vim: set fileencoding=latin-1 :
+# -*- coding: iso-8859-1 -*-
+
+foo = True  # another comment"
+   (should (eq (python-info-encoding-from-cookie) 'latin-1))))
+
+(ert-deftest python-info-encoding-1 ()
+  "Should return the detected encoding from cookie."
+  (python-tests-with-temp-buffer
+   "# vim: set fileencoding=latin-1 :
+
+foo = True  # another comment"
+   (should (eq (python-info-encoding) 'latin-1))))
+
+(ert-deftest python-info-encoding-2 ()
+  "Should default to utf-8."
+  (python-tests-with-temp-buffer
+   "# No encoding for you
+
+foo = True  # another comment"
+   (should (eq (python-info-encoding) 'utf-8))))
+
 
 ;;; Utility functions
 
@@ -3767,7 +4010,7 @@ def foo(a, b, c):
             . "from IPython.core.completerlib import module_completion")
            (python-shell-completion-string-code
             . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
-           (python-shell-virtualenv-path
+           (python-shell-virtualenv-root
             . "/home/user/.virtualenvs/project"))))
     (with-current-buffer buffer
       (kill-all-local-variables)
diff --git a/test/automated/tramp-tests.el b/test/automated/tramp-tests.el
index c03b746..c59445c 100644
--- a/test/automated/tramp-tests.el
+++ b/test/automated/tramp-tests.el
@@ -953,7 +953,12 @@ This tests also `file-directory-p' and 
`file-accessible-directory-p'."
            (goto-char (point-min))
            (should
             (looking-at-p
-             "\\(total.+[[:digit:]]+\n\\)?.+ \\.\n.+ \\.\\.\n.+ foo$"))))
+             (concat
+              ;; There might be a summary line.
+              "\\(total.+[[:digit:]]+\n\\)?"
+              ;; We don't know in which order "." and ".." appear.
+              "\\(.+ \\.?\\.\n\\)\\{2\\}"
+              ".+ foo$")))))
       (ignore-errors (delete-directory tmp-name1 'recursive)))))
 
 (ert-deftest tramp-test18-file-attributes ()



reply via email to

[Prev in Thread] Current Thread [Next in Thread]